/****** Object:  ForeignKey [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels] DROP CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]'))
ALTER TABLE [dbo].[TA_Tbl_AuditField] DROP CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] DROP CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] DROP CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] DROP CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] DROP CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__Appro__5A129A75]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Appro__5A129A75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__empid__5B06BEAE]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__empid__5B06BEAE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__Rejec__5BFAE2E7]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Rejec__5BFAE2E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]'))
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters] DROP CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]'))
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate] DROP CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]'))
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] DROP CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]'))
ALTER TABLE [dbo].[TA_Tbl_Encashment] DROP CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] DROP CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] DROP CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]'))
ALTER TABLE [dbo].[TA_Tbl_Holiday] DROP CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Ho__Holid__20589827]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Ho__Holid__20589827]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]'))
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable] DROP CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] DROP CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]
GO
/****** Object:  ForeignKey [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_levelDetails_TA_Tbl_Level]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]'))
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] DROP CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]
GO
/****** Object:  ForeignKey [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]'))
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail] DROP CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]'))
ALTER TABLE [dbo].[TA_Tbl_MonthClosure] DROP CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails] DROP CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails] DROP CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]'))
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation] DROP CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]'))
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] DROP CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] DROP CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] DROP CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster] DROP CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__logid__62E4AA3C]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__logid__62E4AA3C]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild] DROP CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__Templ__63D8CE75]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__63D8CE75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] DROP CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__Templ__64CCF2AE]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__64CCF2AE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] DROP CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE]
GO
/****** Object:  ForeignKey [FK__Ta_Tbl_SM__Templ__65C116E7]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__65C116E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] DROP CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7]
GO
/****** Object:  ForeignKey [FK__Ta_Tbl_SM__Templ__66B53B20]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__66B53B20]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters] DROP CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels] DROP CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
/****** Object:  ForeignKey [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels] DROP CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails] DROP CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Title_TA_Tbl_Grade]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_TA_Tbl_Grade]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Others]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CCGroup_Others]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Planned]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CCGroup_Planned]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_UnPlanned]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned] DROP CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] DROP CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] DROP CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CCMailGroup]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempPayrollProcessDetails]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails] DROP CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessDetails]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails] DROP CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PayrollProcessDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessLeaveDetails]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails] DROP CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_YearClosure]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Carry_PrevYear]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Carry_PrevYear]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Current_Quota]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Current_Quota]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Borrow_NextYear]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Borrow_NextYear]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Leave_Taken]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Leave_Taken]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Available_Leaves]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Available_Leaves]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Encashment]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Encashment]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearClosure_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearClosure] DROP CONSTRAINT [DF_TA_Tbl_YearClosure_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_YearClosure]
GO
/****** Object:  Table [dbo].[TA_Tbl_Title]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_TA_Tbl_Grade]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Title_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [DF_TA_Tbl_Title_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Title_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Title] DROP CONSTRAINT [DF_TA_Tbl_Title_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Title]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftPattern]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] DROP CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] DROP CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ShiftPattern]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftRoaster]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster] DROP CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ShiftRoaster]
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogChild]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__logid__62E4AA3C]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild] DROP CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_SMSLogChild]
GO
/****** Object:  Table [dbo].[TA_Tbl_RouteMaster]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Ro__IsDel__652525C5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [DF__TA_Tbl_Ro__IsDel__652525C5]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_RouteMaster_IsMapped]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] DROP CONSTRAINT [DF_TA_Tbl_RouteMaster_IsMapped]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_RouteMaster]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditOperation]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] DROP CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] DROP CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_AuditOpr_OprDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] DROP CONSTRAINT [DF_TA_Tbl_AuditOpr_OprDate]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AuditOperation]
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicyDetails]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Emp_LeavePolicyDetails_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [DF_TA_Tbl_Emp_LeavePolicyDetails_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Em__MaxDa__5AA79752]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] DROP CONSTRAINT [DF__TA_Tbl_Em__MaxDa__5AA79752]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidayChildTable]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Ho__Holid__20589827]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]'))
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable] DROP CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_HolidayChildTable]
GO
/****** Object:  Table [dbo].[TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]'))
ALTER TABLE [dbo].[TA_Tbl_MonthClosure] DROP CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_MonthClosure_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_MonthClosure] DROP CONSTRAINT [DF_TA_Tbl_MonthClosure_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_MonthClosure]
GO
/****** Object:  Table [dbo].[Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_levelDetails_TA_Tbl_Level]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]'))
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] DROP CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_le__isDel__5306758A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] DROP CONSTRAINT [DF__Ta_Tbl_le__isDel__5306758A]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_levelDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailTemplate]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]'))
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate] DROP CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmailTemplate]
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Emp_LeavePolicy_Time_stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [DF_TA_Tbl_Emp_LeavePolicy_Time_stamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[TA_Tbl_Emp_LeavePolicy_AutoCredit]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] DROP CONSTRAINT [TA_Tbl_Emp_LeavePolicy_AutoCredit]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Emp_LeavePolicy]
GO
/****** Object:  Table [dbo].[TA_Tbl_Encashment]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]'))
ALTER TABLE [dbo].[TA_Tbl_Encashment] DROP CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Encashment_DateOfEncashment]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Encashment] DROP CONSTRAINT [DF_TA_Tbl_Encashment_DateOfEncashment]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Encashment]
GO
/****** Object:  Table [dbo].[TA_Tbl_Holiday]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]'))
ALTER TABLE [dbo].[TA_Tbl_Holiday] DROP CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Holiday]
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance_INOUTDetails]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] DROP CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] DROP CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_Compensation]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Appro__5A129A75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__empid__5B06BEAE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Rejec__5BFAE2E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Co__TimeS__5CEF0720]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Compensation] DROP CONSTRAINT [DF__TA_Tbl_Co__TimeS__5CEF0720]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Compensation]
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels] DROP CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditField]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]'))
ALTER TABLE [dbo].[TA_Tbl_AuditField] DROP CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AuditField]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduleFilters]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]'))
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters] DROP CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmailScheduleFilters]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmpChildrenDetails]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]'))
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] DROP CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmpChildrenDetails_Time_stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] DROP CONSTRAINT [DF_TA_Tbl_EmpChildrenDetails_Time_stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmpChildrenDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeBonusLeave]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeeBonusLeave_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] DROP CONSTRAINT [DF_TA_Tbl_EmployeeBonusLeave_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]
GO
/****** Object:  Table [dbo].[TA_Tbl_PunchTypes]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]'))
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] DROP CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Pun__Flag__2BECA869]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] DROP CONSTRAINT [DF__TA_Tbl_Pun__Flag__2BECA869]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PunchTypes]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermissionConversation]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]'))
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation] DROP CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermissionConversation_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation] DROP CONSTRAINT [DF_TA_Tbl_PermissionConversation_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PermissionConversation]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicyDetails]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeavePolicyDetails_ApplicableAfterDays]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_ApplicableAfterDays]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeavePolicyDetails_Time_stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_Time_stamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Le__Avail__502A08DF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] DROP CONSTRAINT [DF__TA_Tbl_Le__Avail__502A08DF]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeavePolicyDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePrivateNotes]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] DROP CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_TA_Tbl_LeavePrivateNotes_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] DROP CONSTRAINT [DF_TA_TA_Tbl_LeavePrivateNotes_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeavePrivateNotes]
GO
/****** Object:  Table [dbo].[TA_tbl_MailIdsForTriggeringEmail]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]'))
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail] DROP CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]') AND type in (N'U'))
DROP TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocation]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day1Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day1Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day2Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day2Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day3Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day3Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day4Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day4Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day5Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day5Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day6Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day6Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day7Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day7Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day8Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day8Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day9Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day9Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day10Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day10Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day11Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day11Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day12Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day12Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day13Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day13Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day14Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day14Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day15Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day15Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day16Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day16Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day17Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day17Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day18Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day18Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day19Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day19Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day20Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day20Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day21Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day21Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day22Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day22Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day23Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day23Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day24Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day24Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day25Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day25Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day26Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day26Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day27Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day27Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day28Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day28Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day29Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day29Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day30Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day30Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_Day31Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day31Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_PermanentShiftAllocation_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PermanentShiftAllocation]
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogDetails]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__63D8CE75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] DROP CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__64CCF2AE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] DROP CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_SMSLogDetails]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSReceivers]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__65C116E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] DROP CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7]
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_SM__TimeS__2DD4F0DB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] DROP CONSTRAINT [DF__Ta_Tbl_SM__TimeS__2DD4F0DB]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_SMSReceivers]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplateFilters]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__66B53B20]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters] DROP CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_SMSTemplateFilters]
GO
/****** Object:  Table [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels] DROP CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels] DROP CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocation]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day1Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day1Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day2Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day2Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day3Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day3Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day4Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day4Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day5Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day5Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day6Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day6Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day7Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day7Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day8Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day8Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day9Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day9Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day10Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day10Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day11Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day11Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day12Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day12Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day13Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day13Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day14Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day14Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day15Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day15Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day16Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day16Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day17Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day17Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day18Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day18Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day19Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day19Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day20Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day20Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day21Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day21Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day22Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day22Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day23Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day23Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day24Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day24Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day25Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day25Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day26Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day26Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day27Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day27Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day28Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day28Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day29Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day29Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day30Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day30Shift]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TemporaryShiftAllocation_Day31Shift]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation] DROP CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day31Shift]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemporaryShiftAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocationbkup]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemporaryShiftAllocationbkup]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TemporaryShiftAllocationbkup]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempGroupPolicyAllocation]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempGroupPolicyAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TempGroupPolicyAllocation]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempInsertEmployee]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempInsertEmployee]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TempInsertEmployee]
GO
/****** Object:  Table [dbo].[ta_tbl_PenaltyPercentage]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PenaltyPercentage]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_PenaltyPercentage]
GO
/****** Object:  Table [dbo].[TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_YearSetting_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_YearSetting] DROP CONSTRAINT [DF_TA_Tbl_YearSetting_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearSetting]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_YearSetting]
GO
/****** Object:  Table [dbo].[tb_reportslist]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_reportslist]') AND type in (N'U'))
DROP TABLE [dbo].[tb_reportslist]
GO
/****** Object:  Table [dbo].[Tbl_TempEmployeeShiftTime]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tbl_TempEmployeeShiftTime]') AND type in (N'U'))
DROP TABLE [dbo].[Tbl_TempEmployeeShiftTime]
GO
/****** Object:  Table [dbo].[TblAnalysisReport]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TblAnalysisReport]') AND type in (N'U'))
DROP TABLE [dbo].[TblAnalysisReport]
GO
/****** Object:  Table [dbo].[TempApprovalSettings]    Script Date: 03/25/2021 10:16:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempApprovalSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TempApprovalSettings]
GO
/****** Object:  Table [dbo].[TempEmployee]    Script Date: 03/25/2021 10:16:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempEmployee]') AND type in (N'U'))
DROP TABLE [dbo].[TempEmployee]
GO
/****** Object:  Table [dbo].[TempTitle]    Script Date: 03/25/2021 10:16:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempTitle]') AND type in (N'U'))
DROP TABLE [dbo].[TempTitle]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplates]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_SM__LastM__5CC4E9EE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplates] DROP CONSTRAINT [DF__Ta_Tbl_SM__LastM__5CC4E9EE]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_SM__ToEmp__5DB90E27]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplates] DROP CONSTRAINT [DF__Ta_Tbl_SM__ToEmp__5DB90E27]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplates]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_SMSTemplates]
GO
/****** Object:  Table [dbo].[Ta_tbl_specialOvertimeDetails]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_specialOvertimeDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_specialOvertimeDetails]
GO
/****** Object:  Table [dbo].[Ta_tbl_TaskProgressDetails]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_TaskProgressDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_TaskProgressDetails]
GO
/****** Object:  Table [dbo].[ta_tbl_taskprogressStatus]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_taskprogressStatus]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_taskprogressStatus]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTags]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_SM__Times__7D66C3AA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_SMSTags] DROP CONSTRAINT [DF__Ta_Tbl_SM__Times__7D66C3AA]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTags]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_SMSTags]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftSettings]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__MaxWo__7100ECC5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__MaxWo__7100ECC5]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__Flexi__28ED12D1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__Flexi__28ED12D1]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__Flexi__29E1370A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__Flexi__29E1370A]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__Flexi__2AD55B43]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__Flexi__2AD55B43]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__First__74D17DA9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__First__74D17DA9]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__Carry__75C5A1E2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF__TA_Tbl_Sh__Carry__75C5A1E2]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraint1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [Defaultconstraint1]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraints2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [Defaultconstraints2]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ShiftSettings_EarlyExitMinsPerDay]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitMinsPerDay]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ShiftSettings_EarlyExitDaysPerMonth]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitDaysPerMonth]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraints1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftSettings] DROP CONSTRAINT [Defaultconstraints1]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ShiftSettings]
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSGateway]    Script Date: 03/25/2021 10:16:52 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Ta_Tbl_SM__TimeS__6E24801A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_SMSGateway] DROP CONSTRAINT [DF__Ta_Tbl_SM__TimeS__6E24801A]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSGateway]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_SMSGateway]
GO
/****** Object:  Table [dbo].[TA_Tbl_TitleMapping]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_TitleMapping_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TitleMapping] DROP CONSTRAINT [DF_TA_Tbl_TitleMapping_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TitleMapping]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TitleMapping]
GO
/****** Object:  Table [dbo].[ta_tbl_TotalBreakHours]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_TotalBreakHours]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_TotalBreakHours]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Trace]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Trace]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_Trace]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Transportation]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Mapping]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Transportation_Mapping_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Transportation_Mapping] DROP CONSTRAINT [DF_TA_Tbl_Transportation_Mapping_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Mapping]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Transportation_Mapping]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Route]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Transportation_Route_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Transportation_Route] DROP CONSTRAINT [DF_TA_Tbl_Transportation_Route_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Route]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Transportation_Route]
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Vehicle]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Transportation_Vehicle_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Transportation_Vehicle] DROP CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Transportation_Vehicle_Time_stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Transportation_Vehicle] DROP CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_Time_stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Vehicle]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Transportation_Vehicle]
GO
/****** Object:  Table [dbo].[TA_Tbl_Type]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Type]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Type]
GO
/****** Object:  Table [dbo].[TA_Tbl_Usergroup]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Usergroup_timeStamp_2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Usergroup] DROP CONSTRAINT [DF_TA_Tbl_Usergroup_timeStamp_2]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Usergroup_isDeleted_1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Usergroup] DROP CONSTRAINT [DF_TA_Tbl_Usergroup_isDeleted_1]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Usergroup_ReportsBasedOn]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Usergroup] DROP CONSTRAINT [DF_TA_Tbl_Usergroup_ReportsBasedOn]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Usergroup]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Usergroup]
GO
/****** Object:  Table [dbo].[TA_Tbl_userRights]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_userGroup_isDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_userRights] DROP CONSTRAINT [DF_TA_Tbl_userGroup_isDeleted]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_userGroup_timeStamp_1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_userRights] DROP CONSTRAINT [DF_TA_Tbl_userGroup_timeStamp_1]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_userRights]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_userRights]
GO
/****** Object:  Table [dbo].[TA_Tbl_Version]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Version]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Version]
GO
/****** Object:  Table [dbo].[TA_Tbl_WindowsServiceFlag]    Script Date: 03/25/2021 10:16:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_WindowsServiceFlag]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_WindowsServiceFlag]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempShiftAllocation]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempShiftAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TempShiftAllocation]
GO
/****** Object:  Table [dbo].[TA_Tbl_TempUpdateEmployee]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempUpdateEmployee]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TempUpdateEmployee]
GO
/****** Object:  Table [dbo].[TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Te__TimeS__5523C826]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_TemWeekday] DROP CONSTRAINT [DF__TA_Tbl_Te__TimeS__5523C826]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemWeekday]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TemWeekday]
GO
/****** Object:  Table [dbo].[TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Terminal_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Terminal] DROP CONSTRAINT [DF_TA_Tbl_Terminal_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Terminal]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Terminal]
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalBrand]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TerminalBrand]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TerminalBrand]
GO
/****** Object:  Table [dbo].[TA_tbl_TerminalDatatype]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_TerminalDatatype]') AND type in (N'U'))
DROP TABLE [dbo].[TA_tbl_TerminalDatatype]
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalMapping]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TerminalMapping]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_TerminalMapping]
GO
/****** Object:  Table [dbo].[Ta_tbl_TimeZones]    Script Date: 03/25/2021 10:16:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_TimeZones]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_TimeZones]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationbck]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocationbck]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PermanentShiftAllocationbck]
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]
GO
/****** Object:  Table [dbo].[TA_Tbl_Permission]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Permission_Permission_AppliedDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Permission] DROP CONSTRAINT [DF_TA_Tbl_Permission_Permission_AppliedDate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Permission_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Permission] DROP CONSTRAINT [DF_TA_Tbl_Permission_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Pe__UnPla__181AB9E6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Permission] DROP CONSTRAINT [DF__TA_Tbl_Pe__UnPla__181AB9E6]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Permission]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Permission]
GO
/****** Object:  Table [dbo].[TA_Tbl_ManualTimeEntry]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry] DROP CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry] DROP CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ManualTimeEntry_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ManualTimeEntry] DROP CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ManualTimeEntry]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ManualTimeEntry]
GO
/****** Object:  Table [dbo].[Ta_Tbl_ManualTimeEntrybck]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_ManualTimeEntrybck]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_ManualTimeEntrybck]
GO
/****** Object:  Table [dbo].[ta_tbl_MatchedPunches]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_MatchedPunches]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_MatchedPunches]
GO
/****** Object:  Table [dbo].[Ta_tbl_mobileClockInAndOut]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_mobileClockInAndOut]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_mobileClockInAndOut]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveSettings]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveSettings]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeaveType_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeaveType] DROP CONSTRAINT [DF_TA_Tbl_LeaveType_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Le__Count__026082F1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeaveType] DROP CONSTRAINT [DF__TA_Tbl_Le__Count__026082F1]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveType]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveType]
GO
/****** Object:  Table [dbo].[TA_Tbl_Level]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Level_parentLevelID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Level] DROP CONSTRAINT [DF_TA_Tbl_Level_parentLevelID]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Le__isDel__7E8FF20D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Level] DROP CONSTRAINT [DF__TA_Tbl_Le__isDel__7E8FF20D]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Level]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Level]
GO
/****** Object:  Table [dbo].[TA_Tbl_Preferences]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Preferences]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Preferences]
GO
/****** Object:  Table [dbo].[ta_tbl_PrevPermissionDetails_EastMan]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ta_tbl_Pr__Times__2574B504]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ta_tbl_PrevPermissionDetails_EastMan] DROP CONSTRAINT [DF__ta_tbl_Pr__Times__2574B504]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PrevPermissionDetails_EastMan]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_PrevPermissionDetails_EastMan]
GO
/****** Object:  Table [dbo].[TA_Tbl_ProcessedData]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ProcessedData_ProcessFlag]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ProcessedData] DROP CONSTRAINT [DF_TA_Tbl_ProcessedData_ProcessFlag]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ProcessedData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ProcessedData]
GO
/****** Object:  Table [dbo].[TA_Tbl_Project]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Project_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Project] DROP CONSTRAINT [DF_TA_Tbl_Project_IsDeleted]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Project]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Project]
GO
/****** Object:  Table [dbo].[TA_tbl_ProjectTaskList]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_ProjectTaskList]') AND type in (N'U'))
DROP TABLE [dbo].[TA_tbl_ProjectTaskList]
GO
/****** Object:  Table [dbo].[TA_Tbl_ProjectTerminals]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ProjectTerminals]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ProjectTerminals]
GO
/****** Object:  Table [dbo].[ta_tbl_PunchtypeRemarks]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ta_tbl_Pu__Times__403C232B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ta_tbl_PunchtypeRemarks] DROP CONSTRAINT [DF__ta_tbl_Pu__Times__403C232B]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PunchtypeRemarks]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_PunchtypeRemarks]
GO
/****** Object:  Table [dbo].[Ta_tbl_ReasonForNonProcessedData]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_ReasonForNonProcessedData]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_ReasonForNonProcessedData]
GO
/****** Object:  Table [dbo].[TA_Tbl_Religion]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Religion]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Religion]
GO
/****** Object:  Table [dbo].[TA_Tbl_Results]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Results]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Results]
GO
/****** Object:  Table [dbo].[TA_Tbl_Shift]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Sh__empCa__06F02DE4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Shift] DROP CONSTRAINT [DF__TA_Tbl_Sh__empCa__06F02DE4]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraint_WorkHours]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Shift] DROP CONSTRAINT [Defaultconstraint_WorkHours]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Shift]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Shift]
GO
/****** Object:  Table [dbo].[TA_tbl_ShiftAdd_Location]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_tbl_ShiftAdd_Location_CreatedOn]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_tbl_ShiftAdd_Location] DROP CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_CreatedOn]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_tbl_ShiftAdd_Location_ModifiedOn]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_tbl_ShiftAdd_Location] DROP CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_ModifiedOn]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_ShiftAdd_Location]') AND type in (N'U'))
DROP TABLE [dbo].[TA_tbl_ShiftAdd_Location]
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftExchange]    Script Date: 03/25/2021 10:16:51 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ShiftExchange_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ShiftExchange] DROP CONSTRAINT [DF_TA_Tbl_ShiftExchange_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftExchange]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ShiftExchange]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeCategory]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeeCategory_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeeCategory] DROP CONSTRAINT [DF_TA_Tbl_EmployeeCategory_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeCategory]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeCategory]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeDesignation]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeeDesignation_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeeDesignation] DROP CONSTRAINT [DF_TA_Tbl_EmployeeDesignation_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeDesignation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeDesignation]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeEntrance]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeEntrance]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeEntrance]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLevel]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeeLevel_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeeLevel] DROP CONSTRAINT [DF_TA_Tbl_EmployeeLevel_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeLevel]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeLevel]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLingual]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeLingual]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeLingual]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeePay]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeePay_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeePay] DROP CONSTRAINT [DF_TA_Tbl_EmployeePay_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeePay]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeePay]
GO
/****** Object:  Table [dbo].[Ta_Tbl_EmployeePunch]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_EmployeePunch]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_EmployeePunch]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeType]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmployeeType_Timestamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmployeeType] DROP CONSTRAINT [DF_TA_Tbl_EmployeeType_Timestamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeType]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmployeeType]
GO
/****** Object:  Table [dbo].[TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_DateofBirth]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_DateofBirth_Record]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth_Record]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_Passport_expirydate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_Passport_expirydate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_Visa_expirydate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_Visa_expirydate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_Anniversary_Date]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_Anniversary_Date]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_DateOfJoining]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_DateOfJoining]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Employee_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [DF_TA_Tbl_Employee_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraint]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [Defaultconstraint]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraint2]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Employee] DROP CONSTRAINT [Defaultconstraint2]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Employee]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Employee]
GO
/****** Object:  Table [dbo].[TA_tbl_EmailScheduleStatus]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_EmailScheduleStatus]') AND type in (N'U'))
DROP TABLE [dbo].[TA_tbl_EmailScheduleStatus]
GO
/****** Object:  Table [dbo].[TA_TBL_EmailScripts]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_TBL_EmailScripts]') AND type in (N'U'))
DROP TABLE [dbo].[TA_TBL_EmailScripts]
GO
/****** Object:  Table [dbo].[TA_Tbl_ApprovalSettings]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Ap__webCl__4DB7B088]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ApprovalSettings] DROP CONSTRAINT [DF__TA_Tbl_Ap__webCl__4DB7B088]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ApprovalSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ApprovalSettings]
GO
/****** Object:  Table [dbo].[TA_Tbl_AttandanceCode]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_AttandanceCode_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_AttandanceCode] DROP CONSTRAINT [DF_TA_Tbl_AttandanceCode_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AttandanceCode]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AttandanceCode]
GO
/****** Object:  Table [dbo].[TA_Tbl_AttendenceData]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AttendenceData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AttendenceData]
GO
/****** Object:  Table [dbo].[TA_Tbl_ChangePassword]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ChangePassword]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ChangePassword]
GO
/****** Object:  Table [dbo].[TA_Tbl_Clk_RawData]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Clk_RawData_CLK_PROCESS]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Clk_RawData] DROP CONSTRAINT [DF_TA_Tbl_Clk_RawData_CLK_PROCESS]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Cl__TimeS__470AB2F9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Clk_RawData] DROP CONSTRAINT [DF__TA_Tbl_Cl__TimeS__470AB2F9]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Clk_RawData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Clk_RawData]
GO
/****** Object:  Table [dbo].[TA_Tbl_ClockDetails]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ClockDetails_IsVoid]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ClockDetails] DROP CONSTRAINT [DF_TA_Tbl_ClockDetails_IsVoid]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ClockDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ClockDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_CMITechSyncEmployeeInfo]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CMITechSyncEmployeeInfo]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CMITechSyncEmployeeInfo]
GO
/****** Object:  Table [dbo].[TA_Tbl_CompanyGroup]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CompanyGroup]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CompanyGroup]
GO
/****** Object:  Table [dbo].[TA_Tbl_ConcurrentUser]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ConcurrentUser]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ConcurrentUser]
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardData]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_DashboardData]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_DashboardData]
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardUserrights]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_DashboardUserrights]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_DashboardUserrights]
GO
/****** Object:  Table [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]
GO
/****** Object:  Table [dbo].[TA_Tbl_DataProcessTemp]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_DataProcessTemp]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_DataProcessTemp]
GO
/****** Object:  Table [dbo].[TA_Tbl_DateandTimeFormat]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_DateandTimeFormat]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_DateandTimeFormat]
GO
/****** Object:  Table [dbo].[TA_Tbl_Demo]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Demo]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Demo]
GO
/****** Object:  Table [dbo].[Ta_Tbl_DeviceLogTableDetails]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_DeviceLogTableDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_DeviceLogTableDetails]
GO
/****** Object:  Table [dbo].[Ta_tbl_DeviceServerDetails]    Script Date: 03/25/2021 10:16:43 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_DeviceServerDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_DeviceServerDetails]
GO
/****** Object:  Table [dbo].[Ta_tbl_EmailReportNotSendedDetails]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_EmailReportNotSendedDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_EmailReportNotSendedDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_EmailSchedule_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmailSchedule] DROP CONSTRAINT [DF_TA_Tbl_EmailSchedule_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Em__ToWho__30274DA1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmailSchedule] DROP CONSTRAINT [DF__TA_Tbl_Em__ToWho__30274DA1]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Em__TimeS__311B71DA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_EmailSchedule] DROP CONSTRAINT [DF__TA_Tbl_Em__TimeS__311B71DA]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailSchedule]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmailSchedule]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduled_Employees]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduled_Employees]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_EmailScheduled_Employees]
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditTable]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AuditTable]
GO
/****** Object:  Table [dbo].[TA_Tbl_AutoShiftConfiguration]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_AutoShiftConfiguration_CreatedDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] DROP CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_CreatedDate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_AutoShiftConfiguration_ModifiedDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] DROP CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_ModifiedDate]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Defaultconstraints5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_AutoShiftConfiguration] DROP CONSTRAINT [Defaultconstraints5]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AutoShiftConfiguration]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AutoShiftConfiguration]
GO
/****** Object:  Table [dbo].[Ta_Tbl_Branding]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Branding]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_Branding]
GO
/****** Object:  Table [dbo].[TA_Tbl_Category]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Category]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Category]
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_ODApproval]    Script Date: 03/25/2021 10:16:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_ODApproval]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_CCGroup_ODApproval]
GO
/****** Object:  Table [dbo].[AutoLeaveupdation]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AutoLeaveupdation]') AND type in (N'U'))
DROP TABLE [dbo].[AutoLeaveupdation]
GO
/****** Object:  Table [dbo].[ImportFromExcel]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ImportFromExcel]') AND type in (N'U'))
DROP TABLE [dbo].[ImportFromExcel]
GO
/****** Object:  Table [dbo].[Proc_ImportOvertime]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ImportOvertime]') AND type in (N'U'))
DROP TABLE [dbo].[Proc_ImportOvertime]
GO
/****** Object:  Table [dbo].[TA_ExportData_CustomFormat]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_ExportData_CustomFormat]') AND type in (N'U'))
DROP TABLE [dbo].[TA_ExportData_CustomFormat]
GO
/****** Object:  Table [dbo].[TA_ExportData_FieldData]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_ExportData_FieldData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_ExportData_FieldData]
GO
/****** Object:  Table [dbo].[TA_Tbl_AccessDeniedSettings]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AccessDeniedSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_AccessDeniedSettings]
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff]    Script Date: 03/25/2021 10:16:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Additional_WeeklyOff]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrLog]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ErrLog_TimestampRec]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ErrLog] DROP CONSTRAINT [DF_TA_Tbl_ErrLog_TimestampRec]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrLog]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ErrLog]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ClockRawData]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ErrorLog_ClockRawData_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ErrorLog_ClockRawData] DROP CONSTRAINT [DF_TA_Tbl_ErrorLog_ClockRawData_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrorLog_ClockRawData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ErrorLog_ClockRawData]
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ProcessedData]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_ErrorLog_ProcessedData_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_ErrorLog_ProcessedData] DROP CONSTRAINT [DF_TA_Tbl_ErrorLog_ProcessedData_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrorLog_ProcessedData]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ErrorLog_ProcessedData]
GO
/****** Object:  Table [dbo].[Ta_tbl_ExistingRightsDetails]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_ExistingRightsDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_ExistingRightsDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_ExportDataCentena]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ExportDataCentena]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ExportDataCentena]
GO
/****** Object:  Table [dbo].[TA_Tbl_GlobalWeekdaySettings]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_GlobalWeekdaySettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_GlobalWeekdaySettings]
GO
/****** Object:  Table [dbo].[ta_tbl_GraceDetails]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_GraceDetails]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_GraceDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_Grade]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Grade_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Grade] DROP CONSTRAINT [DF_TA_Tbl_Grade_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Grade]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Grade]
GO
/****** Object:  Table [dbo].[TA_Tbl_GroupDetails]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_GroupDetails]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_GroupDetails]
GO
/****** Object:  Table [dbo].[ta_tbl_HelpContent]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_HelpContent]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_HelpContent]
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance]    Script Date: 03/25/2021 10:16:45 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Entrance_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Entrance] DROP CONSTRAINT [DF_TA_Tbl_Entrance_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Ent__Flag__0A01A4B9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Entrance] DROP CONSTRAINT [DF__TA_Tbl_Ent__Flag__0A01A4B9]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Entrance]
GO
/****** Object:  Table [dbo].[ta_tbl_emp_LeaveTypedetails]    Script Date: 03/25/2021 10:16:44 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ta_tbl_em__IsDel__063113D5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ta_tbl_emp_LeaveTypedetails] DROP CONSTRAINT [DF__ta_tbl_em__IsDel__063113D5]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_emp_LeaveTypedetails]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_emp_LeaveTypedetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidaySettings]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidaySettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_HolidaySettings]
GO
/****** Object:  Table [dbo].[Ta_Tbl_ImportMasterData]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Ta_Tbl_ImportMasterData_Employee_Status]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Ta_Tbl_ImportMasterData] DROP CONSTRAINT [DF_Ta_Tbl_ImportMasterData_Employee_Status]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_ImportMasterData]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_ImportMasterData]
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportMasterError]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ImportMasterError]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ImportMasterError]
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportShiftAllocation]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ImportShiftAllocation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ImportShiftAllocation]
GO
/****** Object:  Table [dbo].[Ta_tbl_LandMarks]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_LandMarks]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_LandMarks]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveAnalysisNotes]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeaveAnalysisNotes_DateInserted_1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes] DROP CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_DateInserted_1]
END
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeaveAnalysisNotes_IsDeleted_1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes] DROP CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_IsDeleted_1]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveAnalysisNotes]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplication]    Script Date: 03/25/2021 10:16:46 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplication]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveApplication]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationExists]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationExists]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveApplicationExists]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationMaster]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationMaster]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveApplicationMaster]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveConversation]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeaveConversation_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeaveConversation] DROP CONSTRAINT [DF_TA_Tbl_LeaveConversation_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveConversation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeaveConversation]
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_LeavePolicy_Time_Stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_LeavePolicy] DROP CONSTRAINT [DF_TA_Tbl_LeavePolicy_Time_Stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicy]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LeavePolicy]
GO
/****** Object:  Table [dbo].[TA_Tbl_LevelRights]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LevelRights]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LevelRights]
GO
/****** Object:  Table [dbo].[TA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LIC_Details]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LIC_Details]
GO
/****** Object:  Table [dbo].[TA_Tbl_LicenseRequestDetail]    Script Date: 03/25/2021 10:16:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LicenseRequestDetail]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LicenseRequestDetail]
GO
/****** Object:  Table [dbo].[TA_Tbl_LockLogin]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LockLogin]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_LockLogin]
GO
/****** Object:  Table [dbo].[ta_tbl_LogDownloaded]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_LogDownloaded]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_LogDownloaded]
GO
/****** Object:  Table [dbo].[TA_Tbl_Login]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Login]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Login]
GO
/****** Object:  Table [dbo].[TA_Tbl_Lookup]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_Lookup_Time_stamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_Lookup] DROP CONSTRAINT [DF_TA_Tbl_Lookup_Time_stamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Lookup]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Lookup]
GO
/****** Object:  Table [dbo].[TA_Tbl_MailConfiguration]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__TA_Tbl_Ma__isReq__5D2EFE42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_MailConfiguration] DROP CONSTRAINT [DF__TA_Tbl_Ma__isReq__5D2EFE42]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MailConfiguration]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_MailConfiguration]
GO
/****** Object:  Table [dbo].[TA_Tbl_MultiLingual]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MultiLingual]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_MultiLingual]
GO
/****** Object:  Table [dbo].[TA_Tbl_NewsEvents]    Script Date: 03/25/2021 10:16:48 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_NewsEvents_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_NewsEvents] DROP CONSTRAINT [DF_TA_Tbl_NewsEvents_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_NewsEvents]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_NewsEvents]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Armis]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_Armis]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Armis]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]') AND type in (N'U'))
DROP TABLE [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]
GO
/****** Object:  Table [dbo].[Ta_tbl_NotProcessedDataDetails]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_NotProcessedDataDetails]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_tbl_NotProcessedDataDetails]
GO
/****** Object:  Table [dbo].[TA_Tbl_OnDutyConversation]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OnDutyConversation]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_OnDutyConversation]
GO
/****** Object:  Table [dbo].[TA_Tbl_OndutyEntry]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OndutyEntry]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_OndutyEntry]
GO
/****** Object:  Table [dbo].[TA_Tbl_OTRoundoffSettings]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OTRoundoffSettings]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_OTRoundoffSettings]
GO
/****** Object:  Table [dbo].[TA_Tbl_OtType]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_TA_Tbl_OtType_TimeStamp]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[TA_Tbl_OtType] DROP CONSTRAINT [DF_TA_Tbl_OtType_TimeStamp]
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OtType]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_OtType]
GO
/****** Object:  Table [dbo].[TA_Tbl_OverTimeStatus]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OverTimeStatus]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_OverTimeStatus]
GO
/****** Object:  Table [dbo].[TA_Tbl_Page]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Page]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_Page]
GO
/****** Object:  Table [dbo].[TA_Tbl_PageError]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PageError]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PageError]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageMandatoryFlag]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageMandatoryFlag]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_PageMandatoryFlag]
GO
/****** Object:  Table [dbo].[TA_Tbl_PageMandatoryFlagStandard]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PageMandatoryFlagStandard]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_PageMandatoryFlagStandard]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirect]    Script Date: 03/25/2021 10:16:49 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageRedirect]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_PageRedirect]
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirectStandard]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageRedirectStandard]') AND type in (N'U'))
DROP TABLE [dbo].[Ta_Tbl_PageRedirectStandard]
GO
/****** Object:  Table [dbo].[TA_Tbl_ParentIDs]    Script Date: 03/25/2021 10:16:50 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ParentIDs]') AND type in (N'U'))
DROP TABLE [dbo].[TA_Tbl_ParentIDs]
GO
/****** Object:  Table [dbo].[TA_Tbl_ParentIDs]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ParentIDs]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ParentIDs](
	[LevelID] [int] NOT NULL,
	[LevelName] [nvarchar](50) NULL,
	[pid] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirectStandard]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageRedirectStandard]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_PageRedirectStandard](
	[ID] [float] NULL,
	[PageId] [int] NULL,
	[TableName] [varchar](100) NULL,
	[Page] [varchar](500) NULL,
	[PageFullPath] [varchar](500) NULL,
	[Module] [varchar](150) NULL,
	[Rows] [int] NULL,
	[Active] [bit] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageRedirect]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageRedirect]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_PageRedirect](
	[ID] [float] NULL,
	[PageId] [int] NULL,
	[TableName] [varchar](100) NULL,
	[Page] [varchar](500) NULL,
	[PageFullPath] [varchar](500) NULL,
	[Module] [varchar](150) NULL,
	[Rows] [int] NULL,
	[Active] [bit] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_PageMandatoryFlagStandard]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PageMandatoryFlagStandard]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PageMandatoryFlagStandard](
	[MandatoryChecking] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_PageMandatoryFlag]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_PageMandatoryFlag]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_PageMandatoryFlag](
	[MandatoryChecking] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_PageError]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PageError]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PageError](
	[ErrorId] [bigint] IDENTITY(1,1) NOT NULL,
	[ErrorMsg] [varchar](max) NULL,
	[ErrorDetails] [varchar](max) NULL,
	[PageName] [varchar](150) NULL,
	[ProductName] [varchar](100) NULL,
	[ProductVersion] [varchar](25) NULL,
	[ClientName] [varchar](260) NULL,
	[TrackingPlatForm] [varchar](150) NULL,
	[ErrorTime] [datetime] NULL,
	[BugStatus] [varchar](15) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Page]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Page]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Page](
	[pageId] [float] NOT NULL,
	[displayName] [nvarchar](100) NULL,
	[path] [nvarchar](200) NULL,
	[parentId] [int] NULL,
	[orderBy] [float] NULL,
	[ParentIdForSubMenu] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_OverTimeStatus]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OverTimeStatus]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_OverTimeStatus](
	[ExtraTime_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Process_RecID] [bigint] NULL,
	[Employee_Id] [int] NULL,
	[Date] [datetime] NULL,
	[HrsExtra] [varchar](5) NULL,
	[ExtraMins] [int] NULL,
	[OverTimeStatus] [varchar](50) NULL,
	[CompOffEligible] [bit] NULL,
	[OTEligible] [bit] NULL,
	[DateToExpired] [datetime] NULL,
	[NoOfDays] [numeric](18, 1) NULL,
	[RemainingDays] [numeric](18, 1) NULL,
	[CompOffSatus] [varchar](30) NULL,
	[LeaveApplicationId] [varchar](150) NULL,
	[ActHrsExtra] [varchar](6) NULL,
	[ActExtraMins] [int] NULL,
	[isdelete] [bit] NULL,
	[isRequest] [bit] NULL,
	[DaysWorked] [nvarchar](100) NULL,
	[InTime] [nvarchar](20) NULL,
	[OutTime] [nvarchar](20) NULL,
	[Reason] [nvarchar](250) NULL,
	[ApplicationDate] [datetime] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_OtType]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OtType]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_OtType](
	[OtTypeID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyID] [int] NULL,
	[OtType] [varchar](50) NULL,
	[OtValue] [nchar](10) NULL,
	[EmpID] [int] NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_OtType_TimeStamp]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_OTRoundoffSettings]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OTRoundoffSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_OTRoundoffSettings](
	[OTRoundoffId] [int] IDENTITY(1,1) NOT NULL,
	[ShiftSettingId] [int] NOT NULL,
	[StartTime] [nvarchar](5) NOT NULL,
	[EndTime] [nvarchar](5) NOT NULL,
	[StartMins] [float] NOT NULL,
	[EndMins] [float] NOT NULL,
	[RoundedAs] [nvarchar](5) NOT NULL,
 CONSTRAINT [PK_TA_Tbl_OTRoundoffSettings] PRIMARY KEY CLUSTERED 
(
	[OTRoundoffId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_OndutyEntry]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OndutyEntry]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_OndutyEntry](
	[Onduty_ID] [int] IDENTITY(1,1) NOT NULL,
	[Onduty_EmployeeID] [nvarchar](20) NULL,
	[Onduty_EntryDate] [datetime] NULL,
	[Onduty_Type] [int] NULL,
	[IncludeWeekOff] [int] NULL,
	[Onduty_FromDate] [datetime] NULL,
	[Onduty_FromTime] [nvarchar](50) NULL,
	[Onduty_ToDate] [datetime] NULL,
	[Onduty_ToTime] [nvarchar](50) NULL,
	[Onduty_Reason] [nvarchar](255) NULL,
	[Onduty_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[From_Session] [nvarchar](20) NULL,
	[To_Session] [nvarchar](20) NULL,
	[YearSettings_Id] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_OnDutyConversation]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_OnDutyConversation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_OnDutyConversation](
	[OnDutyConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[OnDutyApplicationId] [int] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_tbl_NotProcessedDataDetails]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_NotProcessedDataDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_NotProcessedDataDetails](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Process_Rec_ID] [int] NULL,
	[SwipeCardNumber] [varchar](50) NULL,
	[ReaderId] [int] NULL,
	[Reason] [varchar](200) NULL,
	[RaisedFrom] [char](1) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_WorkHrs](
	[WorkhrsID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_WorkHrs] PRIMARY KEY CLUSTERED 
(
	[WorkhrsID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_Lateentry]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Lateentry](
	[LateEntryID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_Lateentry] PRIMARY KEY CLUSTERED 
(
	[LateEntryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_NoOfDaysDeduction_Armis]    Script Date: 03/25/2021 10:16:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_NoOfDaysDeduction_Armis]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_NoOfDaysDeduction_Armis](
	[ArmisID] [int] IDENTITY(1,1) NOT NULL,
	[StartTime1] [int] NULL,
	[EndTime1] [int] NULL,
	[Day1] [decimal](18, 2) NULL,
	[StartTime2] [int] NULL,
	[EndTime2] [int] NULL,
	[Day2] [decimal](18, 2) NULL,
	[StartTime3] [int] NULL,
	[EndTime3] [int] NULL,
	[Day3] [decimal](18, 2) NULL,
	[StartTime4] [int] NULL,
	[EndTime4] [int] NULL,
	[Day4] [decimal](18, 2) NULL,
	[StartTime5] [int] NULL,
	[EndTime5] [int] NULL,
	[Day5] [decimal](18, 2) NULL,
	[StartTime6] [int] NULL,
	[EndTime6] [int] NULL,
	[Day6] [decimal](18, 2) NULL,
	[StartTime7] [int] NULL,
	[EndTime7] [int] NULL,
	[Day7] [decimal](18, 2) NULL,
	[StartTime8] [int] NULL,
	[EndTime8] [int] NULL,
	[Day8] [decimal](18, 2) NULL,
	[StartTime9] [int] NULL,
	[EndTime9] [int] NULL,
	[Day9] [decimal](18, 2) NULL,
	[StartTime10] [int] NULL,
	[EndTime10] [int] NULL,
	[Day10] [decimal](18, 2) NULL,
	[Datetime] [datetime] NULL,
 CONSTRAINT [PK_ta_tbl_NoOfDaysDeduction_Armis] PRIMARY KEY CLUSTERED 
(
	[ArmisID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_NewsEvents]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_NewsEvents]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_NewsEvents](
	[NewsEvent_Id] [int] IDENTITY(1,1) NOT NULL,
	[NewsEventFromDate] [datetime] NULL,
	[NewsEventToDate] [datetime] NULL,
	[NewsEventTitle] [nvarchar](100) NULL,
	[NewsEventDescription] [nvarchar](500) NULL,
	[NewsEventActive] [bit] NULL,
	[NewsEventImage] [nvarchar](255) NULL,
	[LeftNewsEvent] [bit] NULL,
	[RightNewsEvent] [bit] NULL,
	[LeftBanner] [bit] NULL,
	[RightBanner] [bit] NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_NewsEvents_TimeStamp]  DEFAULT (getdate()),
	[Emp_Id] [decimal](18, 0) NULL,
 CONSTRAINT [PK_TA_Tbl_NewsEvents] PRIMARY KEY CLUSTERED 
(
	[NewsEvent_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_MultiLingual]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MultiLingual]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_MultiLingual](
	[Language_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Language_Name] [nvarchar](50) NULL,
	[Resource_File_Name] [nvarchar](50) NULL,
	[IsActive] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_MultiLingual] PRIMARY KEY CLUSTERED 
(
	[Language_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_MailConfiguration]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MailConfiguration]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_MailConfiguration](
	[FromEmailId] [varchar](300) NULL,
	[SMTPClientHost] [varchar](100) NULL,
	[SMTPPort] [varchar](50) NULL,
	[SSLEnable] [bit] NULL,
	[MailAuthentication] [bit] NULL,
	[MailAuthenticateUser] [nvarchar](30) NULL,
	[MailAuthenticatePassword] [nvarchar](30) NULL,
	[isRequired] [bit] NULL DEFAULT ((0))
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Lookup]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Lookup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Lookup](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Type] [int] NULL,
	[Title] [nvarchar](50) NULL,
	[Parent] [int] NULL,
	[Remarks] [nvarchar](50) NULL,
	[EmpID] [int] NULL,
	[Time_stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Lookup_Time_stamp]  DEFAULT (getdate()),
	[Isdeleted] [bit] NULL,
	[Emp_ID] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Lookup] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Login]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Login]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Login](
	[Username] [nvarchar](2000) NOT NULL,
	[LastLoginTime] [varchar](20) NULL,
	[LastLogoutTime] [varchar](20) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ta_tbl_LogDownloaded]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_LogDownloaded]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_LogDownloaded](
	[LoggedId] [int] IDENTITY(1,1) NOT NULL,
	[LoggedEmployeeId] [int] NOT NULL,
	[LoggedDate] [datetime] NOT NULL,
 CONSTRAINT [PK__ta_tbl_L__0605AD131E9FCF4A] PRIMARY KEY CLUSTERED 
(
	[LoggedId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LockLogin]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LockLogin]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LockLogin](
	[UserName] [nvarchar](1000) NULL,
	[LockedTime] [datetime] NULL,
	[IsActive] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LicenseRequestDetail]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LicenseRequestDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LicenseRequestDetail](
	[RequestID] [bigint] NOT NULL,
	[Status] [bit] NULL,
	[MacAddress] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LIC_Details]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LIC_Details](
	[CustomerId] [nvarchar](200) NULL,
	[PackageId] [nvarchar](200) NOT NULL,
	[PackageVersion] [nvarchar](200) NOT NULL,
	[NoOfConcurrentUser] [nvarchar](200) NOT NULL,
	[MACAddress] [nvarchar](200) NOT NULL,
	[LicenseGenerationDate] [nvarchar](200) NOT NULL,
	[ExpiryDate] [nvarchar](200) NOT NULL,
	[Module] [nvarchar](200) NOT NULL,
	[Module1] [nvarchar](200) NOT NULL,
	[Module2] [nvarchar](200) NOT NULL,
	[Module3] [nvarchar](200) NOT NULL,
	[Module4] [nvarchar](200) NOT NULL,
	[Module5] [nvarchar](200) NOT NULL,
	[NoOfEmployee] [nvarchar](200) NULL,
	[NoOfTerminal] [nvarchar](200) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LevelRights]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LevelRights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LevelRights](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[GroupId] [int] NULL,
	[LevelId] [nvarchar](50) NULL,
	[emp_id] [nvarchar](50) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicy]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeavePolicy](
	[Policy_Id] [int] IDENTITY(1,1) NOT NULL,
	[PolicyName] [nvarchar](50) NOT NULL,
	[Permission_MaxHrs_Month] [nvarchar](5) NULL,
	[Permission_MaxInstances_Month] [int] NULL,
	[Permission_MaxHrs_Instance] [nvarchar](5) NULL,
	[PermissionBeforeLeave] [bit] NULL,
	[PermissionAfterLeave] [bit] NULL,
	[OtHourWise] [bit] NULL,
	[OtDayWise] [bit] NULL,
	[OtMinHrs] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_LeavePolicy_Time_Stamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NULL,
	[EmployeeCategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](10) NULL,
	[Religion] [int] NULL,
	[CompOffValidDays] [int] NULL,
	[FullDayOTMinHrs] [nvarchar](5) NULL,
	[companyID] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_LeavePolicy] PRIMARY KEY CLUSTERED 
(
	[Policy_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveConversation]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveConversation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveConversation](
	[LeaveConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[LeaveApplicationId] [int] NOT NULL,
	[CommentsBy] [int] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_LeaveConversation_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_LeaveConversation] PRIMARY KEY CLUSTERED 
(
	[LeaveConversationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationPrintDetails_Eastman](
	[Autoid] [int] NOT NULL,
	[leaveAppID] [bigint] NULL,
	[LeaveTaken] [decimal](18, 1) NULL,
	[EarnedLeave] [decimal](18, 1) NULL,
	[LOP] [decimal](18, 1) NULL,
	[LeaveBalance] [decimal](18, 1) NULL,
	[WaiveOff] [decimal](18, 1) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationMaster]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationMaster](
	[LeaveApplication_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [nvarchar](20) NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[Reason] [nvarchar](1000) NULL,
	[IntimationType] [nvarchar](25) NULL,
	[Status] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[CCMail] [varchar](3000) NULL,
	[LeaveAvailedYear] [decimal](18, 1) NULL,
	[LeaveAvailedMonth] [decimal](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveApplicationMaster] PRIMARY KEY CLUSTERED 
(
	[LeaveApplication_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplicationExists]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplicationExists]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveApplicationExists](
	[LeaveApplicationId] [int] NULL,
	[Employee_Id] [nvarchar](20) NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[Leave_FromDate] [datetime] NOT NULL,
	[Leave_ToDate] [datetime] NOT NULL,
	[Leave_SessionFrom] [nvarchar](50) NOT NULL,
	[Leave_SessionTo] [nvarchar](50) NOT NULL,
	[Status] [nvarchar](50) NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveApplication]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveApplication]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveApplication](
	[LeaveApplication_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [nvarchar](20) NOT NULL,
	[Leave_ApplicationDate] [datetime] NOT NULL,
	[LeaveType_id] [int] NOT NULL,
	[Type] [nvarchar](50) NOT NULL,
	[Leave_FromDate] [datetime] NOT NULL,
	[Leave_ToDate] [datetime] NOT NULL,
	[Leave_SessionFrom] [nvarchar](50) NULL,
	[Leave_SessionTo] [nvarchar](50) NULL,
	[NumberOfDays] [decimal](18, 1) NOT NULL,
	[Reason] [nvarchar](1000) NULL,
	[IntimationType] [nvarchar](25) NULL,
	[Status] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[Remarks] [nvarchar](1000) NULL,
	[IsBorrow] [bit] NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[CheckedIDs] [int] NULL,
	[InformTo] [varchar](max) NULL,
	[companyId] [int] NULL,
	[Successiveyear] [bit] NULL,
	[Intervening] [char](5) NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveApplication] PRIMARY KEY CLUSTERED 
(
	[LeaveApplication_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Employee_Id'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Employee Id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Employee_Id'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Leave_ApplicationDate'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Leave Application Date' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Leave_ApplicationDate'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Type'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Leave Type' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Type'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Leave_FromDate'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Leave FromDate' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Leave_FromDate'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Leave_ToDate'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Leave ToDate' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Leave_ToDate'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Leave_SessionFrom'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Session From' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Leave_SessionFrom'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Leave_SessionTo'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Session To' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Leave_SessionTo'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'NumberOfDays'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Number of Days' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'NumberOfDays'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', N'COLUMN',N'Status'))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Status' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication', @level2type=N'COLUMN',@level2name=N'Status'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_LeaveApplication', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'Description', @value=N'Leave Application' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_LeaveApplication'
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveAnalysisNotes]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveAnalysisNotes]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveAnalysisNotes](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Notes] [varchar](8000) NULL,
	[DateInserted] [datetime] NULL CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_DateInserted_1]  DEFAULT (getdate()),
	[EmpID] [int] NULL,
	[IsDeleted] [bit] NULL CONSTRAINT [DF_TA_Tbl_LeaveAnalysisNotes_IsDeleted_1]  DEFAULT ((0))
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_LandMarks]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_LandMarks]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_LandMarks](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Options] [nvarchar](max) NULL,
	[LocationName] [nvarchar](500) NULL,
	[Radius] [int] NULL,
	[Description] [nvarchar](1000) NULL,
	[Address] [nvarchar](500) NULL,
	[City] [nvarchar](500) NULL,
	[State] [nvarchar](500) NULL,
	[Country] [nvarchar](500) NULL,
	[latitude] [varchar](30) NULL,
	[longitude] [varchar](30) NULL,
	[CreatedBy] [int] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportShiftAllocation]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ImportShiftAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ImportShiftAllocation](
	[Employee_Id] [int] NULL,
	[Employee_Code_Id] [varchar](100) NULL,
	[Company_Id] [int] NULL,
	[Company_Name] [varchar](250) NULL,
	[Year] [varchar](5) NULL,
	[Mon] [varchar](20) NULL,
	[Day1] [varchar](8) NULL,
	[Day2] [varchar](8) NULL,
	[Day3] [varchar](8) NULL,
	[Day4] [varchar](8) NULL,
	[Day5] [varchar](8) NULL,
	[Day6] [varchar](8) NULL,
	[Day7] [varchar](8) NULL,
	[Day8] [varchar](8) NULL,
	[Day9] [varchar](8) NULL,
	[Day10] [varchar](8) NULL,
	[Day11] [varchar](8) NULL,
	[Day12] [varchar](8) NULL,
	[Day13] [varchar](8) NULL,
	[Day14] [varchar](8) NULL,
	[Day15] [varchar](8) NULL,
	[Day16] [varchar](8) NULL,
	[Day17] [varchar](8) NULL,
	[Day18] [varchar](8) NULL,
	[Day19] [varchar](8) NULL,
	[Day20] [varchar](8) NULL,
	[Day21] [varchar](8) NULL,
	[Day22] [varchar](8) NULL,
	[Day23] [varchar](8) NULL,
	[Day24] [varchar](8) NULL,
	[Day25] [varchar](8) NULL,
	[Day26] [varchar](8) NULL,
	[Day27] [varchar](8) NULL,
	[Day28] [varchar](8) NULL,
	[Day29] [varchar](8) NULL,
	[Day30] [varchar](8) NULL,
	[Day31] [varchar](8) NULL,
	[ImportID] [int] IDENTITY(1,1) NOT NULL,
	[RecordNumber] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ImportMasterError]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ImportMasterError]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ImportMasterError](
	[id] [bigint] IDENTITY(1,1) NOT NULL,
	[Emp_FirstName] [nvarchar](50) NULL,
	[Emp_MiddleName] [nvarchar](50) NULL,
	[Emp_LastName] [nvarchar](50) NULL,
	[Father_Name] [nvarchar](50) NULL,
	[Mother_Name] [nvarchar](50) NULL,
	[DateOfBirth] [nvarchar](20) NULL,
	[DateOfBirth_Record] [nvarchar](20) NULL,
	[Blood_Group] [nvarchar](10) NULL,
	[Email_Id] [nvarchar](100) NULL,
	[Contact_Address] [nvarchar](max) NULL,
	[Permanent_Address] [nvarchar](max) NULL,
	[Phone_Number] [nvarchar](50) NULL,
	[Mobile_Number] [nvarchar](50) NULL,
	[Gender] [nvarchar](10) NULL,
	[Marital_Status] [nvarchar](10) NULL,
	[Nationality] [nvarchar](50) NULL,
	[Religion] [nvarchar](50) NULL,
	[Personal_EmailID] [nvarchar](100) NULL,
	[Passport_No] [nvarchar](50) NULL,
	[Passport_ExpiryDate] [nvarchar](20) NULL,
	[Visa_No] [nvarchar](50) NULL,
	[Visa_ExpiryDate] [nvarchar](20) NULL,
	[Employee_Code] [nvarchar](50) NULL,
	[DateOfJoining] [nvarchar](20) NULL,
	[Qualification_joiningtime] [nvarchar](50) NULL,
	[Qualification_Employement] [nvarchar](50) NULL,
	[CompOff_Eligible] [nvarchar](5) NULL,
	[OT_Eligible] [nvarchar](5) NULL,
	[Report_Exclude] [nvarchar](5) NULL,
	[Employee_Status] [nvarchar](5) NULL,
	[IsDeleted] [nvarchar](5) NULL,
	[Hostel] [nvarchar](5) NULL,
	[Designation] [nvarchar](200) NULL,
	[Grade] [nvarchar](50) NULL,
	[GradeNo] [nvarchar](50) NULL,
	[Employee_Type] [nvarchar](100) NULL,
	[Employee_Category] [nvarchar](100) NULL,
	[BasicSalary] [nvarchar](50) NULL,
	[Level1] [nvarchar](100) NULL,
	[Level2] [nvarchar](100) NULL,
	[Level3] [nvarchar](100) NULL,
	[Level4] [nvarchar](100) NULL,
	[Level5] [nvarchar](100) NULL,
	[Level6] [nvarchar](100) NULL,
	[Level7] [nvarchar](100) NULL,
	[Level8] [nvarchar](100) NULL,
	[Level9] [nvarchar](100) NULL,
	[Level10] [nvarchar](100) NULL,
	[IsValid] [int] NULL,
	[Error] [nvarchar](max) NULL,
	[RecordNumber] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_ImportMasterData]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_ImportMasterData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_ImportMasterData](
	[EmployeeID] [int] NULL,
	[Emp_FirstName] [nvarchar](250) NULL,
	[Emp_MiddleName] [nvarchar](250) NULL,
	[Emp_LastName] [nvarchar](250) NULL,
	[Father_Name] [nvarchar](250) NULL,
	[Mother_Name] [nvarchar](250) NULL,
	[DateOfBirth] [nvarchar](250) NULL,
	[DateOfBirth_Record] [nvarchar](250) NULL,
	[Blood_Group] [nvarchar](5) NULL,
	[Email_Id] [nvarchar](250) NULL,
	[Contact_Address] [nvarchar](2250) NULL,
	[Permanent_Address] [nvarchar](2250) NULL,
	[Phone_Number] [nvarchar](250) NULL,
	[Mobile_Number] [nvarchar](250) NULL,
	[Gender] [nvarchar](250) NULL,
	[Marital_Status] [nvarchar](250) NULL,
	[Nationality] [nvarchar](250) NULL,
	[Religion] [nvarchar](250) NULL,
	[Personal_EmailID] [nvarchar](250) NULL,
	[Passport_No] [nvarchar](250) NULL,
	[Passport_ExpiryDate] [nvarchar](250) NULL,
	[Visa_No] [nvarchar](250) NULL,
	[Visa_ExpiryDate] [nvarchar](250) NULL,
	[Employee_Code] [nvarchar](25) NULL,
	[DateOfJoining] [nvarchar](25) NULL,
	[Qualification_joiningtime] [nvarchar](25) NULL,
	[Qualification_Employement] [nvarchar](25) NULL,
	[OutDoorJob] [bit] NULL,
	[CompOff_Eligible] [bit] NULL,
	[OT_Eligible] [bit] NULL,
	[ESI_Eligible] [bit] NULL,
	[PF_Eligible] [bit] NULL,
	[Report_Exclude] [bit] NULL,
	[Employee_Status] [bit] NULL CONSTRAINT [DF_Ta_Tbl_ImportMasterData_Employee_Status]  DEFAULT ((1)),
	[SwipeCardNo] [nvarchar](250) NULL,
	[IsDeleted] [bit] NULL,
	[Hostel] [bit] NULL,
	[Designation] [nvarchar](250) NULL,
	[Grade] [nvarchar](250) NULL,
	[GradeNo] [nvarchar](250) NULL,
	[EmployeeType] [nvarchar](250) NULL,
	[EmployeeCategory] [nvarchar](250) NULL,
	[BasicSalary] [nvarchar](10) NULL,
	[Level1] [nvarchar](250) NULL,
	[Level2] [nvarchar](250) NULL,
	[Level3] [nvarchar](250) NULL,
	[Level4] [nvarchar](250) NULL,
	[Level5] [nvarchar](250) NULL,
	[Level6] [nvarchar](250) NULL,
	[Level7] [nvarchar](250) NULL,
	[Level8] [nvarchar](250) NULL,
	[Level9] [nvarchar](250) NULL,
	[Level10] [nvarchar](250) NULL,
	[Level1_Id] [int] NULL,
	[Level2_Id] [int] NULL,
	[Level3_Id] [int] NULL,
	[Level4_Id] [int] NULL,
	[Level5_Id] [int] NULL,
	[Level6_Id] [int] NULL,
	[Level7_Id] [int] NULL,
	[Level8_Id] [int] NULL,
	[Level9_Id] [int] NULL,
	[Level10_Id] [int] NULL,
	[childLevelId] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidaySettings]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidaySettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_HolidaySettings](
	[Holiday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Global_Maxdays] [int] NOT NULL,
	[Yearly_Maxdays] [int] NOT NULL,
	[YearSettingId] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_HolidaySettings] PRIMARY KEY CLUSTERED 
(
	[Holiday_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_emp_LeaveTypedetails]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_emp_LeaveTypedetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_emp_LeaveTypedetails](
	[LeaveTypeDetailsId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LeaveTypeId] [int] NULL,
	[PreviousYearBalance] [decimal](18, 1) NULL,
	[NoOffLeaveAvailed] [decimal](18, 1) NULL,
	[YearSettingsId] [int] NULL,
	[IsDeleted] [bit] NOT NULL DEFAULT ((0))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Entrance](
	[Entrance_Id] [int] IDENTITY(1,1) NOT NULL,
	[Entrance_Name] [nvarchar](50) NOT NULL,
	[Entrance_Description] [nvarchar](250) NULL,
	[OrgLevel_Id] [int] NULL,
	[NoOfInTerminals] [int] NULL,
	[NoOfOutTerminals] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[Time_Stamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_Entrance_Time_Stamp]  DEFAULT (getdate()),
	[Emp_ID] [int] NULL,
	[Flag] [int] NULL DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_Entrance] PRIMARY KEY CLUSTERED 
(
	[Entrance_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_HelpContent]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_HelpContent]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_HelpContent](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Header] [nvarchar](max) NULL,
	[Paragraph] [nvarchar](max) NULL,
	[createdDate] [datetime] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_GroupDetails]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_GroupDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_GroupDetails](
	[Group_Id] [int] IDENTITY(1,1) NOT NULL,
	[Group_Name] [nvarchar](50) NOT NULL,
	[Group_Description] [nvarchar](50) NOT NULL,
	[IsDeleted] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Grade]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Grade]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Grade](
	[Grade_ID] [int] IDENTITY(1,1) NOT NULL,
	[Grade_Name] [nvarchar](50) NOT NULL,
	[Grade_Level] [int] NULL,
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Grade_Time_Stamp]  DEFAULT (getdate()),
	[Isdeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_Grade] PRIMARY KEY CLUSTERED 
(
	[Grade_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_GraceDetails]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_GraceDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_GraceDetails](
	[ShiftID] [int] NULL,
	[OldGraceShiftIn] [nvarchar](6) NULL,
	[OldGraceShiftOut] [nvarchar](6) NULL,
	[Shift_BreakStartTime1] [nvarchar](10) NULL,
	[Shift_BreakEndTime1] [nvarchar](10) NULL,
	[Shift_BreakStartTime2] [nvarchar](10) NULL,
	[Shift_BreakEndTime2] [nvarchar](10) NULL,
	[Shift_BreakStartTime3] [nvarchar](10) NULL,
	[Shift_BreakEndTime3] [nvarchar](10) NULL,
	[TimeStamp] [datetime] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_GlobalWeekdaySettings]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_GlobalWeekdaySettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_GlobalWeekdaySettings](
	[GlobalWeekday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[GlobalWeekday_HrsMonday] [int] NOT NULL,
	[GlobalWeekday_HrsTuesday] [int] NOT NULL,
	[GlobalWeekday_HrsWenesday] [int] NOT NULL,
	[GlobalWeekday_HrsThursday] [int] NOT NULL,
	[GlobalWeekday_HrsFriday] [int] NOT NULL,
	[GlobalWeekday_HrsSaturday] [int] NOT NULL,
	[GlobalWeekday_HrsSunday] [int] NOT NULL,
	[GlobalWeekday_MondayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_TuesdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_WensdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_ThursdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_FridayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_SaturdayWeekOff] [bit] NOT NULL,
	[GlobalWeekday_SundayWeekOff] [bit] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ExportDataCentena]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ExportDataCentena]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ExportDataCentena](
	[DateImport] [datetime] NULL,
	[EmpCode] [varchar](50) NULL,
	[LeaveType] [varchar](20) NULL,
	[Days] [numeric](2, 1) NULL,
	[Remarks] [varchar](8000) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_ExistingRightsDetails]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_ExistingRightsDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_ExistingRightsDetails](
	[id] [int] NULL,
	[groupName] [nvarchar](500) NULL,
	[groupId] [int] NULL,
	[pageId] [float] NULL,
	[pageGroupId] [int] NULL,
	[addPrv] [bit] NULL,
	[modifyPrv] [bit] NULL,
	[deletePrv] [bit] NULL,
	[viewPrv] [bit] NULL,
	[isDeleted] [bit] NULL,
	[timeStamp] [datetime] NULL,
	[employeeId] [decimal](18, 0) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ProcessedData]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrorLog_ProcessedData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ErrorLog_ProcessedData](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Process_Rec_ID] [bigint] NULL,
	[ErrorMessage] [varchar](max) NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_ErrorLog_ProcessedData_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_ErrorLog_ProcessedData] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrorLog_ClockRawData]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrorLog_ClockRawData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ErrorLog_ClockRawData](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Clock_Id] [nchar](20) NULL,
	[ErrorMessage] [varchar](max) NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_ErrorLog_ClockRawData_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_ErrorLog_ClockRawData] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ErrLog]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ErrLog]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ErrLog](
	[ErrId] [bigint] IDENTITY(1,1) NOT NULL,
	[ErrMessage] [nvarchar](4000) NULL,
	[ErrSource] [nvarchar](4000) NULL,
	[ErrStackTrace] [nvarchar](4000) NULL,
	[ErrException] [nvarchar](4000) NULL,
	[TimestampRec] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_ErrLog_TimestampRec]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Additional_WeeklyOff](
	[Addl_WeeklyOff_Id] [int] IDENTITY(1,1) NOT NULL,
	[Addl_WeekOff_Day] [nvarchar](50) NULL,
	[Addl_WeekOff_Week] [nvarchar](50) NULL,
	[LevelId_Id] [int] NULL,
	[IsDeleted] [bit] NULL,
	[Emp_Id] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Additional_WeeklyOff] PRIMARY KEY CLUSTERED 
(
	[Addl_WeeklyOff_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AccessDeniedSettings]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AccessDeniedSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AccessDeniedSettings](
	[AccessDenied_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_ReaderID] [nvarchar](10) NULL,
	[Employee_Code_Id] [nvarchar](10) NULL,
	[AccessDeniedKey] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_ExportData_FieldData]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_ExportData_FieldData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_ExportData_FieldData](
	[OptionType] [varchar](50) NOT NULL,
	[FieldName] [varchar](50) NOT NULL,
	[UserDefinedFieldName] [varchar](50) NOT NULL,
	[FieldType] [varchar](50) NOT NULL,
	[DataType] [varchar](50) NULL,
	[CompanyID] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_ExportData_CustomFormat]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_ExportData_CustomFormat]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_ExportData_CustomFormat](
	[OptionType] [varchar](50) NOT NULL,
	[DateFormat] [varchar](50) NOT NULL,
	[TimeFormat] [varchar](50) NOT NULL,
	[DateTimeFormat] [varchar](50) NOT NULL,
	[XML_RootTag] [varchar](50) NOT NULL,
	[XML_FirstChildTag] [varchar](50) NOT NULL,
	[DataType] [varchar](50) NULL,
	[CompanyID] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Proc_ImportOvertime]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ImportOvertime]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Proc_ImportOvertime](
	[autoid] [bigint] IDENTITY(1,1) NOT NULL,
	[Sl.no] [varchar](20) NULL,
	[Employee_Code_Id] [varchar](20) NULL,
	[Employee_FirstName] [varchar](max) NULL,
	[LevelName] [varchar](max) NULL,
	[date] [varchar](20) NULL,
	[HrsOT] [varchar](20) NULL,
	[ActHrsOT] [varchar](20) NULL,
	[OffOT] [varchar](20) NULL,
	[ActOffOT] [varchar](20) NULL,
	[HolOT] [varchar](20) NULL,
	[ActHolOT] [varchar](20) NULL,
	[SPEC_NormOT1] [varchar](20) NULL,
	[Modified_Spec_NormOTHrs1] [varchar](20) NULL,
	[SPEC_NormOT2] [varchar](20) NULL,
	[Modified_Spec_NormOTHrs2] [varchar](20) NULL,
	[SPEC_OffOT1] [varchar](20) NULL,
	[Modified_Spec_OffOTHrs1] [varchar](20) NULL,
	[SPEC_OffOT2] [varchar](20) NULL,
	[Modified_Spec_OffOTHrs2] [varchar](20) NULL,
	[SPEC_HOLOT1] [varchar](20) NULL,
	[Modified_Spec_HolOTHrs1] [varchar](20) NULL,
	[SPEC_HOLOT2] [varchar](20) NULL,
	[Modified_Spec_HolOTHrs2] [varchar](20) NULL,
	[OverTimeStatus] [varchar](20) NULL,
	[Error] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ImportFromExcel]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ImportFromExcel]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ImportFromExcel](
	[Sl.No] [varchar](50) NULL,
	[Employeeid] [varchar](50) NULL,
	[LeaveType1] [decimal](18, 1) NULL,
	[LeaveType2] [decimal](18, 1) NULL,
	[LeaveType3] [decimal](18, 1) NULL,
	[LeaveType4] [decimal](18, 1) NULL,
	[LeaveType5] [decimal](18, 1) NULL,
	[LeaveType6] [decimal](18, 1) NULL,
	[LeaveType7] [decimal](18, 1) NULL,
	[LeaveType8] [decimal](18, 1) NULL,
	[LeaveType9] [decimal](18, 1) NULL,
	[LeaveType10] [decimal](18, 1) NULL,
	[LeaveType11] [decimal](18, 1) NULL,
	[LeaveType12] [decimal](18, 1) NULL,
	[LeaveType13] [decimal](18, 1) NULL,
	[LeaveType14] [decimal](18, 1) NULL,
	[LeaveType15] [decimal](18, 1) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AutoLeaveupdation]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AutoLeaveupdation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[AutoLeaveupdation](
	[autoid] [int] IDENTITY(1,1) NOT NULL,
	[leaveapplicationID] [bigint] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_ODApproval]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_ODApproval]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CCGroup_ODApproval](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupId] [bigint] NOT NULL,
	[CC_ODApproval] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_ODApproval] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Category]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Category]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Category](
	[CategoryId] [bigint] IDENTITY(1,1) NOT NULL,
	[CategoryName] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[EmpId] [bigint] NULL,
	[IsFlexible] [bit] NULL,
	[MonToSat_WorkHrs] [varchar](20) NULL,
	[Sat_WorkHrs] [numeric](18, 1) NULL,
	[WeekDay_WorkHrs] [varchar](20) NULL,
	[ARMIS_WorkHrs] [numeric](18, 1) NULL,
	[ParentIdForSubMenu] [int] NULL,
	[InActiveDate] [datetime] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_Branding]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Branding]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_Branding](
	[img_id] [int] IDENTITY(1,1) NOT NULL,
	[Cus_Image] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AutoShiftConfiguration]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AutoShiftConfiguration]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AutoShiftConfiguration](
	[AutoShiftConfigId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[ShiftId1] [int] NULL,
	[ShiftId2] [int] NULL,
	[ShiftId3] [int] NULL,
	[ShiftId4] [int] NULL,
	[ShiftId5] [int] NULL,
	[CreatedBy] [int] NULL,
	[CreatedDate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_CreatedDate]  DEFAULT (getdate()),
	[ModifiedBy] [int] NULL,
	[ModifiedDate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_AutoShiftConfiguration_ModifiedDate]  DEFAULT (getdate()),
	[IsImport] [bit] NOT NULL CONSTRAINT [Defaultconstraints5]  DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_AutoShiftConfiguration] PRIMARY KEY CLUSTERED 
(
	[AutoShiftConfigId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AuditTable](
	[TableID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableName] [nvarchar](100) NOT NULL,
	[TableDescription] [nvarchar](100) NOT NULL,
	[Status] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_AuditTable] PRIMARY KEY CLUSTERED 
(
	[TableID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduled_Employees]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduled_Employees]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmailScheduled_Employees](
	[ScheduleId] [bigint] NULL,
	[Employee_id] [bigint] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailSchedule]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmailSchedule](
	[ScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleName] [varchar](250) NOT NULL,
	[ReportId] [int] NOT NULL,
	[Frequency] [varchar](20) NOT NULL,
	[DayToSend] [varchar](10) NOT NULL,
	[DayFrom] [varchar](10) NOT NULL,
	[DayTo] [varchar](10) NOT NULL,
	[DateToSend] [int] NOT NULL,
	[DateFrom] [int] NOT NULL,
	[DateTo] [int] NOT NULL,
	[TimeToSend] [varchar](20) NOT NULL,
	[EmployeeId] [int] NOT NULL,
	[EmailSendType] [bit] NOT NULL,
	[Authentication] [bit] NOT NULL,
	[FileType] [varchar](20) NOT NULL,
	[Enabled] [bit] NOT NULL,
	[IsDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmailSchedule_TimeStamp]  DEFAULT (getdate()),
	[ReportName] [varchar](50) NULL,
	[ToWhom] [bit] NULL DEFAULT ((0)),
	[TimeSendOption] [int] NULL DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_EmailSchedule] PRIMARY KEY CLUSTERED 
(
	[ScheduleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_EmailReportNotSendedDetails]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_EmailReportNotSendedDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_EmailReportNotSendedDetails](
	[ReScheduleid] [bigint] IDENTITY(1,1) NOT NULL,
	[Id] [bigint] NULL,
	[FromMailId] [nvarchar](max) NULL,
	[ToEmailIds] [nvarchar](max) NULL,
	[CCEmailIds] [nvarchar](max) NULL,
	[EmailSubject] [nvarchar](300) NULL,
	[Content] [nvarchar](max) NULL,
	[Attachment] [nvarchar](max) NULL,
	[AraisedFrom] [nvarchar](50) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_tbl_DeviceServerDetails]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_DeviceServerDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_DeviceServerDetails](
	[ServerName] [nvarchar](1000) NULL,
	[DatabaseName] [nvarchar](1000) NULL,
	[UserId] [varchar](100) NULL,
	[Password] [varchar](100) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_DeviceLogTableDetails]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_DeviceLogTableDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_DeviceLogTableDetails](
	[tblAutoID] [int] IDENTITY(1,1) NOT NULL,
	[DeviceLog_TableName] [varchar](50) NULL,
	[LastLogID] [bigint] NULL,
	[LogFetch_LastTime] [datetime] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Demo]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Demo]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Demo](
	[InstalledDate] [nvarchar](100) NULL,
	[DemoExpiryDate] [nvarchar](100) NULL,
	[DemoType] [nvarchar](50) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_DateandTimeFormat]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_DateandTimeFormat]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_DateandTimeFormat](
	[DateandTimeFormatId] [int] IDENTITY(1,1) NOT NULL,
	[DateFormat] [nvarchar](50) NULL,
	[TimeFormat] [nvarchar](50) NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[isDomain] [int] NULL,
	[DomainName] [nvarchar](500) NULL,
	[DomainAdminUserName] [nvarchar](500) NULL,
	[DomainAdminPassword] [nvarchar](1000) NULL,
 CONSTRAINT [PK_TA_Tbl_DateandTimeFormat] PRIMARY KEY CLUSTERED 
(
	[DateandTimeFormatId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_DataProcessTemp]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_DataProcessTemp]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_DataProcessTemp](
	[ProcessDate] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_DataProcessCompanyLevelTemp]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_DataProcessCompanyLevelTemp](
	[LevelId] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardUserrights]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_DashboardUserrights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_DashboardUserrights](
	[Rightsid] [int] IDENTITY(1,1) NOT NULL,
	[Usergroupid] [int] NULL,
	[Boardid] [int] NULL,
	[ViewPrev] [int] NULL,
	[Dashboard] [int] NULL,
	[Gridview] [int] NULL,
	[Chart] [int] NULL,
	[Empid] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_DashboardData]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_DashboardData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_DashboardData](
	[DataId] [int] IDENTITY(1,1) NOT NULL,
	[BoardParentName] [varchar](50) NULL,
	[BoardChildName] [varchar](50) NULL,
	[BoardId] [int] NULL,
 CONSTRAINT [PK__ta_tbl_D__9D05303DC71941DA] PRIMARY KEY CLUSTERED 
(
	[DataId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ConcurrentUser]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ConcurrentUser]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ConcurrentUser](
	[ConcurrentUserId] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [nvarchar](15) NOT NULL,
	[IpAddress] [nvarchar](15) NOT NULL,
	[LoginTime] [datetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[SessionId] [nvarchar](25) NOT NULL,
 CONSTRAINT [PK_TA_Tbl_ConcurrentUser] PRIMARY KEY CLUSTERED 
(
	[ConcurrentUserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_CompanyGroup]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CompanyGroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CompanyGroup](
	[CompanyGroup] [varchar](500) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_CMITechSyncEmployeeInfo]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CMITechSyncEmployeeInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CMITechSyncEmployeeInfo](
	[CMITechRecordNo] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [varchar](max) NOT NULL,
	[EmployeeName] [varchar](max) NOT NULL,
 CONSTRAINT [TA_Tbl_CMITechEmployeeInfo] PRIMARY KEY CLUSTERED 
(
	[CMITechRecordNo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ClockDetails]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ClockDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ClockDetails](
	[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_CompId] [nvarchar](10) NULL,
	[Clk_EmpId] [nvarchar](20) NULL,
	[Clk_InDeviceId] [nvarchar](20) NULL,
	[Clk_InDate] [datetime] NULL,
	[Clk_InTime] [datetime] NULL,
	[Clk_InPunchType] [nvarchar](25) NULL,
	[Clk_OutDeviceId] [nvarchar](20) NULL,
	[Clk_OutDate] [datetime] NULL,
	[Clk_OutTime] [datetime] NULL,
	[Clk_OutPunchType] [nvarchar](25) NULL,
	[Clk_Process] [nvarchar](1) NULL,
	[Clk_Remarks] [nvarchar](255) NULL,
	[Clk_User] [nvarchar](20) NULL,
	[Clk_Date] [datetime] NULL,
	[Clk_Status] [nvarchar](1) NULL,
	[IsVoid] [bit] NULL CONSTRAINT [DF_TA_Tbl_ClockDetails_IsVoid]  DEFAULT ((0)),
	[PunchType_Remarks] [varchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_ClockDetails] PRIMARY KEY CLUSTERED 
(
	[Clk_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Clk_RawData]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Clk_RawData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Clk_RawData](
	[CLK_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL CONSTRAINT [DF_TA_Tbl_Clk_RawData_CLK_PROCESS]  DEFAULT ((0)),
	[TimeStamp] [datetime] NOT NULL DEFAULT (getdate()),
	[TimecheckDateTime] [datetime] NULL,
	[ReasonId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Clk_RawData] PRIMARY KEY CLUSTERED 
(
	[CLK_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ChangePassword]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ChangePassword]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ChangePassword](
	[EmployeeId] [int] NOT NULL,
	[OldPassword] [nvarchar](16) NOT NULL,
	[NewPassword] [nvarchar](16) NOT NULL,
	[ConfirmNewPassword] [nvarchar](16) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AttendenceData]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AttendenceData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AttendenceData](
	[Attendence_Id] [int] IDENTITY(1,1) NOT NULL,
	[EmpId] [nvarchar](50) NOT NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[OD] [numeric](18, 1) NULL,
	[EL] [numeric](18, 1) NULL,
	[CL] [numeric](18, 1) NULL,
	[SL] [numeric](18, 1) NULL,
	[LOP_Absent] [numeric](18, 1) NULL,
	[Difference_Days] [numeric](18, 1) NULL,
	[Total] [numeric](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_AttendenceData] PRIMARY KEY CLUSTERED 
(
	[Attendence_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AttandanceCode]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AttandanceCode]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AttandanceCode](
	[AttandanceID] [int] IDENTITY(1,1) NOT NULL,
	[CompanyID] [int] NULL,
	[AttandanceCode] [nvarchar](50) NULL,
	[AttandanceValue] [nvarchar](50) NULL,
	[EmpID] [int] NULL,
	[isDeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_AttandanceCode_TimeStamp]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ApprovalSettings]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ApprovalSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ApprovalSettings](
	[CompanyId] [int] NOT NULL,
	[OTApproval] [bit] NOT NULL,
	[LeaveSanction] [bit] NOT NULL,
	[PermissionSanction] [bit] NOT NULL,
	[ManualEntry] [bit] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[Roster] [bit] NULL,
	[Pattern] [bit] NOT NULL,
	[ODEntry] [bit] NULL,
	[Approval] [bit] NOT NULL,
	[webClockInOut] [bit] NULL DEFAULT ((0))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_TBL_EmailScripts]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_TBL_EmailScripts]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_TBL_EmailScripts](
	[ScriptId] [int] NOT NULL,
	[ScriptText] [varchar](max) NULL,
	[ScriptType] [nvarchar](200) NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_tbl_EmailScheduleStatus]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_EmailScheduleStatus]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_tbl_EmailScheduleStatus](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[DurationFrom] [datetime] NOT NULL,
	[DurationTo] [datetime] NOT NULL,
	[SentDate] [datetime] NOT NULL,
	[Status] [bit] NOT NULL,
	[To_Mail] [varchar](50) NULL,
	[EmailID] [varchar](max) NULL,
	[ErrorMessage] [nvarchar](max) NULL,
 CONSTRAINT [PK_TA_tbl_EmailScheduleStatus] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_EmailScheduleStatus]') AND name = N'IDX_EmailSchedule_GetEmployeeEmail')
CREATE NONCLUSTERED INDEX [IDX_EmailSchedule_GetEmployeeEmail] ON [dbo].[TA_tbl_EmailScheduleStatus] 
(
	[ScheduleId] ASC,
	[Status] ASC
)
INCLUDE ( [SentDate],
[To_Mail]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Employee]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Employee](
	[Employee_Id] [int] IDENTITY(1,1) NOT NULL,
	[UserGroup_Id] [int] NULL,
	[Designation_Id] [int] NULL,
	[ShiftPattern_Id] [int] NULL,
	[Bus_Id] [int] NULL,
	[Employee_FirstName] [nvarchar](50) NULL,
	[Employee_MiddleName] [nvarchar](50) NULL,
	[Employee_LastName] [nvarchar](50) NULL,
	[Father_name] [nvarchar](50) NULL,
	[Mother_name] [nvarchar](50) NULL,
	[DateofBirth] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth]  DEFAULT (NULL),
	[DateofBirth_Record] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_DateofBirth_Record]  DEFAULT (NULL),
	[Blood_Group] [nvarchar](10) NULL,
	[EmailId] [nvarchar](100) NULL,
	[Contact_Address] [nvarchar](255) NULL,
	[Permanent_Address] [nvarchar](255) NULL,
	[Phone_Number] [nvarchar](50) NULL,
	[Mobile_Number] [nvarchar](50) NULL,
	[Gender] [nvarchar](10) NULL,
	[Marital_status] [nvarchar](10) NULL,
	[Nationality] [nvarchar](50) NULL,
	[Religion] [int] NULL,
	[Photo] [image] NULL,
	[Personal_mailid] [nvarchar](100) NULL,
	[Passport_No] [nvarchar](50) NULL,
	[Passport_expirydate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_Passport_expirydate]  DEFAULT (NULL),
	[Visa_No] [nvarchar](50) NULL,
	[Visa_expirydate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_Visa_expirydate]  DEFAULT (NULL),
	[Vehicle_Type] [nvarchar](20) NULL,
	[Vehicle_No] [nvarchar](50) NULL,
	[Anniversary_Date] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_Anniversary_Date]  DEFAULT (NULL),
	[Native_Place] [int] NULL,
	[District] [nvarchar](50) NULL,
	[State] [int] NULL,
	[Country] [int] NULL,
	[Spouse_No] [int] NULL,
	[Children_No] [int] NULL,
	[Employee_Code_Id] [nvarchar](15) NULL,
	[DateOfJoining] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_DateOfJoining]  DEFAULT (NULL),
	[Reporting_To] [int] NULL,
	[Leave_Sanc_Authority] [int] NULL,
	[Prev_Experience] [float] NULL,
	[Basic_Salary] [float] NULL,
	[Allowances] [float] NULL,
	[UserName] [nvarchar](15) NULL,
	[Emp_password] [nvarchar](50) NULL,
	[Qual_JoiningTime] [nvarchar](50) NULL,
	[Qual_Employment] [nvarchar](50) NULL,
	[OutDoorJob] [bit] NULL,
	[CompOff_Eligible] [bit] NOT NULL,
	[OT_Eligible] [bit] NOT NULL,
	[ESI_Eligible] [bit] NOT NULL,
	[PF_Eligible] [bit] NULL,
	[Report_Exclude] [bit] NULL,
	[Employee_Status] [bit] NULL,
	[SwipeCardNo] [nvarchar](20) NULL,
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Employee_Time_Stamp]  DEFAULT (getdate()),
	[Emp_ID] [int] NULL,
	[Isdeleted] [bit] NULL,
	[Hostel] [bit] NULL,
	[IsFlexible] [bit] NULL,
	[InActiveDate] [datetime] NULL,
	[CustomField1] [nvarchar](1000) NULL,
	[CustomField2] [nvarchar](1000) NULL,
	[CustomField3] [nvarchar](1000) NULL,
	[CustomField4] [nvarchar](1000) NULL,
	[CustomField5] [nvarchar](1000) NULL,
	[IsComplete] [bit] NULL,
	[Isdeleted_Status] [bit] NULL,
	[InActive_Status] [bit] NULL,
	[IsImported] [bit] NULL,
	[modify_date] [datetime] NULL,
	[modify_by] [bigint] NULL,
	[penalty] [bit] NULL,
	[MobileClockInOUt] [bit] NOT NULL CONSTRAINT [Defaultconstraint]  DEFAULT ((0)),
	[SMSEnabled] [bit] NOT NULL CONSTRAINT [Defaultconstraint2]  DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_Employee] PRIMARY KEY CLUSTERED 
(
	[Employee_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Employee]') AND name = N'IDX_GetEmployeeEmail')
CREATE NONCLUSTERED INDEX [IDX_GetEmployeeEmail] ON [dbo].[TA_Tbl_Employee] 
(
	[Employee_Status] ASC,
	[Isdeleted] ASC,
	[EmailId] ASC
)
INCLUDE ( [Employee_Id],
[Employee_Code_Id]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeType]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeType]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeType](
	[EmployeeId] [bigint] NOT NULL,
	[TypeId] [bigint] NOT NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmployeeType_Timestamp]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeShiftId_ForShiftReAllocation](
	[EmployeeAutoId] [bigint] NULL,
	[Date] [datetime] NULL,
	[CurrentShiftId] [int] NULL,
	[PreviousDayShift] [int] NULL,
	[NextDayShift] [int] NULL,
	[LoggedInEmployeId] [int] NULL,
	[Flag] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_EmployeePunch]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_EmployeePunch]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_EmployeePunch](
	[RecordId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [varchar](5) NULL,
	[Date] [date] NULL,
	[Time] [time](7) NULL,
 CONSTRAINT [PK_Ta_Tbl_EmployeePunch] PRIMARY KEY CLUSTERED 
(
	[RecordId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeePay]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeePay]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeePay](
	[PayID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[BasicPay] [numeric](18, 2) NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpID] [int] NULL,
	[Timestamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_EmployeePay_Timestamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_EmployeePay] PRIMARY KEY CLUSTERED 
(
	[PayID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLingual]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeLingual]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeLingual](
	[EmployeeLingualId] [int] IDENTITY(1,1) NOT NULL,
	[LanguageId] [int] NOT NULL,
	[EmployeeId] [int] NOT NULL,
 CONSTRAINT [PK_EmployeeLingual] PRIMARY KEY CLUSTERED 
(
	[EmployeeLingualId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeLevel]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeLevel]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeLevel](
	[EmployeeId] [bigint] NULL,
	[LevelId] [bigint] NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmployeeLevel_Timestamp]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeEntrance]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeEntrance]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeEntrance](
	[Unique_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Code_Id] [varchar](50) NULL,
	[Device_Id] [varchar](50) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeDesignation]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeDesignation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeDesignation](
	[EmpDesignationID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeID] [int] NULL,
	[DesignationID] [int] NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpID] [int] NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmployeeDesignation_Timestamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_EmployeeDesignation] PRIMARY KEY CLUSTERED 
(
	[EmpDesignationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeCategory]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeCategory]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeCategory](
	[EmployeeId] [bigint] NOT NULL,
	[CategoryId] [bigint] NOT NULL,
	[EffectiveDate] [datetime] NULL,
	[EmpId] [bigint] NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmployeeCategory_Timestamp]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftExchange]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftExchange]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ShiftExchange](
	[ShiftExchange_id] [bigint] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NOT NULL,
	[Date] [datetime] NOT NULL,
	[Employee1_Id] [int] NOT NULL,
	[Employee1_ActualShift] [int] NOT NULL,
	[Employee2_Id] [int] NOT NULL,
	[Employee2_ActualShift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[YearSettings_Id] [int] NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_ShiftExchange_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_ShiftExchange] PRIMARY KEY CLUSTERED 
(
	[ShiftExchange_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_tbl_ShiftAdd_Location]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_ShiftAdd_Location]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_tbl_ShiftAdd_Location](
	[Shift_Lcoation_Id] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LocationId] [int] NULL,
	[ShiftDate] [datetime] NULL,
	[CreatedBy] [int] NULL,
	[CreatedOn] [datetime] NULL CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_CreatedOn]  DEFAULT (getdate()),
	[ModifiedBy] [int] NULL,
	[ModifiedOn] [datetime] NULL CONSTRAINT [DF_TA_tbl_ShiftAdd_Location_ModifiedOn]  DEFAULT (getdate()),
	[months]  AS (datepart(month,[ShiftDate])),
 CONSTRAINT [PK_TA_tbl_ShiftAdd_Location] PRIMARY KEY CLUSTERED 
(
	[Shift_Lcoation_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Shift]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Shift]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Shift](
	[Shift_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[Shift_Name] [nvarchar](50) NULL,
	[Shift_ShortName] [varchar](8) NULL,
	[Shift_Description] [nvarchar](255) NULL,
	[Shift_StartTime] [nvarchar](10) NULL,
	[Shift_EndTime] [nvarchar](10) NOT NULL,
	[Shift_FirstHalf_StartTime] [nvarchar](10) NULL,
	[Shift_FirstHalf_EndTime] [nvarchar](10) NULL,
	[Shift_SecondHalf_StartTime] [nvarchar](10) NULL,
	[Shift_SecondHalf_EndTime] [nvarchar](10) NULL,
	[Shift_GraceInTime] [nvarchar](10) NOT NULL,
	[Shift_GraceOutTime] [nvarchar](10) NULL,
	[Shift_BreakStartTime1] [nvarchar](10) NULL,
	[Shift_BreakEndTime1] [nvarchar](10) NULL,
	[Shift_BreakStartTime2] [nvarchar](10) NULL,
	[Shift_BreakEndTime2] [nvarchar](10) NULL,
	[Shift_BreakStartTime3] [nvarchar](10) NULL,
	[Shift_BreakEndTime3] [nvarchar](10) NULL,
	[Shift_MinTimeOT] [nvarchar](50) NULL,
	[Shift_MaxTimeOT] [nvarchar](50) NULL,
	[Shift_WorkingDay_OverTime] [float] NULL,
	[Shift_TotalWorkingHours] [nvarchar](50) NULL,
	[Shift_LunchOutTimeGrace] [nvarchar](10) NULL,
	[Shift_LunchInTimeGrace] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceBefore] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceAfter] [nvarchar](10) NULL,
	[Shift_LunchInTimeGraceBefore] [nvarchar](10) NULL,
	[Shift_LunchInTimeGraceAfter] [nvarchar](10) NULL,
	[Shift_LunchOutTimeGraceBeforeChk] [bit] NULL,
	[Shift_LunchOutTimeGraceAfterChk] [bit] NULL,
	[Shift_LunchInTimeGraceBeforeChk] [bit] NULL,
	[Shift_LunchInTimeGraceAfterChk] [bit] NULL,
	[Isdeleted] [bit] NULL,
	[Emp_ID] [nvarchar](50) NULL,
	[Shift_FirstHalfWorkingHours] [nvarchar](5) NULL,
	[Shift_SecondHalfWorkingHours] [nvarchar](5) NULL,
	[IsBreakDeducted] [bit] NULL,
	[DefaultShift] [bit] NULL,
	[ShiftType] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
	[24HrsShift] [bit] NULL,
	[isStraightShift] [bit] NULL,
	[StraightPresentTime] [nvarchar](10) NULL,
	[BreakHours] [nvarchar](6) NULL,
	[empCategory] [int] NULL DEFAULT ((1)),
	[specialOvertime_start1] [varchar](10) NULL,
	[specialOvertime_start2] [varchar](10) NULL,
	[MaxShiftWorkHours] [varchar](10) NOT NULL CONSTRAINT [Defaultconstraint_WorkHours]  DEFAULT ('00:00'),
 CONSTRAINT [PK_TA_Tbl_Shift] PRIMARY KEY CLUSTERED 
(
	[Shift_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Results]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Results]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Results](
	[CardNo] [nvarchar](10) NULL,
	[EmpName] [nvarchar](100) NULL,
	[Department] [nvarchar](50) NULL,
	[SwipeData] [smalldatetime] NULL,
	[Swipes] [ntext] NULL,
	[SwipesCount] [nvarchar](50) NULL,
	[TotalHrs] [nvarchar](50) NULL,
	[d1] [nvarchar](20) NULL,
	[d2] [nvarchar](20) NULL,
	[d3] [nvarchar](20) NULL,
	[d4] [nvarchar](20) NULL,
	[d5] [nvarchar](20) NULL,
	[d6] [nvarchar](20) NULL,
	[d7] [nvarchar](20) NULL,
	[d8] [nvarchar](20) NULL,
	[d9] [nvarchar](20) NULL,
	[d10] [nvarchar](20) NULL,
	[d11] [nvarchar](20) NULL,
	[d12] [nvarchar](20) NULL,
	[d13] [nvarchar](20) NULL,
	[d14] [nvarchar](20) NULL,
	[d15] [nvarchar](20) NULL,
	[d16] [nvarchar](20) NULL,
	[d17] [nvarchar](20) NULL,
	[d18] [nvarchar](20) NULL,
	[d19] [nvarchar](20) NULL,
	[d20] [nvarchar](20) NULL,
	[d21] [nvarchar](20) NULL,
	[d22] [nvarchar](20) NULL,
	[d23] [nvarchar](20) NULL,
	[d24] [nvarchar](20) NULL,
	[d25] [nvarchar](20) NULL,
	[d26] [nvarchar](20) NULL,
	[d27] [nvarchar](20) NULL,
	[d28] [nvarchar](20) NULL,
	[d29] [nvarchar](20) NULL,
	[d30] [nvarchar](20) NULL,
	[d31] [nvarchar](20) NULL,
	[MusterComplete] [tinyint] NULL,
	[Emp_Location] [nvarchar](20) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Religion]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Religion]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Religion](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Description] [nvarchar](250) NULL,
	[IsDeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl_Religion] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_tbl_ReasonForNonProcessedData]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_ReasonForNonProcessedData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_ReasonForNonProcessedData](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ReasonId] [int] NULL,
	[Reasons] [nvarchar](max) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_PunchtypeRemarks]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PunchtypeRemarks]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_PunchtypeRemarks](
	[Remarks_id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_Type] [nvarchar](10) NULL,
	[PunchType] [nvarchar](50) NULL,
	[Punchtype_Remarks] [nvarchar](max) NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF__ta_tbl_Pu__Times__403C232B]  DEFAULT (getdate())
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ProjectTerminals]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ProjectTerminals]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ProjectTerminals](
	[Project_Terminal_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Project_Id] [bigint] NOT NULL,
	[Terminal_id] [bigint] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_tbl_ProjectTaskList]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_ProjectTaskList]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_tbl_ProjectTaskList](
	[ProjectID] [bigint] NOT NULL,
	[TaskID] [int] IDENTITY(1,1) NOT NULL,
	[TaskName] [nvarchar](max) NULL,
	[TaskHours] [varchar](25) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Project]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Project]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Project](
	[Project_Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Project_Name] [varchar](250) NULL,
	[Project_Code] [varchar](15) NULL,
	[Client_Name] [varchar](150) NULL,
	[Project_Description] [varchar](500) NULL,
	[Project_StartTime] [datetime] NULL,
	[Project_EndTime] [datetime] NULL,
	[Project_Status] [varchar](15) NULL,
	[IsDeleted] [bit] NULL CONSTRAINT [DF_TA_Tbl_Project_IsDeleted]  DEFAULT ((0)),
	[Created_By] [bigint] NULL,
	[Created_On] [datetime] NULL,
	[Modified_By] [bigint] NULL,
	[Modified_On] [datetime] NULL,
	[LevelID] [int] NULL,
	[Mandays] [int] NULL,
	[ManHours] [int] NULL,
 CONSTRAINT [PK__TA_Tbl_P__1CB92E03DA08B5D4] PRIMARY KEY CLUSTERED 
(
	[Project_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ProcessedData]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ProcessedData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ProcessedData](
	[Process_Rec_ID] [bigint] IDENTITY(1,1) NOT NULL,
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Date] [datetime] NULL,
	[Shift_Id] [int] NULL,
	[InTime] [nvarchar](25) NULL,
	[OutTime] [nvarchar](25) NULL,
	[HrsWork] [nvarchar](10) NULL,
	[HrsOT] [nvarchar](10) NULL,
	[NormOT] [nvarchar](10) NULL,
	[OffOT] [nvarchar](10) NULL,
	[HolOT] [nvarchar](10) NULL,
	[EarlyOut] [nvarchar](10) NULL,
	[LateIn] [nvarchar](10) NULL,
	[Attendance] [nvarchar](20) NULL,
	[WorkHrs] [nvarchar](10) NULL,
	[HrsLess] [nvarchar](10) NULL,
	[HrsExtra] [nvarchar](10) NULL,
	[LateInMins] [float] NULL,
	[EarlyOutMins] [float] NULL,
	[ExtraMins] [float] NULL,
	[OtMins] [float] NULL,
	[OvertimeStatus] [nvarchar](50) NULL,
	[TotalDays] [numeric](18, 1) NULL,
	[LeaveCode] [nvarchar](20) NULL,
	[LateEntryReason] [nvarchar](260) NULL,
	[EarlyOutReason] [nvarchar](260) NULL,
	[BreakOut] [nvarchar](25) NULL,
	[BreakIn] [nvarchar](25) NULL,
	[BreakHours] [nvarchar](10) NULL,
	[BreakLate] [nvarchar](10) NULL,
	[BreakLateMins] [float] NULL,
	[TotalLate] [nvarchar](10) NULL,
	[TotalLateMins] [float] NULL,
	[ProcessFlag] [int] NULL CONSTRAINT [DF_TA_Tbl_ProcessedData_ProcessFlag]  DEFAULT ((0)),
	[Status] [nvarchar](50) NULL,
	[FNAttendanceCode] [nvarchar](15) NULL,
	[ANAttendanceCode] [nvarchar](15) NULL,
	[DinnerOut] [nvarchar](25) NULL,
	[DinnerIn] [nvarchar](25) NULL,
	[DinnerHours] [nvarchar](10) NULL,
	[DinnerLate] [nvarchar](10) NULL,
	[DinnerLateMins] [float] NULL,
	[LateExit] [bit] NULL,
	[EarlyEntry] [bit] NULL,
	[BreakHrs] [nvarchar](10) NULL,
	[LunchHrs] [nvarchar](10) NULL,
	[BreakHrsInMins] [float] NULL,
	[LunchHrsInMins] [float] NULL,
	[InNotation] [char](1) NULL,
	[OutNotation] [char](1) NULL,
	[Shift_StartTime] [nvarchar](20) NULL,
	[Shift_EndTime] [nvarchar](20) NULL,
	[PermissionHrs] [nvarchar](10) NULL,
	[PermissionHrsInMins] [float] NULL,
	[HoursWorkInMins] [float] NULL,
	[WorkHoursInMins] [float] NULL,
	[LessHoursInMins] [float] NULL,
	[IsOnduty] [bit] NULL,
	[LeaveStatus] [nvarchar](50) NULL,
	[PermissionStatus] [nvarchar](50) NULL,
	[NormOtmins] [float] NULL,
	[OffOtmins] [float] NULL,
	[HolOtMins] [float] NULL,
	[CLAvailed]  AS (case when [FNAttendanceCode]='CL' AND [ANAttendanceCode]='CL' then (1) when [FNAttendanceCode]='CL' AND [ANAttendanceCode]<>'CL' then (0.5) when [FNAttendanceCode]<>'CL' AND [ANAttendanceCode]='CL' then (0.5) else (0) end),
	[YearSettingId] [int] NULL,
	[LeaveType_Id] [int] NULL,
	[Holiday_Description] [nvarchar](250) NULL,
	[EarlyInmins] [int] NULL,
	[EarlyInHrs] [varchar](20) NULL,
	[lateExitMins] [int] NULL,
	[LateExitHours] [varchar](20) NULL,
	[ActNormOTMins] [float] NULL,
	[ActOffOTMins] [float] NULL,
	[ActHolOTMins] [float] NULL,
	[ActOTMins] [float] NULL,
	[ActHrsOT] [nvarchar](20) NULL,
	[ActNormOT] [nvarchar](20) NULL,
	[ActOffOT] [nvarchar](20) NULL,
	[ActHolOT] [nvarchar](20) NULL,
	[Inpunch] [varchar](20) NULL,
	[Outpunch] [varchar](20) NULL,
	[Indate] [datetime] NULL,
	[Outdate] [datetime] NULL,
	[SPEC_NormOT1] [varchar](10) NULL,
	[SPEC_NormOTMins1] [int] NULL,
	[SPEC_NormOT2] [varchar](10) NULL,
	[SPEC_NormOTMins2] [int] NULL,
	[SPEC_OffOT1] [varchar](10) NULL,
	[SPEC_OffOTMins1] [int] NULL,
	[SPEC_OffOT2] [varchar](10) NULL,
	[SPEC_OffOTMins2] [int] NULL,
	[SPEC_HOLOT1] [varchar](10) NULL,
	[SPEC_HOLOTMins1] [int] NULL,
	[SPEC_HOLOT2] [varchar](10) NULL,
	[SPEC_HOLOTMins2] [int] NULL,
	[InLocation] [varchar](500) NULL,
	[OutLocation] [varchar](500) NULL,
 CONSTRAINT [PK_TA_Tbl_ProcessedData] PRIMARY KEY CLUSTERED 
(
	[Process_Rec_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ProcessedData]') AND name = N'IDX_EmailScheduler_GetEmployeeEmail')
CREATE NONCLUSTERED INDEX [IDX_EmailScheduler_GetEmployeeEmail] ON [dbo].[TA_Tbl_ProcessedData] 
(
	[Employee_Code_Id] ASC,
	[Date] ASC,
	[ProcessFlag] ASC
)
INCLUDE ( [Shift_Id]) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ta_tbl_PrevPermissionDetails_EastMan]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PrevPermissionDetails_EastMan]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_PrevPermissionDetails_EastMan](
	[AutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[Cur_Perm_ID] [bigint] NULL,
	[Prev_Perm_ID] [bigint] NULL,
	[Timestamp] [datetime] NULL DEFAULT (getdate()),
	[Prev_Perm_date] [varchar](20) NULL,
	[Prev_Perm_ShiftTime] [varchar](20) NULL,
	[Prev_Perm_InTime] [varchar](20) NULL,
	[Prev_Perm_LateHours] [varchar](20) NULL,
	[Prev_Perm_Reason] [varchar](500) NULL,
	[Prev_Perm_ReceivedDate] [varchar](20) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Preferences]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Preferences]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Preferences](
	[isDomain] [int] NULL,
	[DomainName] [nvarchar](500) NULL,
	[DomainAdminUserName] [nvarchar](max) NULL,
	[DomainAdminPassword] [nvarchar](max) NULL,
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Level]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Level]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Level](
	[levelID] [int] IDENTITY(1,1) NOT NULL,
	[levelName] [nvarchar](255) NULL,
	[parentLevelID] [int] NULL CONSTRAINT [DF_TA_Tbl_Level_parentLevelID]  DEFAULT ((0)),
	[isDeleted] [bit] NULL DEFAULT ((0)),
	[timeStamp] [datetime] NULL,
	[emp_Id] [nvarchar](50) NULL,
 CONSTRAINT [PK_TA_Tbl_Level] PRIMARY KEY CLUSTERED 
(
	[levelID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveType]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveType](
	[LeaveType_Id] [int] IDENTITY(1,1) NOT NULL,
	[LeaveType] [nvarchar](10) NOT NULL,
	[LeaveDescription] [nvarchar](250) NOT NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_LeaveType_IsDeleted]  DEFAULT ((1)),
	[Emp_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL,
	[CountFactor] [bit] NOT NULL DEFAULT ((0)),
	[Employeecategory] [int] NULL,
	[EmployeeType] [int] NULL,
	[Gender] [varchar](10) NULL,
	[Religion] [int] NULL,
	[isWFH] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveType] PRIMARY KEY CLUSTERED 
(
	[LeaveType_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_LeaveSettings]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeaveSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeaveSettings](
	[MailSettingId] [bigint] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NULL,
	[Approval] [bit] NULL,
	[FirstLevelIntimation] [bit] NULL,
	[SecondLevelIntimation] [bit] NULL,
	[ApprovalCC] [varchar](8000) NULL,
	[ToMail_DailyReport] [varchar](8000) NULL,
	[CCMail_DailyReport] [varchar](8000) NULL,
 CONSTRAINT [PK_TA_Tbl_LeaveSettings] PRIMARY KEY CLUSTERED 
(
	[MailSettingId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_mobileClockInAndOut]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_mobileClockInAndOut]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_mobileClockInAndOut](
	[Autoid] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeCodeID] [varchar](20) NULL,
	[ClockDate] [datetime] NULL,
	[Clock_Time] [varchar](15) NULL,
	[PunchType] [varchar](20) NULL,
	[InsertedOn] [datetime] NULL,
	[Latitude_value] [varchar](20) NULL,
	[Longitude_value] [varchar](20) NULL,
	[Clock_Address] [varchar](500) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ta_tbl_MatchedPunches]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_MatchedPunches]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_MatchedPunches](
	[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
	[Clk_EmpId] [nvarchar](20) NULL,
	[Clk_InDeviceId] [nvarchar](20) NULL,
	[Clk_InDate] [datetime] NULL,
	[Clk_InTime] [datetime] NULL,
	[Clk_InPunchType] [nvarchar](25) NULL,
	[Clk_OutDeviceId] [nvarchar](20) NULL,
	[Clk_OutDate] [datetime] NULL,
	[Clk_OutTime] [datetime] NULL,
	[Clk_OutPunchType] [nvarchar](25) NULL,
	[Clk_Date] [datetime] NULL,
	[PunchDiffInHours]  AS (isnull([clk_OutTime]-[clk_Intime],'')),
	[PunchDiffInMin]  AS (isnull(datepart(hour,[clk_OutTime]-[clk_Intime])*(60)+datepart(minute,[clk_OutTime]-[clk_Intime]),(0)))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_ManualTimeEntrybck]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_ManualTimeEntrybck]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_ManualTimeEntrybck](
	[ManualTimeEntry_Id] [int] IDENTITY(1,1) NOT NULL,
	[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
	[ManualTimeEntry_Date] [datetime] NULL,
	[ManualTimeEntry_InDate] [datetime] NULL,
	[ManualTimeEntry_InTime] [nvarchar](50) NULL,
	[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_OutDate] [datetime] NULL,
	[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
	[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_InReaderID] [int] NULL,
	[ManualTimeEntry_OutReaderID] [int] NULL,
	[ManualTimeEntry_Reason] [nvarchar](255) NULL,
	[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
	[Route_Id] [int] NULL,
	[Clk_Process] [char](1) NULL,
	[ManualTimeEntry_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ManualTimeEntry]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ManualTimeEntry]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ManualTimeEntry](
	[ManualTimeEntry_Id] [int] IDENTITY(1,1) NOT NULL,
	[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
	[ManualTimeEntry_Date] [datetime] NULL,
	[ManualTimeEntry_InDate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_InDate]  DEFAULT (NULL),
	[ManualTimeEntry_InTime] [nvarchar](50) NULL,
	[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_OutDate] [datetime] NULL CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_ManualTimeEntry_OutDate]  DEFAULT (NULL),
	[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
	[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
	[ManualTimeEntry_InReaderID] [int] NULL,
	[ManualTimeEntry_OutReaderID] [int] NULL,
	[ManualTimeEntry_Reason] [nvarchar](255) NULL,
	[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
	[Route_Id] [int] NULL,
	[Clk_Process] [nvarchar](1) NULL,
	[ManualTimeEntry_Status] [nvarchar](25) NULL,
	[Isdeleted] [bit] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_ManualTimeEntry_TimeStamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[IsDiscrepancyEntry] [bit] NULL,
	[IsOnDuty] [bit] NULL,
	[Shift_Id] [int] NULL,
	[Shift_Date] [datetime] NULL,
	[IsImported] [int] NULL,
	[OnDuty_ID] [int] NULL,
	[modify_By] [int] NULL,
	[modify_date] [datetime] NULL,
	[Latitude_value] [varchar](20) NULL,
	[Longitude_value] [varchar](20) NULL,
	[Clock_Address] [varchar](500) NULL,
 CONSTRAINT [PK_TA_Tbl_ManualTimeEntry] PRIMARY KEY CLUSTERED 
(
	[ManualTimeEntry_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Permission]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Permission]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Permission](
	[Permission_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [bigint] NOT NULL,
	[Permission_AppliedDate] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_Permission_Permission_AppliedDate]  DEFAULT (getdate()),
	[Permission_Date] [datetime] NOT NULL,
	[Permission_Type] [nvarchar](50) NULL,
	[Permission_FromTime] [datetime] NOT NULL,
	[Permission_ToTime] [datetime] NOT NULL,
	[Permission_Reason] [nvarchar](1000) NULL,
	[Permission_Status] [nvarchar](50) NULL,
	[Emp_Id_Sanction] [int] NULL,
	[Remarks] [nvarchar](1000) NULL,
	[IsDeleted] [bit] NOT NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_Permission_TimeStamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NULL,
	[YearSettings_Id] [int] NULL,
	[UnPlanned] [int] NULL DEFAULT ((0)),
	[CCMail] [varchar](3000) NULL,
	[Permission_Hours] [varchar](5) NULL,
	[No_Of_Hours] [nvarchar](10) NULL,
 CONSTRAINT [PK_TA_Tbl_Permission] PRIMARY KEY CLUSTERED 
(
	[Permission_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocationoldbeforeshift](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocationbck]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocationbck]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocationbck](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_tbl_TimeZones]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_TimeZones]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_TimeZones](
	[TimeZoneID] [int] NOT NULL,
	[TimeZoneName] [varchar](100) NOT NULL,
	[TimeZoneDesc] [varchar](10) NULL,
	[HoursToBeAdded] [int] NOT NULL,
	[MinToBeAdded] [int] NOT NULL,
 CONSTRAINT [PK_Ta_tbl_TimeZones] PRIMARY KEY CLUSTERED 
(
	[TimeZoneID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalMapping]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TerminalMapping]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TerminalMapping](
	[TerMap_Id] [int] IDENTITY(1,1) NOT NULL,
	[EntranceName] [nvarchar](50) NOT NULL,
	[EntranceDescription] [nvarchar](50) NULL,
	[InTerminalID] [int] NULL,
	[OutTerminalID] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_TerminalMapping] PRIMARY KEY CLUSTERED 
(
	[TerMap_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_tbl_TerminalDatatype]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_TerminalDatatype]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_tbl_TerminalDatatype](
	[TerminalDatatype_ID] [int] IDENTITY(1,1) NOT NULL,
	[Raw_Data_Format] [nvarchar](25) NOT NULL,
	[FileType] [nvarchar](15) NOT NULL,
	[File_SourcePath] [nvarchar](2000) NULL,
	[File_BackupPath] [nvarchar](2000) NULL,
	[File_BackupType] [nvarchar](10) NULL,
	[Delimiter_NoOfFields] [int] NULL,
	[Delimiter_Delimiter] [char](5) NULL,
	[Delimiter_StringEnclosedBy] [nvarchar](5) NULL,
	[Delimiter_ReaderNo] [nvarchar](10) NULL,
	[Delimiter_CardNo] [nvarchar](10) NULL,
	[Delimiter_DateTimeBit] [bit] NULL,
	[Delimiter_Date] [nvarchar](10) NULL,
	[Delimiter_Time] [nvarchar](10) NULL,
	[Delimiter_DateTime] [nvarchar](10) NULL,
	[Delimiter_Type] [nvarchar](10) NULL,
	[Delimiter_TransactionIdentifier] [nvarchar](10) NULL,
	[FixedLength_ReaderNoFrom] [int] NULL,
	[FixedLength_ReaderNoTo] [int] NULL,
	[FixedLength_CardNoFrom] [int] NULL,
	[FixedLength_CardNoTo] [int] NULL,
	[FixedLength_DateTimeBit] [bit] NULL,
	[FixedLength_DateFrom] [int] NULL,
	[FixedLength_DateTo] [int] NULL,
	[FixedLength_TimeFrom] [int] NULL,
	[FixedLength_TimeTo] [int] NULL,
	[FixedLength_DateTimeFrom] [int] NULL,
	[FixedLength_DateTimeTo] [int] NULL,
	[FixedLength_TypeFrom] [int] NULL,
	[FixedLength_TypeTo] [int] NULL,
	[FixedLength_TransactionIdentifierFrom] [int] NULL,
	[FixedLength_TransactionIdentifierTo] [int] NULL,
	[ConnectionString] [nvarchar](2000) NULL,
	[TableName] [nvarchar](50) NULL,
	[MDB_ReaderNo] [nvarchar](25) NULL,
	[MDB_CardNo] [nvarchar](25) NULL,
	[MDB_DateTimeBit] [bit] NULL,
	[MDB_Date] [nvarchar](25) NULL,
	[MDB_Time] [nvarchar](25) NULL,
	[MDB_DateTime] [nvarchar](25) NULL,
	[MDB_Type] [nvarchar](25) NULL,
	[MDB_TransactionIdentifier] [nvarchar](25) NULL,
	[RDBMS_ReaderNo] [nvarchar](25) NULL,
	[RDBMS_CardNo] [nvarchar](25) NULL,
	[RDBMS_DateTimeBit] [bit] NULL,
	[RDBMS_Date] [nvarchar](25) NULL,
	[RDBMS_Time] [nvarchar](25) NULL,
	[RDBMS_DateTime] [nvarchar](25) NULL,
	[RDBMS_Type] [nvarchar](25) NULL,
	[RDBMS_TransactionIdentifier] [nvarchar](25) NULL,
	[RDBMS_MDB_Flag] [nvarchar](25) NULL,
	[IsEmployeeId] [bit] NULL,
	[DateTimeFormat] [nvarchar](40) NULL,
	[DateFormat] [nvarchar](15) NULL,
	[TimeFormat] [nvarchar](15) NULL,
	[IsEncrypted] [bit] NULL,
	[TransactionIdentifierBit] [bit] NULL,
	[TransactionIdentifierValue] [nvarchar](50) NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[BrandId] [int] NULL,
	[IsFreeScan] [int] NULL,
 CONSTRAINT [PK_TA_tbl_TerminalDatatype] PRIMARY KEY CLUSTERED 
(
	[TerminalDatatype_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_TerminalBrand]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TerminalBrand]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TerminalBrand](
	[BrandID] [int] IDENTITY(1,1) NOT NULL,
	[DisplayName] [nvarchar](500) NULL,
	[KeyValue] [varchar](500) NULL,
 CONSTRAINT [PK_TA_Tbl_TerminalBrand] PRIMARY KEY CLUSTERED 
(
	[BrandID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Terminal]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Terminal](
	[Terminal_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_ReaderID] [nvarchar](10) NULL,
	[Terminal_Name] [nvarchar](50) NOT NULL,
	[Terminal_Description] [nvarchar](250) NOT NULL,
	[TerminalDatatype_ID] [int] NULL,
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Terminal_TimeStamp]  DEFAULT (getdate()),
	[Emp_ID] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Terminal] PRIMARY KEY CLUSTERED 
(
	[Terminal_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemWeekday]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TemWeekday](
	[TempWeekday_Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_FromDate] [datetime] NOT NULL,
	[TempWeekday_ToDate] [datetime] NOT NULL,
	[ClosingTime] [nvarchar](50) NULL,
	[Reason] [nvarchar](255) NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL,
	[TimeStamp] [datetime] NOT NULL DEFAULT (getdate()),
	[ShiftId] [nvarchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_TemWeekday] PRIMARY KEY CLUSTERED 
(
	[TempWeekday_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TempUpdateEmployee]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempUpdateEmployee]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TempUpdateEmployee](
	[employee_code] [bigint] NOT NULL,
	[first_name] [nvarchar](50) NULL,
	[last_name] [nvarchar](50) NULL,
	[birth_date] [datetime] NULL,
	[local_addr1] [nvarchar](50) NULL,
	[local_addr2] [nvarchar](50) NULL,
	[local_addr3] [nvarchar](50) NULL,
	[join_date] [datetime] NULL,
	[section_name] [nvarchar](50) NULL,
	[desg_name] [nvarchar](50) NULL,
	[category_name] [nvarchar](50) NULL,
	[basic] [numeric](16, 3) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TempShiftAllocation]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempShiftAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TempShiftAllocation](
	[EmpID] [int] NOT NULL,
	[EmployeeId] [nvarchar](50) NOT NULL,
	[EmployeeName] [nvarchar](50) NOT NULL,
	[LoginEmployeeId] [int] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_WindowsServiceFlag]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_WindowsServiceFlag]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_WindowsServiceFlag](
	[WindowsServiceFlag] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Version]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Version]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Version](
	[VersionId] [bigint] IDENTITY(1,1) NOT NULL,
	[DatabaseVersionNo] [float] NULL,
	[DatabaseVersionName] [nvarchar](250) NULL,
	[ApplicationVersionNo] [float] NULL,
	[ApplicationVersionName] [nvarchar](250) NULL,
	[DatabaseVersionDate] [datetime] NULL,
	[ApplicationVersionDate] [datetime] NULL,
 CONSTRAINT [PK_TA_Tbl_Version] PRIMARY KEY CLUSTERED 
(
	[VersionId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_userRights]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_userRights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_userRights](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[groupName] [nvarchar](50) NULL,
	[groupId] [int] NULL,
	[pageId] [float] NULL,
	[pageGroupId] [int] NULL,
	[addPrv] [bit] NULL,
	[modifyPrv] [bit] NULL,
	[deletePrv] [bit] NULL,
	[viewPrv] [bit] NULL,
	[isDeleted] [bit] NULL CONSTRAINT [DF_TA_Tbl_userGroup_isDeleted]  DEFAULT ((0)),
	[timeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_userGroup_timeStamp_1]  DEFAULT (getdate()),
	[employeeId] [decimal](18, 0) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Usergroup]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Usergroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Usergroup](
	[groupId] [int] IDENTITY(1,1) NOT NULL,
	[groupName] [nvarchar](50) NULL,
	[IndividualUsers] [bit] NULL,
	[hasSpecialRights] [bit] NULL,
	[timeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Usergroup_timeStamp_2]  DEFAULT (getdate()),
	[isDeleted] [bit] NULL CONSTRAINT [DF_TA_Tbl_Usergroup_isDeleted_1]  DEFAULT ((0)),
	[Emp_Id] [nchar](10) NULL,
	[ReportsBasedOn] [bit] NULL CONSTRAINT [DF_TA_Tbl_Usergroup_ReportsBasedOn]  DEFAULT ((0)),
	[AllowLeaveApprovalPastEntry] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Type]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Type](
	[TypeId] [bigint] IDENTITY(1,1) NOT NULL,
	[TypeName] [nvarchar](50) NULL,
	[IsDeleted] [bit] NULL,
	[EmpId] [bigint] NULL,
	[IsFlexible] [bit] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Vehicle]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Vehicle]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Transportation_Vehicle](
	[VehicleId] [int] IDENTITY(1,1) NOT NULL,
	[VehicleNo] [nvarchar](20) NOT NULL,
	[VehicleDescription] [nvarchar](250) NOT NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_IsDeleted]  DEFAULT ((1)),
	[Emp_Id] [int] NULL,
	[Time_stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Transportation_Vehicle_Time_stamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_Transportation_Vehicle] PRIMARY KEY CLUSTERED 
(
	[VehicleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Route]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Route]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Transportation_Route](
	[RouteId] [int] IDENTITY(1,1) NOT NULL,
	[VehicleId] [int] NULL,
	[RouteName] [nvarchar](20) NULL,
	[RouteDescription] [nvarchar](250) NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_Transportation_Route_IsDeleted]  DEFAULT ((1))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation_Mapping]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation_Mapping]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Transportation_Mapping](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[VehicleId] [int] NOT NULL,
	[RouteId] [int] NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_Transportation_Mapping_IsDeleted]  DEFAULT ((1))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Transportation]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Transportation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Transportation](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[VehicleNo] [int] NOT NULL,
	[RouteName] [nvarchar](50) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_Trace]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Trace]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_Trace](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[PageName] [nvarchar](200) NULL,
	[ErrDescription] [nvarchar](2000) NULL,
	[DateOfError] [datetime] NULL,
 CONSTRAINT [PK_Ta_Tbl_Trace] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_TotalBreakHours]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_TotalBreakHours]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_TotalBreakHours](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ShiftDate] [datetime] NULL,
	[Employee_Code_Id] [nvarchar](10) NOT NULL,
	[TotalBreakmin] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TitleMapping]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TitleMapping]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TitleMapping](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Company_Id] [int] NOT NULL,
	[Region_Id] [int] NOT NULL,
	[Branch_Id] [int] NOT NULL,
	[Department_Id] [int] NOT NULL,
	[Section_Id] [int] NOT NULL,
	[TitleId] [int] NOT NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_TitleMapping_IsDeleted]  DEFAULT ((1))
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSGateway]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSGateway]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_SMSGateway](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[ServiceUrl] [varchar](max) NULL,
	[DestinationKey] [varchar](100) NULL,
	[MessageKey] [varchar](100) NULL,
	[TimeStamp] [datetime] NULL DEFAULT (getdate()),
	[PhNo] [varchar](20) NULL,
	[EmployeeID] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftSettings]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ShiftSettings](
	[ShiftSettingId] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NULL,
	[MaxHoursBeforeShift] [nvarchar](50) NULL,
	[MaxHoursAfterShift] [nvarchar](50) NULL,
	[ShiftBreak] [nvarchar](50) NULL,
	[ShiftMaxBreakHours] [nvarchar](50) NULL,
	[MonthlyWorkingHours] [nvarchar](50) NULL,
	[WeeklyWorkingHours] [nvarchar](50) NULL,
	[EmpID] [nvarchar](50) NULL,
	[HolidayOT] [decimal](18, 2) NULL,
	[WeekOffOT] [decimal](18, 2) NULL,
	[otOption] [nvarchar](50) NULL,
	[DefaultMonthClosureDate] [datetime] NULL,
	[IsFlexible] [bit] NULL,
	[FlexibleFlag] [tinyint] NULL,
	[OTRoundoffEnable] [bit] NULL,
	[FullDayAttendanceHrs] [nvarchar](5) NULL,
	[HalfDayAttendanceHrs] [nvarchar](5) NULL,
	[HalfDayAttendance] [bit] NULL,
	[FullDayAttendance] [bit] NULL,
	[DefaultLunchHours] [nvarchar](5) NULL,
	[MaxLunchHours] [nvarchar](5) NULL,
	[WeeklyOffStartHours] [nvarchar](5) NULL,
	[IgnoreDuplicatePunch] [bit] NULL,
	[PunchInterval] [nvarchar](5) NULL,
	[AfterShiftTime] [bit] NULL,
	[BeforeShiftTime] [bit] NULL,
	[DefinedWorkhrs] [bit] NULL,
	[NoOfSuccessiveDaysInYear] [int] NULL,
	[CompensationValitityDays] [int] NULL,
	[VaildityCompOffDays] [int] NULL,
	[HalfDayCompOff] [varchar](5) NULL,
	[FullDayCompOff] [varchar](50) NULL,
	[LateEntry] [bit] NULL,
	[EarlyEntry] [bit] NULL,
	[EarlyExit] [bit] NULL,
	[LateExit] [bit] NULL,
	[TimeStamp] [datetime] NULL,
	[TimeStamp1] [datetime] NULL,
	[IsLunchDeduction] [bit] NULL,
	[LunchDeductionHours] [nvarchar](10) NULL,
	[MaxWorkPlaceInHours] [nvarchar](5) NULL DEFAULT ('00:03'),
	[Flexi_AfterShiftTime] [bit] NULL CONSTRAINT [DF__TA_Tbl_Sh__Flexi__28ED12D1]  DEFAULT ((0)),
	[Flexi_BeforeShiftTime] [bit] NULL CONSTRAINT [DF__TA_Tbl_Sh__Flexi__29E1370A]  DEFAULT ((0)),
	[Flexi_DefinedWorkhrs] [bit] NULL CONSTRAINT [DF__TA_Tbl_Sh__Flexi__2AD55B43]  DEFAULT ((0)),
	[MaxHoursBeforeShift_24HrsShift] [nvarchar](50) NULL,
	[WeeklyOffStartHours_24HrsShift] [nvarchar](50) NULL,
	[CumulativeWeekStartDay] [nvarchar](10) NULL,
	[CumulativeWeekEndDay] [nvarchar](10) NULL,
	[MonthStartDay] [int] NULL,
	[MonthEndDay] [int] NULL,
	[isRequestingforCompOff] [bit] NULL,
	[FirstAndLast] [bit] NULL DEFAULT ((0)),
	[Carry_Forward_COff_Year] [int] NULL DEFAULT ((0)),
	[MapKey] [varchar](max) NULL,
	[SpecialOverTime1] [int] NULL,
	[SpecialOverTime2] [int] NULL,
	[LateMinsPerDay] [int] NOT NULL CONSTRAINT [Defaultconstraint1]  DEFAULT ((0)),
	[LateDaysPerMonth] [int] NOT NULL CONSTRAINT [Defaultconstraints2]  DEFAULT ((0)),
	[EarlyExitMinsPerDay] [int] NULL CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitMinsPerDay]  DEFAULT ((0)),
	[EarlyExitDaysPerMonth] [int] NULL CONSTRAINT [DF_TA_Tbl_ShiftSettings_EarlyExitDaysPerMonth]  DEFAULT ((0)),
	[EnableAbsent] [int] NOT NULL CONSTRAINT [Defaultconstraints1]  DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_ShiftSettings] PRIMARY KEY CLUSTERED 
(
	[ShiftSettingId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTags]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTags]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_SMSTags](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Tags] [varchar](50) NULL,
	[TemplateName] [varchar](50) NULL,
	[Timestamp] [datetime] NULL DEFAULT (getdate()),
 CONSTRAINT [PK__Ta_Tbl_S__3213E83FEB774D5C] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ta_tbl_taskprogressStatus]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_taskprogressStatus]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_taskprogressStatus](
	[ProgressAutoID] [bigint] IDENTITY(1,1) NOT NULL,
	[TaskDetailID] [bigint] NULL,
	[ApprovedHours] [varchar](10) NULL,
	[ApprovedBy] [bigint] NULL,
	[ApprovedDate] [datetime] NULL,
	[Comments] [varchar](500) NULL,
	[Status] [varchar](500) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_TaskProgressDetails]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_TaskProgressDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_TaskProgressDetails](
	[TaskDetailID] [bigint] IDENTITY(1,1) NOT NULL,
	[TaskID] [int] NULL,
	[ProjectID] [bigint] NULL,
	[ShiftDate] [datetime] NULL,
	[TaskHours] [varchar](10) NULL,
	[TaskDescription] [varchar](5000) NULL,
	[SpentHours] [varchar](10) NULL,
	[TaskSubmittedDate] [datetime] NULL,
	[TaskSubmittedBy] [bigint] NULL,
	[TaskModifiedDate] [datetime] NULL,
	[TaskModifiedBy] [bigint] NULL,
	[ModificationReason] [varchar](5000) NULL,
	[ApprovedHours] [varchar](10) NULL,
	[ApprovedBy1] [bigint] NULL,
	[ApprovedDate1] [datetime] NULL,
	[ApprovedBy2] [bigint] NULL,
	[ApprovedDate2] [datetime] NULL,
	[Status] [varchar](10) NULL,
	[isSubmitted_Completely] [bit] NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_tbl_specialOvertimeDetails]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_tbl_specialOvertimeDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_tbl_specialOvertimeDetails](
	[Employee_code_id] [varchar](50) NULL,
	[Date] [datetime] NULL,
	[Modified_Spec_NormOTMins1] [int] NULL,
	[Modified_Spec_NormOTMins2] [int] NULL,
	[Modified_Spec_OffOTMins1] [int] NULL,
	[Modified_Spec_OffOTMins2] [int] NULL,
	[Modified_Spec_HolOTMins1] [int] NULL,
	[Modified_Spec_HolOTMins2] [int] NULL,
	[Modified_Spec_NormOTHrs1] [varchar](10) NULL,
	[Modified_Spec_NormOTHrs2] [varchar](10) NULL,
	[Modified_Spec_OffOTHrs1] [varchar](10) NULL,
	[Modified_Spec_OffOTHrs2] [varchar](10) NULL,
	[Modified_Spec_HolOTHrs1] [varchar](10) NULL,
	[Modified_Spec_HolOTHrs2] [varchar](10) NULL,
	[Inserted_By] [bigint] NULL,
	[Inserted_Date] [datetime] NULL,
	[Modified_By] [bigint] NULL,
	[Modified_Date] [datetime] NULL,
	[Rec_ID] [bigint] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplates]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplates]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_SMSTemplates](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[TemplateName] [varchar](50) NULL,
	[Message] [varchar](max) NULL,
	[Status] [bit] NULL,
	[LastModified] [datetime] NULL DEFAULT (getdate()),
	[ModifiedBy] [int] NULL,
	[First_TriggeringTime] [varchar](5) NULL,
	[Second_TriggeringTime] [varchar](5) NULL,
	[ToEmployee] [bit] NULL DEFAULT ((0)),
	[LessHrsLimitation] [varchar](5) NULL,
	[Continue_AbsentDays] [int] NULL,
	[Tags] [varchar](max) NULL,
 CONSTRAINT [PK__Ta_Tbl_S__3213E83F141C6E29] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TempTitle]    Script Date: 03/25/2021 10:16:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempTitle]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TempTitle](
	[TitleName] [nvarchar](50) NOT NULL,
	[TitleDescription] [nvarchar](250) NULL,
	[LevelID] [int] NULL,
	[LeavePolicyID] [int] NULL,
	[GradeID] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [bit] NOT NULL,
	[Time_Stamp] [datetime] NULL,
	[TitleId] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TempEmployee]    Script Date: 03/25/2021 10:16:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempEmployee]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TempEmployee](
	[Employee_Id] [int] NULL,
	[Leave_Sanc_Authority] [int] NULL,
	[Reporting_To] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TempApprovalSettings]    Script Date: 03/25/2021 10:16:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempApprovalSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TempApprovalSettings](
	[CompanyId] [int] NOT NULL,
	[OTApproval] [bit] NOT NULL,
	[LeaveSanction] [bit] NOT NULL,
	[PermissionSanction] [bit] NOT NULL,
	[ManualEntry] [bit] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[Roster] [bit] NULL,
	[Pattern] [bit] NOT NULL,
	[ODEntry] [bit] NULL,
	[Approval] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TblAnalysisReport]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TblAnalysisReport]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TblAnalysisReport](
	[Level] [varchar](max) NULL,
	[AbsentDate] [varchar](max) NULL,
	[LeaveDate] [varchar](max) NULL,
	[PermiDate] [varchar](max) NULL,
	[Employee Id] [int] NULL,
	[Employee Name] [varchar](max) NULL,
	[Total Late Days] [int] NULL,
	[Total Late Hours] [int] NULL,
	[PermissionHours] [int] NULL,
	[LeaveType] [varchar](100) NULL,
	[LeaveTypeTotalDays] [decimal](18, 1) NULL,
	[IntimationType] [varchar](max) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tbl_TempEmployeeShiftTime]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tbl_TempEmployeeShiftTime]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Tbl_TempEmployeeShiftTime](
	[Employee_Code_Id] [varchar](10) NULL,
	[Employee_Name] [varchar](250) NULL,
	[Shift_Date] [datetime] NULL,
	[Shift_InTime] [varchar](10) NULL,
	[Shift_OutTime] [varchar](10) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[tb_reportslist]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_reportslist]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_reportslist](
	[nIndex] [int] IDENTITY(1,1) NOT NULL,
	[dtDateTime] [datetime] NULL,
	[m_Date] [int] NULL,
	[m_Time] [int] NULL,
	[nDeviceID] [int] NULL,
	[nEvent] [int] NULL,
	[nUserID] [int] NULL,
	[sUserName] [varchar](255) NULL,
	[nSource] [int] NULL,
	[bAdminCheck] [int] NULL,
	[nTNAEvent] [int] NULL,
	[strUniqueKey] [char](38) NOT NULL,
	[ipAddress] [varchar](30) NULL,
	[LogUID] [bigint] NULL,
 CONSTRAINT [PK__tb_repor__ACB000332B754518] PRIMARY KEY CLUSTERED 
(
	[nIndex] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearSetting]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_YearSetting](
	[YearSettings_Id] [int] IDENTITY(1,1) NOT NULL,
	[StartMonth] [nvarchar](50) NOT NULL,
	[StartYear] [int] NOT NULL,
	[EndMonth] [nvarchar](50) NOT NULL,
	[EndYear] [int] NOT NULL,
	[FromDate] [smalldatetime] NULL,
	[ToDate] [smalldatetime] NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_YearSetting_TimeStamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NOT NULL,
	[IsActive] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_YearSetting] PRIMARY KEY CLUSTERED 
(
	[YearSettings_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[ta_tbl_PenaltyPercentage]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ta_tbl_PenaltyPercentage]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ta_tbl_PenaltyPercentage](
	[CompanyId] [int] NULL,
	[categoryID] [int] NULL,
	[StartTime1] [varchar](5) NULL,
	[EndTime1] [varchar](5) NULL,
	[StartTime2] [varchar](5) NULL,
	[EndTime2] [varchar](5) NULL,
	[StartTime3] [varchar](5) NULL,
	[EndTime3] [varchar](5) NULL,
	[Day1] [decimal](18, 2) NULL,
	[Day2] [decimal](18, 2) NULL,
	[Day3] [decimal](18, 2) NULL,
	[Day4] [decimal](18, 2) NULL,
	[Day5] [decimal](18, 2) NULL,
	[Day6] [decimal](18, 2) NULL,
	[Day7] [decimal](18, 2) NULL,
	[Day8] [decimal](18, 2) NULL,
	[Day9] [decimal](18, 2) NULL,
	[Day10] [decimal](18, 2) NULL,
	[Day11] [decimal](18, 2) NULL,
	[Day12] [decimal](18, 2) NULL,
	[StartTime1Mins]  AS (substring([StartTime1],(0),charindex(':',[StartTime1]))*(60)+substring([StartTime1],charindex(':',[StartTime1])+(1),len([StartTime1]))),
	[EndTime1Mins]  AS (substring([EndTime1],(0),charindex(':',[EndTime1]))*(60)+substring([EndTime1],charindex(':',[EndTime1])+(1),len([EndTime1]))),
	[StartTime2Mins]  AS (substring([StartTime2],(0),charindex(':',[StartTime2]))*(60)+substring([StartTime2],charindex(':',[StartTime2])+(1),len([StartTime2]))),
	[EndTime2Mins]  AS (substring([EndTime2],(0),charindex(':',[EndTime2]))*(60)+substring([EndTime2],charindex(':',[EndTime2])+(1),len([EndTime2]))),
	[StartTime3Mins]  AS (substring([StartTime3],(0),charindex(':',[StartTime3]))*(60)+substring([StartTime3],charindex(':',[StartTime3])+(1),len([StartTime3]))),
	[EndTime3Mins]  AS (substring([EndTime3],(0),charindex(':',[EndTime3]))*(60)+substring([EndTime3],charindex(':',[EndTime3])+(1),len([EndTime3])))
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_TempInsertEmployee]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempInsertEmployee]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TempInsertEmployee](
	[employee_code] [bigint] NOT NULL,
	[first_name] [nvarchar](50) NULL,
	[last_name] [nvarchar](50) NULL,
	[birth_date] [datetime] NULL,
	[local_addr1] [nvarchar](50) NULL,
	[local_addr2] [nvarchar](50) NULL,
	[local_addr3] [nvarchar](50) NULL,
	[join_date] [datetime] NULL,
	[section_name] [nvarchar](50) NULL,
	[desg_name] [nvarchar](50) NULL,
	[category_name] [nvarchar](50) NULL,
	[basic] [numeric](16, 3) NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TempGroupPolicyAllocation]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempGroupPolicyAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TempGroupPolicyAllocation](
	[EmpID] [int] NOT NULL,
	[EmployeeId] [nvarchar](50) NOT NULL,
	[EmployeeName] [nvarchar](50) NOT NULL,
	[LoginEmployeeId] [int] NOT NULL,
	[DateOfJoining] [datetime] NOT NULL,
	[LevelID] [int] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocationbkup]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemporaryShiftAllocationbkup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocationbkup](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL,
	[Day2Shift] [int] NOT NULL,
	[Day3Shift] [int] NOT NULL,
	[Day4Shift] [int] NOT NULL,
	[Day5Shift] [int] NOT NULL,
	[Day6Shift] [int] NOT NULL,
	[Day7Shift] [int] NOT NULL,
	[Day8Shift] [int] NOT NULL,
	[Day9Shift] [int] NOT NULL,
	[Day10Shift] [int] NOT NULL,
	[Day11Shift] [int] NOT NULL,
	[Day12Shift] [int] NOT NULL,
	[Day13Shift] [int] NOT NULL,
	[Day14Shift] [int] NOT NULL,
	[Day15Shift] [int] NOT NULL,
	[Day16Shift] [int] NOT NULL,
	[Day17Shift] [int] NOT NULL,
	[Day18Shift] [int] NOT NULL,
	[Day19Shift] [int] NOT NULL,
	[Day20Shift] [int] NOT NULL,
	[Day21Shift] [int] NOT NULL,
	[Day22Shift] [int] NOT NULL,
	[Day23Shift] [int] NOT NULL,
	[Day24Shift] [int] NOT NULL,
	[Day25Shift] [int] NOT NULL,
	[Day26Shift] [int] NOT NULL,
	[Day27Shift] [int] NOT NULL,
	[Day28Shift] [int] NOT NULL,
	[Day29Shift] [int] NOT NULL,
	[Day30Shift] [int] NOT NULL,
	[Day31Shift] [int] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_TemporaryShiftAllocation]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TemporaryShiftAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day1Shift]  DEFAULT ((0)),
	[Day2Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day2Shift]  DEFAULT ((0)),
	[Day3Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day3Shift]  DEFAULT ((0)),
	[Day4Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day4Shift]  DEFAULT ((0)),
	[Day5Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day5Shift]  DEFAULT ((0)),
	[Day6Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day6Shift]  DEFAULT ((0)),
	[Day7Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day7Shift]  DEFAULT ((0)),
	[Day8Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day8Shift]  DEFAULT ((0)),
	[Day9Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day9Shift]  DEFAULT ((0)),
	[Day10Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day10Shift]  DEFAULT ((0)),
	[Day11Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day11Shift]  DEFAULT ((0)),
	[Day12Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day12Shift]  DEFAULT ((0)),
	[Day13Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day13Shift]  DEFAULT ((0)),
	[Day14Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day14Shift]  DEFAULT ((0)),
	[Day15Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day15Shift]  DEFAULT ((0)),
	[Day16Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day16Shift]  DEFAULT ((0)),
	[Day17Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day17Shift]  DEFAULT ((0)),
	[Day18Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day18Shift]  DEFAULT ((0)),
	[Day19Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day19Shift]  DEFAULT ((0)),
	[Day20Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day20Shift]  DEFAULT ((0)),
	[Day21Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day21Shift]  DEFAULT ((0)),
	[Day22Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day22Shift]  DEFAULT ((0)),
	[Day23Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day23Shift]  DEFAULT ((0)),
	[Day24Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day24Shift]  DEFAULT ((0)),
	[Day25Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day25Shift]  DEFAULT ((0)),
	[Day26Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day26Shift]  DEFAULT ((0)),
	[Day27Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day27Shift]  DEFAULT ((0)),
	[Day28Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day28Shift]  DEFAULT ((0)),
	[Day29Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day29Shift]  DEFAULT ((0)),
	[Day30Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day30Shift]  DEFAULT ((0)),
	[Day31Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_TemporaryShiftAllocation_Day31Shift]  DEFAULT ((0)),
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[DateShift] [datetime] NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_Id] [int] NULL,
	[LevelId] [int] NULL,
 CONSTRAINT [PK_Ta_Tbl_Temporary_WeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[TempWeekday_Id] [int] NULL,
	[Temp_WeeklyOff_Levels] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_Temp_WeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSTemplateFilters]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_SMSTemplateFilters](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[TemplateId] [int] NULL,
	[Filters] [varchar](max) NULL,
	[ReportType] [varchar](50) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_SMSReceivers]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_SMSReceivers](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Usergroupid] [int] NULL,
	[TemplateId] [int] NULL,
	[TimeStamp] [datetime] NULL DEFAULT (getdate()),
	[CreatedBy] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogDetails]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_SMSLogDetails](
	[logid] [int] IDENTITY(1,1) NOT NULL,
	[TemplateID] [int] NULL,
	[TriggeredDate] [datetime] NULL,
	[Receivers] [varchar](50) NULL,
	[NextTriggeringTime] [datetime] NULL,
	[Status] [bit] NULL,
	[StatusMessage] [varchar](max) NULL,
	[ShiftId] [int] NULL,
	[Message] [varchar](max) NULL,
	[TriggeredTimings] [datetime] NULL,
 CONSTRAINT [PK__TA_Tbl_S__7838F2653B5D1C78] PRIMARY KEY CLUSTERED 
(
	[logid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_PermanentShiftAllocation]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocation](
	[EmployeeId] [int] NOT NULL,
	[Year] [int] NOT NULL,
	[Month] [int] NOT NULL,
	[Day1Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day1Shift]  DEFAULT ((0)),
	[Day2Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day2Shift]  DEFAULT ((0)),
	[Day3Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day3Shift]  DEFAULT ((0)),
	[Day4Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day4Shift]  DEFAULT ((0)),
	[Day5Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day5Shift]  DEFAULT ((0)),
	[Day6Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day6Shift]  DEFAULT ((0)),
	[Day7Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day7Shift]  DEFAULT ((0)),
	[Day8Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day8Shift]  DEFAULT ((0)),
	[Day9Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day9Shift]  DEFAULT ((0)),
	[Day10Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day10Shift]  DEFAULT ((0)),
	[Day11Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day11Shift]  DEFAULT ((0)),
	[Day12Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day12Shift]  DEFAULT ((0)),
	[Day13Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day13Shift]  DEFAULT ((0)),
	[Day14Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day14Shift]  DEFAULT ((0)),
	[Day15Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day15Shift]  DEFAULT ((0)),
	[Day16Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day16Shift]  DEFAULT ((0)),
	[Day17Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day17Shift]  DEFAULT ((0)),
	[Day18Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day18Shift]  DEFAULT ((0)),
	[Day19Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day19Shift]  DEFAULT ((0)),
	[Day20Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day20Shift]  DEFAULT ((0)),
	[Day21Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day21Shift]  DEFAULT ((0)),
	[Day22Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day22Shift]  DEFAULT ((0)),
	[Day23Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day23Shift]  DEFAULT ((0)),
	[Day24Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day24Shift]  DEFAULT ((0)),
	[Day25Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day25Shift]  DEFAULT ((0)),
	[Day26Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day26Shift]  DEFAULT ((0)),
	[Day27Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day27Shift]  DEFAULT ((0)),
	[Day28Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day28Shift]  DEFAULT ((0)),
	[Day29Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day29Shift]  DEFAULT ((0)),
	[Day30Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day30Shift]  DEFAULT ((0)),
	[Day31Shift] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_Day31Shift]  DEFAULT ((0)),
	[Emp_Id] [int] NOT NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_PermanentShiftAllocation_TimeStamp]  DEFAULT (getdate()),
	[DateShift] [datetime] NOT NULL,
	[ShiftAllocationID] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_tbl_MailIdsForTriggeringEmail]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[MailType] [varchar](5) NOT NULL,
	[EmailID] [varchar](250) NOT NULL,
 CONSTRAINT [PK_TA_tbl_MailIdsForTriggeringEmail] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePrivateNotes]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeavePrivateNotes](
	[LeavePrivateNotesId] [bigint] IDENTITY(1,1) NOT NULL,
	[LeaveApplicationId] [int] NOT NULL,
	[NotesBy] [int] NOT NULL,
	[Notes] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[ToMailIds] [nvarchar](4000) NULL,
	[CcMailIds] [nvarchar](4000) NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_TA_Tbl_LeavePrivateNotes_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_TA_Tbl_LeavePrivateNotes] PRIMARY KEY CLUSTERED 
(
	[LeavePrivateNotesId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_LeavePolicyDetails]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_LeavePolicyDetails](
	[PolicyDetails_Id] [int] IDENTITY(1,1) NOT NULL,
	[Policy_Id] [int] NOT NULL,
	[LeaveType_Id] [int] NOT NULL,
	[MaxDays_applicable] [decimal](18, 1) NOT NULL,
	[MaxDays_avail] [decimal](18, 1) NULL,
	[MinDays_avail] [decimal](18, 1) NULL,
	[Spells] [int] NULL,
	[MaxDays_Acc] [decimal](18, 1) NULL,
	[LossOfPay] [bit] NOT NULL,
	[Max_LOP_Days] [decimal](18, 1) NOT NULL,
	[Count_BeforeWeeklyOff] [bit] NOT NULL,
	[Count_AfterWeeklyOff] [bit] NOT NULL,
	[Count_Intervening] [bit] NULL,
	[Borrow_FromNextYear] [bit] NOT NULL,
	[Carry_ToNextYear] [bit] NOT NULL,
	[Encashment] [bit] NULL,
	[Calc_Factor] [decimal](18, 1) NULL,
	[MinWorkDays] [decimal](18, 0) NULL,
	[WeekDays] [bit] NULL,
	[WeekOff] [bit] NULL,
	[Leave] [bit] NULL,
	[Holidays] [bit] NULL,
	[ApplicableAfterDays] [decimal](18, 1) NULL CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_ApplicableAfterDays]  DEFAULT ((0)),
	[Emp_Id] [int] NOT NULL,
	[Time_stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_LeavePolicyDetails_Time_stamp]  DEFAULT (getdate()),
	[MaxDays_Month] [decimal](18, 1) NULL,
	[AvailServicePeriod] [int] NULL DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_LeavePolicyDetails] PRIMARY KEY CLUSTERED 
(
	[PolicyDetails_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_PermissionConversation]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PermissionConversation](
	[PermissionConversationId] [bigint] IDENTITY(1,1) NOT NULL,
	[PermissionId] [int] NOT NULL,
	[CommentsBy] [int] NOT NULL,
	[Comments] [nvarchar](1000) NULL,
	[OrderBy] [int] NOT NULL,
	[Emp_Id] [bigint] NOT NULL,
	[TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_PermissionConversation_TimeStamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_PermissionConversation] PRIMARY KEY CLUSTERED 
(
	[PermissionConversationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_Description' , N'SCHEMA',N'dbo', N'TABLE',N'TA_Tbl_PermissionConversation', N'COLUMN',N'CommentsBy'))
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0-Applicant,1-First Level Authority,2-Second Level Authotrity' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Tbl_PermissionConversation', @level2type=N'COLUMN',@level2name=N'CommentsBy'
GO
/****** Object:  Table [dbo].[TA_Tbl_PunchTypes]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PunchTypes](
	[PunchType_Id] [int] IDENTITY(1,1) NOT NULL,
	[Terminal_Id] [int] NOT NULL,
	[PunchType] [nvarchar](25) NOT NULL,
	[Value] [nvarchar](25) NOT NULL,
	[Isdeleted] [bit] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[Time_Stamp] [datetime] NOT NULL,
	[Addedby] [char](1) NULL,
	[Flag] [int] NULL DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_INOUT] PRIMARY KEY CLUSTERED 
(
	[PunchType_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_EmployeeBonusLeave]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmployeeBonusLeave](
	[BonusLeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[YearSettingId] [int] NULL,
	[EmployeeId] [int] NULL,
	[BonusLeaveQuota] [int] NULL,
	[EmpId] [int] NULL,
	[Timestamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmployeeBonusLeave_Timestamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_EmployeeBonusLeave] PRIMARY KEY CLUSTERED 
(
	[BonusLeaveId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmpChildrenDetails]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmpChildrenDetails](
	[ChildEmp_ID] [int] IDENTITY(1,1) NOT NULL,
	[Emp_ID] [int] NOT NULL,
	[Spouse_Child] [char](1) NULL,
	[Name] [nvarchar](50) NULL,
	[DOB] [datetime] NULL,
	[Isdeleted] [bit] NULL,
	[Time_stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_EmpChildrenDetails_Time_stamp]  DEFAULT (getdate()),
	[Employee_ID] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_EmpChildrenDetails] PRIMARY KEY CLUSTERED 
(
	[ChildEmp_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailScheduleFilters]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmailScheduleFilters](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Filters] [varchar](max) NULL,
	[ReportType] [varchar](25) NULL,
	[CompanyId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_EmailScheduleFilters] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditField]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AuditField](
	[FieldID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableID] [decimal](18, 0) NOT NULL,
	[FieldName] [nvarchar](100) NOT NULL,
	[FieldDescription] [nvarchar](100) NOT NULL,
	[InsertBit] [bit] NOT NULL,
	[UpdateBit] [bit] NOT NULL,
	[DeleteBit] [bit] NOT NULL,
	[Status] [bit] NOT NULL,
	[Datatype] [varchar](50) NULL,
 CONSTRAINT [PK_TA_Tbl_AuditField_1] PRIMARY KEY CLUSTERED 
(
	[FieldID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]    Script Date: 03/25/2021 10:16:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Addl_WeeklyOff_Id] [int] NOT NULL,
	[LevelId] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_AdditionalWeeklyOff_Levels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Compensation]    Script Date: 03/25/2021 10:16:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Compensation](
	[Compensation_Id] [int] IDENTITY(1,1) NOT NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[ApplicationDate] [datetime] NULL,
	[FromDate] [datetime] NULL,
	[ToDate] [datetime] NULL,
	[Type] [numeric](18, 1) NULL,
	[Remarks] [nvarchar](2000) NULL,
	[Isdeleted] [bit] NULL,
	[LevelId] [bigint] NULL,
	[Status] [nvarchar](50) NULL,
	[LeaveApplication_Id] [nvarchar](200) NULL,
	[NoOfLeaveDays] [float] NULL,
	[InTime] [varchar](100) NULL,
	[OutTime] [varchar](100) NULL,
	[WorkedHours] [varchar](100) NULL,
	[DayWorked] [varchar](100) NULL,
	[Comments] [nvarchar](2000) NULL,
	[ExpiredDate] [datetime] NULL,
	[Quota] [float] NULL,
	[empid] [int] NULL,
	[ApprovedBy] [int] NULL,
	[ApprovedDate] [datetime] NULL,
	[RejectedBy] [int] NULL,
	[RejectedDate] [datetime] NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF__TA_Tbl_Co__TimeS__5CEF0720]  DEFAULT (getdate()),
	[RemainingLeave] [float] NULL,
	[CompOffSatus] [nvarchar](100) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Entrance_INOUTDetails]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails](
	[EntranceInOut_Id] [int] IDENTITY(1,1) NOT NULL,
	[Entrance_Id] [int] NOT NULL,
	[Reader_Id] [int] NOT NULL,
	[Type] [nvarchar](10) NOT NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Holiday]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Holiday](
	[Holiday_Id] [int] IDENTITY(1,1) NOT NULL,
	[Holiday_Type] [char](1) NOT NULL,
	[Holiday_FromDate] [datetime] NOT NULL,
	[Holiday_ToDate] [datetime] NULL,
	[Holiday_Description] [nvarchar](250) NOT NULL,
	[YearSettings_Id] [int] NULL,
	[Isdeleted] [bit] NOT NULL,
	[Emp_Id] [int] NOT NULL,
	[LevelId] [bigint] NULL,
 CONSTRAINT [PK_TA_Tbl_Holiday] PRIMARY KEY CLUSTERED 
(
	[Holiday_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_Encashment]    Script Date: 03/25/2021 10:16:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Encashment](
	[EncashmentId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[LeaveTypeId] [int] NOT NULL,
	[NumberOfDays] [decimal](18, 1) NOT NULL,
	[DateOfEncashment] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_Encashment_DateOfEncashment]  DEFAULT (getdate()),
	[YearSettingId] [bigint] NOT NULL,
	[Reason] [nvarchar](50) NOT NULL,
	[Isdeleted] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_Encashment] PRIMARY KEY CLUSTERED 
(
	[EncashmentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Emp_LeavePolicy](
	[Emp_LeavePolicyId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [int] NULL,
	[LeavePolicy_Id] [int] NULL,
	[FromDate] [datetime] NULL,
	[ToDate] [datetime] NULL,
	[YearSettingId] [int] NULL,
	[Isdeleted] [bit] NULL,
	[Time_stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Emp_LeavePolicy_Time_stamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NULL,
	[AutoCredit] [bit] NULL CONSTRAINT [TA_Tbl_Emp_LeavePolicy_AutoCredit]  DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_Emp_LeavePolicy] PRIMARY KEY CLUSTERED 
(
	[Emp_LeavePolicyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_EmailTemplate]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_EmailTemplate](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ScheduleId] [bigint] NOT NULL,
	[Subject] [varchar](300) NOT NULL,
	[EmailContent] [varchar](max) NULL,
 CONSTRAINT [PK_TA_Tbl_EmailContent] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Ta_Tbl_levelDetails](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[levelId] [int] NULL,
	[parentId] [int] NULL,
	[name] [nvarchar](255) NULL,
	[description] [nvarchar](255) NULL,
	[city] [nvarchar](100) NULL,
	[state] [nvarchar](100) NULL,
	[country] [nvarchar](100) NULL,
	[zip] [nvarchar](50) NULL,
	[phone1] [nvarchar](50) NULL,
	[phone2] [nvarchar](50) NULL,
	[fax1] [nvarchar](50) NULL,
	[fax2] [nvarchar](50) NULL,
	[email] [nvarchar](255) NULL,
	[webAddress] [nvarchar](255) NULL,
	[logo] [image] NULL,
	[isDeleted] [bit] NULL DEFAULT ((0)),
	[timeStamp] [datetime] NULL,
	[Emp_id] [nvarchar](50) NULL,
	[ToMailIds] [varchar](4000) NULL,
	[CCMailIds] [varchar](4000) NULL,
 CONSTRAINT [PK_Ta_Tbl_levelDetails] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_MonthClosure](
	[MonthClosure_Id] [int] IDENTITY(1,1) NOT NULL,
	[OrgLevel_Id] [int] NULL,
	[MonthClosure_Month] [nvarchar](15) NULL,
	[MonthClosure_Year] [int] NULL,
	[MonthClosure_StartDate] [datetime] NULL,
	[MonthClosure_EndDate] [datetime] NULL,
	[MonthClosure_ClosingDate] [datetime] NULL,
	[Emp_Id] [int] NULL,
	[Process] [char](1) NULL,
	[TimeStamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_MonthClosure_TimeStamp]  DEFAULT (getdate()),
	[IsDeleted] [bit] NULL,
	[YearSettings_Id] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_MonthClosure] PRIMARY KEY CLUSTERED 
(
	[MonthClosure_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_HolidayChildTable]    Script Date: 03/25/2021 10:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_HolidayChildTable](
	[Holiday_ChildId] [int] IDENTITY(1,1) NOT NULL,
	[LevelId] [bigint] NULL,
	[Holiday_Id] [int] NULL
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Emp_LeavePolicyDetails]    Script Date: 03/25/2021 10:16:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails](
	[Emp_LeavePolicyDetailsId] [int] IDENTITY(1,1) NOT NULL,
	[Emp_LeavePolicyId] [int] NULL,
	[EmpID] [int] NULL,
	[Policy_ID] [int] NULL,
	[LeaveType_Id] [int] NULL,
	[No_Of_Days] [decimal](18, 1) NULL,
	[Isdeleted] [bit] NULL,
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Emp_LeavePolicyDetails_Time_Stamp]  DEFAULT (getdate()),
	[Emp_Id] [int] NULL,
	[MaxDays_Month] [decimal](18, 1) NULL DEFAULT ((0)),
 CONSTRAINT [PK_TA_Tbl_Emp_LeavePolicyDetails] PRIMARY KEY CLUSTERED 
(
	[Emp_LeavePolicyDetailsId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_AuditOperation]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_AuditOperation](
	[ID] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
	[TableID] [decimal](18, 0) NOT NULL,
	[RecordID] [decimal](18, 0) NOT NULL,
	[FieldID] [decimal](18, 0) NOT NULL,
	[Opr] [nvarchar](25) NOT NULL,
	[OldValue] [nvarchar](500) NULL,
	[NewValue] [nvarchar](500) NULL,
	[EmployeeID] [int] NULL,
	[OprDate] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_AuditOpr_OprDate]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_AuditOperation] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_RouteMaster]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_RouteMaster](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[VehicleID] [int] NULL,
	[Route_Name] [nvarchar](50) NOT NULL,
	[Route_Description] [nvarchar](250) NULL,
	[Time_Stamp] [datetime] NULL,
	[Emp_ID] [int] NULL,
	[IsDeleted] [bit] NOT NULL DEFAULT ((0)),
	[IsMapped] [int] NOT NULL CONSTRAINT [DF_TA_Tbl_RouteMaster_IsMapped]  DEFAULT ((1)),
 CONSTRAINT [PK_TA_Tbl_RouteMaster] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_SMSLogChild]    Script Date: 03/25/2021 10:16:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_SMSLogChild](
	[logchildid] [int] IDENTITY(1,1) NOT NULL,
	[logid] [int] NULL,
	[Employeesids] [varchar](50) NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftRoaster]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ShiftRoaster](
	[ShiftRoaster_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[ShiftRoaster_Name] [nvarchar](50) NULL,
	[NumberOfPatterns] [int] NOT NULL,
	[Pattern1] [int] NULL,
	[Pattern2] [int] NULL,
	[Pattern3] [int] NULL,
	[Pattern4] [int] NULL,
	[Pattern5] [int] NULL,
	[Pattern6] [int] NULL,
	[Pattern7] [int] NULL,
	[Pattern8] [int] NULL,
	[Pattern9] [int] NULL,
	[Pattern10] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_ShiftRoaster] PRIMARY KEY CLUSTERED 
(
	[ShiftRoaster_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_ShiftPattern]    Script Date: 03/25/2021 10:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_ShiftPattern](
	[ShiftPattern_Id] [int] IDENTITY(1,1) NOT NULL,
	[Level_Id] [int] NULL,
	[Pattern_Name] [nvarchar](50) NOT NULL,
	[Shift_days] [int] NOT NULL,
	[Day1_Shift] [int] NULL,
	[Day2_shift] [int] NULL,
	[Day3_Shift] [int] NULL,
	[Day4_Shift] [int] NULL,
	[Day5_Shift] [int] NULL,
	[Day6_Shift] [int] NULL,
	[Day7_Shift] [int] NULL,
	[Day8_Shift] [int] NULL,
	[Day9_Shift] [int] NULL,
	[Day10_Shift] [int] NULL,
	[Day11_Shift] [int] NULL,
	[Day12_Shift] [int] NULL,
	[Day13_Shift] [int] NULL,
	[Day14_Shift] [int] NULL,
	[Day15_Shift] [int] NULL,
	[Day16_Shift] [int] NULL,
	[Day17_Shift] [int] NULL,
	[Day18_Shift] [int] NULL,
	[Day19_Shift] [int] NULL,
	[Day20_Shift] [int] NULL,
	[Day21_Shift] [int] NULL,
	[Day22_Shift] [int] NULL,
	[Day23_Shift] [int] NULL,
	[Day24_Shift] [int] NULL,
	[Day25_Shift] [int] NULL,
	[Day26_Shift] [int] NULL,
	[Day27_Shift] [int] NULL,
	[Day28_Shift] [int] NULL,
	[Day29_Shift] [int] NULL,
	[Day30_Shift] [int] NULL,
	[Day31_Shift] [int] NULL,
	[Emp_Id] [int] NULL,
	[Isdeleted] [bit] NULL,
 CONSTRAINT [PK_TA_Tbl] PRIMARY KEY CLUSTERED 
(
	[ShiftPattern_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_Title]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_Title](
	[TitleId] [int] IDENTITY(1,1) NOT NULL,
	[TitleName] [nvarchar](50) NOT NULL,
	[TitleDescription] [nvarchar](250) NULL,
	[LevelID] [int] NULL,
	[LeavePolicyID] [int] NULL,
	[GradeID] [int] NULL,
	[Emp_Id] [int] NULL,
	[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_TA_Tbl_Title_IsDeleted]  DEFAULT ((1)),
	[Time_Stamp] [datetime] NULL CONSTRAINT [DF_TA_Tbl_Title_Time_Stamp]  DEFAULT (getdate()),
 CONSTRAINT [PK_TA_Tbl_Title] PRIMARY KEY CLUSTERED 
(
	[TitleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_YearClosure]    Script Date: 03/25/2021 10:16:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_YearClosure](
	[YearClosureId] [int] IDENTITY(1,1) NOT NULL,
	[Year_SettingID] [int] NOT NULL,
	[OrgLevelId] [int] NULL,
	[YearClosed] [nvarchar](50) NULL,
	[DateClosed] [datetime] NULL,
	[Employee_Id] [int] NOT NULL,
	[LeaveTypeID] [int] NOT NULL,
	[Carry_PrevYear] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Carry_PrevYear]  DEFAULT ((0)),
	[Current_Quota] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Current_Quota]  DEFAULT ((0)),
	[Borrow_NextYear] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Borrow_NextYear]  DEFAULT ((0)),
	[Leave_Taken] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Leave_Taken]  DEFAULT ((0)),
	[Available_Leaves] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Available_Leaves]  DEFAULT ((0)),
	[Encashment] [decimal](18, 1) NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Encashment]  DEFAULT ((0)),
	[Time_Stamp] [datetime] NOT NULL CONSTRAINT [DF_TA_Tbl_YearClosure_Time_Stamp]  DEFAULT (getdate()),
	[Emp_ID] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_YearClosure] PRIMARY KEY CLUSTERED 
(
	[YearClosureId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessLeaveDetails]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails](
	[PayrollProcessLeave_id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NOT NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[LeaveType_id] [int] NULL,
	[Leave_Count] [int] NULL,
 CONSTRAINT [PK_TA_Tbl_PayrollProcessLeaveDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcessLeave_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_PayrollProcessDetails]    Script Date: 03/25/2021 10:16:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_PayrollProcessDetails](
	[PayrollProcess_Id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[HrsWork] [nvarchar](25) NULL,
	[HrsOT] [nvarchar](25) NULL,
	[NormOT] [nvarchar](25) NULL,
	[OffOT] [nvarchar](25) NULL,
	[HolOT] [nvarchar](25) NULL,
	[EarlyOut] [nvarchar](25) NULL,
	[LateIn] [nvarchar](25) NULL,
	[WorkHrs] [nvarchar](25) NULL,
	[HrsLess] [nvarchar](25) NULL,
	[HrsExtra] [nvarchar](25) NULL,
	[LeaveDays] [numeric](18, 1) NULL,
	[AbsentDays] [numeric](18, 1) NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[Holidays] [numeric](18, 1) NULL,
	[LOPDays] [numeric](18, 1) NULL,
	[Emp_Id] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[TotalPermissionHours] [varchar](100) NULL,
	[WeekOffDays] [decimal](18, 1) NULL,
	[SPEC_NormOT1] [nvarchar](10) NULL,
	[SPEC_NormOT2] [nvarchar](10) NULL,
	[SPEC_OffOT1] [nvarchar](10) NULL,
	[SPEC_OffOT2] [nvarchar](10) NULL,
	[SPEC_HOLOT1] [nvarchar](10) NULL,
	[SPEC_HOLOT2] [nvarchar](10) NULL,
 CONSTRAINT [PK_TA_Tbl_PayrollProcessDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcess_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_TempPayrollProcessDetails]    Script Date: 03/25/2021 10:16:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails](
	[PayrollProcess_Id] [int] IDENTITY(1,1) NOT NULL,
	[MonthClosure_Id] [int] NULL,
	[Employee_Id] [nvarchar](20) NULL,
	[HrsWork] [nvarchar](25) NULL,
	[HrsOT] [nvarchar](25) NULL,
	[NormOT] [nvarchar](25) NULL,
	[OffOT] [nvarchar](25) NULL,
	[HolOT] [nvarchar](25) NULL,
	[EarlyOut] [nvarchar](25) NULL,
	[LateIn] [nvarchar](25) NULL,
	[WorkHrs] [nvarchar](25) NULL,
	[HrsLess] [nvarchar](25) NULL,
	[HrsExtra] [nvarchar](25) NULL,
	[LeaveDays] [numeric](18, 1) NULL,
	[AbsentDays] [numeric](18, 1) NULL,
	[PresentDays] [numeric](18, 1) NULL,
	[Holidays] [numeric](18, 1) NULL,
	[LOPDays] [numeric](18, 1) NULL,
	[Emp_Id] [int] NULL,
	[TimeStamp] [datetime] NULL,
	[TotalPermissionHours] [varchar](100) NULL,
	[WeekOffDays] [decimal](18, 1) NULL,
 CONSTRAINT [PK_TA_Tbl_TempPayrollProcessDetails] PRIMARY KEY CLUSTERED 
(
	[PayrollProcess_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CCMailGroup](
	[CCGroupID] [bigint] IDENTITY(1,1) NOT NULL,
	[LevelID] [int] NOT NULL,
	[DesignationID] [int] NOT NULL,
	[MailTo_SecondLevel_Planned] [bit] NOT NULL,
	[MailTo_SecondLevel_UnPlanned] [bit] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCMailGroup] PRIMARY KEY CLUSTERED 
(
	[CCGroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_UnPlanned]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupID] [bigint] NOT NULL,
	[CC_UnPlanned] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_UnPlanned] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Planned]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CCGroup_Planned](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupID] [bigint] NOT NULL,
	[CC_Planned] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_Planned] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  Table [dbo].[TA_Tbl_CCGroup_Others]    Script Date: 03/25/2021 10:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TA_Tbl_CCGroup_Others](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[CCGroupId] [bigint] NOT NULL,
	[CC_Others] [int] NOT NULL,
 CONSTRAINT [PK_TA_Tbl_CCGroup_Others] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]    Script Date: 03/25/2021 10:16:41 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff] FOREIGN KEY([Addl_WeeklyOff_Id])
REFERENCES [dbo].[TA_Tbl_Additional_WeeklyOff] ([Addl_WeeklyOff_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Additional_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Additional_WeeklyOff_Levels] CHECK CONSTRAINT [FK_TA_Tbl_AdditionalWeeklyOff_Levels_TA_Tbl_Additional_WeeklyOff]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]'))
ALTER TABLE [dbo].[TA_Tbl_AuditField]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable] FOREIGN KEY([TableID])
REFERENCES [dbo].[TA_Tbl_AuditTable] ([TableID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditField]'))
ALTER TABLE [dbo].[TA_Tbl_AuditField] CHECK CONSTRAINT [FK_TA_Tbl_AuditField_TA_Tbl_AuditTable]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField] FOREIGN KEY([FieldID])
REFERENCES [dbo].[TA_Tbl_AuditField] ([FieldID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] CHECK CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditField]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable] FOREIGN KEY([TableID])
REFERENCES [dbo].[TA_Tbl_AuditTable] ([TableID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_AuditOperation]'))
ALTER TABLE [dbo].[TA_Tbl_AuditOperation] CHECK CONSTRAINT [FK_TA_Tbl_AuditOperation_TA_Tbl_AuditTable]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup] FOREIGN KEY([CCGroupId])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Others]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Others] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_Others_TA_Tbl_CCMailGroup]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned] FOREIGN KEY([CCGroupID])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_Planned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_Planned] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_Planned_TA_Tbl_CCGroup_Planned]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup] FOREIGN KEY([CCGroupID])
REFERENCES [dbo].[TA_Tbl_CCMailGroup] ([CCGroupID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCGroup_UnPlanned]'))
ALTER TABLE [dbo].[TA_Tbl_CCGroup_UnPlanned] CHECK CONSTRAINT [FK_TA_Tbl_CCGroup_UnPlanned_TA_Tbl_CCMailGroup]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails] FOREIGN KEY([LevelID])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] CHECK CONSTRAINT [FK_TA_Tbl_CCMailGroup_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]    Script Date: 03/25/2021 10:16:42 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title] FOREIGN KEY([DesignationID])
REFERENCES [dbo].[TA_Tbl_Title] ([TitleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_CCMailGroup]'))
ALTER TABLE [dbo].[TA_Tbl_CCMailGroup] CHECK CONSTRAINT [FK_TA_Tbl_CCMailGroup_TA_Tbl_Title]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__Appro__5A129A75]    Script Date: 03/25/2021 10:16:43 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Appro__5A129A75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75] FOREIGN KEY([ApprovedBy])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Appro__5A129A75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__Appro__5A129A75]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__empid__5B06BEAE]    Script Date: 03/25/2021 10:16:43 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__empid__5B06BEAE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE] FOREIGN KEY([empid])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__empid__5B06BEAE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__empid__5B06BEAE]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Co__Rejec__5BFAE2E7]    Script Date: 03/25/2021 10:16:43 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Rejec__5BFAE2E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7] FOREIGN KEY([RejectedBy])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Co__Rejec__5BFAE2E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Compensation]'))
ALTER TABLE [dbo].[TA_Tbl_Compensation] CHECK CONSTRAINT [FK__TA_Tbl_Co__Rejec__5BFAE2E7]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]'))
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailScheduleFilters]'))
ALTER TABLE [dbo].[TA_Tbl_EmailScheduleFilters] CHECK CONSTRAINT [FK_TA_Tbl_EmailScheduleFilters_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]'))
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmailTemplate]'))
ALTER TABLE [dbo].[TA_Tbl_EmailTemplate] CHECK CONSTRAINT [FK_TA_Tbl_EmailTemplate_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy] FOREIGN KEY([LeavePolicy_Id])
REFERENCES [dbo].[TA_Tbl_LeavePolicy] ([Policy_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting] FOREIGN KEY([YearSettingId])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicy]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicy] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicy_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy] FOREIGN KEY([Emp_LeavePolicyId])
REFERENCES [dbo].[TA_Tbl_Emp_LeavePolicy] ([Emp_LeavePolicyId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_Emp_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType] FOREIGN KEY([LeaveType_Id])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Emp_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Emp_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_Emp_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]'))
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1] FOREIGN KEY([Emp_ID])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmpChildrenDetails]'))
ALTER TABLE [dbo].[TA_Tbl_EmpChildrenDetails] CHECK CONSTRAINT [FK_TA_Tbl_EmpChildrenDetails_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1] FOREIGN KEY([EmpId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:44 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting] FOREIGN KEY([YearSettingId])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_EmployeeBonusLeave]'))
ALTER TABLE [dbo].[TA_Tbl_EmployeeBonusLeave] CHECK CONSTRAINT [FK_TA_Tbl_EmployeeBonusLeave_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:45 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]'))
ALTER TABLE [dbo].[TA_Tbl_Encashment]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType] FOREIGN KEY([LeaveTypeId])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Encashment]'))
ALTER TABLE [dbo].[TA_Tbl_Encashment] CHECK CONSTRAINT [FK_TA_Tbl_Encashment_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]    Script Date: 03/25/2021 10:16:45 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance] FOREIGN KEY([Entrance_Id])
REFERENCES [dbo].[TA_Tbl_Entrance] ([Entrance_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] CHECK CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Entrance]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:45 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal] FOREIGN KEY([Reader_Id])
REFERENCES [dbo].[TA_Tbl_Terminal] ([Terminal_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Entrance_INOUTDetails]'))
ALTER TABLE [dbo].[TA_Tbl_Entrance_INOUTDetails] CHECK CONSTRAINT [FK_TA_Tbl_Entrance_INOUTDetails_TA_Tbl_Terminal]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:46 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]'))
ALTER TABLE [dbo].[TA_Tbl_Holiday]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting] FOREIGN KEY([YearSettings_Id])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Holiday]'))
ALTER TABLE [dbo].[TA_Tbl_Holiday] CHECK CONSTRAINT [FK_TA_Tbl_Holiday_TA_Tbl_YearSetting]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_Ho__Holid__20589827]    Script Date: 03/25/2021 10:16:46 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Ho__Holid__20589827]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]'))
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827] FOREIGN KEY([Holiday_Id])
REFERENCES [dbo].[TA_Tbl_Holiday] ([Holiday_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_Ho__Holid__20589827]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_HolidayChildTable]'))
ALTER TABLE [dbo].[TA_Tbl_HolidayChildTable] CHECK CONSTRAINT [FK__TA_Tbl_Ho__Holid__20589827]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:47 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]    Script Date: 03/25/2021 10:16:47 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy] FOREIGN KEY([Policy_Id])
REFERENCES [dbo].[TA_Tbl_LeavePolicy] ([Policy_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeavePolicy]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:47 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType] FOREIGN KEY([LeaveType_Id])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePolicyDetails]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePolicyDetails] CHECK CONSTRAINT [FK_TA_Tbl_LeavePolicyDetails_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]    Script Date: 03/25/2021 10:16:47 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster] FOREIGN KEY([LeaveApplicationId])
REFERENCES [dbo].[TA_Tbl_LeaveApplicationMaster] ([LeaveApplication_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_LeavePrivateNotes]'))
ALTER TABLE [dbo].[TA_Tbl_LeavePrivateNotes] CHECK CONSTRAINT [FK_TA_Tbl_LeavePrivateNotes_TA_Tbl_LeaveApplicationMaster]
GO
/****** Object:  ForeignKey [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]    Script Date: 03/25/2021 10:16:47 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_levelDetails_TA_Tbl_Level]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]'))
ALTER TABLE [dbo].[Ta_Tbl_levelDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level] FOREIGN KEY([levelId])
REFERENCES [dbo].[TA_Tbl_Level] ([levelID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_levelDetails_TA_Tbl_Level]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_levelDetails]'))
ALTER TABLE [dbo].[Ta_Tbl_levelDetails] CHECK CONSTRAINT [FK_Ta_Tbl_levelDetails_TA_Tbl_Level]
GO
/****** Object:  ForeignKey [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]    Script Date: 03/25/2021 10:16:48 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]'))
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule] FOREIGN KEY([ScheduleId])
REFERENCES [dbo].[TA_Tbl_EmailSchedule] ([ScheduleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_tbl_MailIdsForTriggeringEmail]'))
ALTER TABLE [dbo].[TA_tbl_MailIdsForTriggeringEmail] CHECK CONSTRAINT [FK_TA_tbl_MailIdsForTriggeringEmail_TA_Tbl_EmailSchedule]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:48 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]'))
ALTER TABLE [dbo].[TA_Tbl_MonthClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails] FOREIGN KEY([OrgLevel_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_MonthClosure]'))
ALTER TABLE [dbo].[TA_Tbl_MonthClosure] CHECK CONSTRAINT [FK_TA_Tbl_MonthClosure_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:50 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessDetails] CHECK CONSTRAINT [FK_TA_Tbl_PayrollProcessDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:50 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PayrollProcessLeaveDetails]'))
ALTER TABLE [dbo].[TA_Tbl_PayrollProcessLeaveDetails] CHECK CONSTRAINT [FK_TA_Tbl_PayrollProcessLeaveDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:50 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] CHECK CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]    Script Date: 03/25/2021 10:16:50 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermanentShiftAllocation]'))
ALTER TABLE [dbo].[TA_Tbl_PermanentShiftAllocation] CHECK CONSTRAINT [FK_TA_Tbl_PermanentShiftAllocation_TA_Tbl_Employee1]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]    Script Date: 03/25/2021 10:16:50 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]'))
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission] FOREIGN KEY([PermissionId])
REFERENCES [dbo].[TA_Tbl_Permission] ([Permission_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PermissionConversation]'))
ALTER TABLE [dbo].[TA_Tbl_PermissionConversation] CHECK CONSTRAINT [FK_TA_Tbl_TA_Tbl_PermissionConversation_TA_Tbl_Permission]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]'))
ALTER TABLE [dbo].[TA_Tbl_PunchTypes]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal] FOREIGN KEY([Terminal_Id])
REFERENCES [dbo].[TA_Tbl_Terminal] ([Terminal_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_PunchTypes]'))
ALTER TABLE [dbo].[TA_Tbl_PunchTypes] CHECK CONSTRAINT [FK_TA_Tbl_PunchTypes_TA_Tbl_Terminal]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] CHECK CONSTRAINT [FK_TA_Tbl_RouteMaster_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle] FOREIGN KEY([VehicleID])
REFERENCES [dbo].[TA_Tbl_Transportation_Vehicle] ([VehicleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_RouteMaster]'))
ALTER TABLE [dbo].[TA_Tbl_RouteMaster] CHECK CONSTRAINT [FK_TA_Tbl_RouteMaster_TA_Tbl_Transportation_Vehicle]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee] FOREIGN KEY([Emp_Id])
REFERENCES [dbo].[TA_Tbl_Employee] ([Employee_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] CHECK CONSTRAINT [FK_TA_Tbl_ShiftPattern_TA_Tbl_Employee]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftPattern]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftPattern] CHECK CONSTRAINT [FK_TA_Tbl_ShiftPattern_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:51 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails] FOREIGN KEY([Level_Id])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_ShiftRoaster]'))
ALTER TABLE [dbo].[TA_Tbl_ShiftRoaster] CHECK CONSTRAINT [FK_TA_Tbl_ShiftRoaster_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__logid__62E4AA3C]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__logid__62E4AA3C]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C] FOREIGN KEY([logid])
REFERENCES [dbo].[TA_Tbl_SMSLogDetails] ([logid])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__logid__62E4AA3C]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogChild]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogChild] CHECK CONSTRAINT [FK__TA_Tbl_SM__logid__62E4AA3C]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__Templ__63D8CE75]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__63D8CE75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75] FOREIGN KEY([TemplateID])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__63D8CE75]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] CHECK CONSTRAINT [FK__TA_Tbl_SM__Templ__63D8CE75]
GO
/****** Object:  ForeignKey [FK__TA_Tbl_SM__Templ__64CCF2AE]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__64CCF2AE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails]  WITH CHECK ADD  CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE] FOREIGN KEY([TemplateID])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__TA_Tbl_SM__Templ__64CCF2AE]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_SMSLogDetails]'))
ALTER TABLE [dbo].[TA_Tbl_SMSLogDetails] CHECK CONSTRAINT [FK__TA_Tbl_SM__Templ__64CCF2AE]
GO
/****** Object:  ForeignKey [FK__Ta_Tbl_SM__Templ__65C116E7]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__65C116E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers]  WITH CHECK ADD  CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7] FOREIGN KEY([TemplateId])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__65C116E7]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSReceivers]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSReceivers] CHECK CONSTRAINT [FK__Ta_Tbl_SM__Templ__65C116E7]
GO
/****** Object:  ForeignKey [FK__Ta_Tbl_SM__Templ__66B53B20]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__66B53B20]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters]  WITH CHECK ADD  CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20] FOREIGN KEY([TemplateId])
REFERENCES [dbo].[Ta_Tbl_SMSTemplates] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK__Ta_Tbl_SM__Templ__66B53B20]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_SMSTemplateFilters]'))
ALTER TABLE [dbo].[Ta_Tbl_SMSTemplateFilters] CHECK CONSTRAINT [FK__Ta_Tbl_SM__Templ__66B53B20]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday] FOREIGN KEY([TempWeekday_Id])
REFERENCES [dbo].[TA_Tbl_TemWeekday] ([TempWeekday_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Temp_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[TA_Tbl_Temp_WeeklyOff_Levels] CHECK CONSTRAINT [FK_TA_Tbl_Temp_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
/****** Object:  ForeignKey [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]    Script Date: 03/25/2021 10:16:52 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]  WITH NOCHECK ADD  CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday] FOREIGN KEY([TempWeekday_Id])
REFERENCES [dbo].[TA_Tbl_TemWeekday] ([TempWeekday_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels]'))
ALTER TABLE [dbo].[Ta_Tbl_Temporary_WeeklyOff_Levels] CHECK CONSTRAINT [FK_Ta_Tbl_Temporary_WeeklyOff_Levels_TA_Tbl_TemWeekday]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]    Script Date: 03/25/2021 10:16:53 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails]  WITH CHECK ADD  CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure] FOREIGN KEY([MonthClosure_Id])
REFERENCES [dbo].[TA_Tbl_MonthClosure] ([MonthClosure_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_TempPayrollProcessDetails]'))
ALTER TABLE [dbo].[TA_Tbl_TempPayrollProcessDetails] CHECK CONSTRAINT [FK_TA_Tbl_TempPayrollProcessDetails_TA_Tbl_MonthClosure]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Title_TA_Tbl_Grade]    Script Date: 03/25/2021 10:16:53 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_TA_Tbl_Grade]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade] FOREIGN KEY([GradeID])
REFERENCES [dbo].[TA_Tbl_Grade] ([Grade_ID])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_TA_Tbl_Grade]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] CHECK CONSTRAINT [FK_TA_Tbl_Title_TA_Tbl_Grade]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:53 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails] FOREIGN KEY([LevelID])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_Title_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Title]'))
ALTER TABLE [dbo].[TA_Tbl_Title] CHECK CONSTRAINT [FK_TA_Tbl_Title_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]    Script Date: 03/25/2021 10:16:54 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType] FOREIGN KEY([LeaveTypeID])
REFERENCES [dbo].[TA_Tbl_LeaveType] ([LeaveType_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_LeaveType]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]    Script Date: 03/25/2021 10:16:54 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails] FOREIGN KEY([OrgLevelId])
REFERENCES [dbo].[Ta_Tbl_levelDetails] ([id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_Ta_Tbl_levelDetails]
GO
/****** Object:  ForeignKey [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]    Script Date: 03/25/2021 10:16:54 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure]  WITH NOCHECK ADD  CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting] FOREIGN KEY([Year_SettingID])
REFERENCES [dbo].[TA_Tbl_YearSetting] ([YearSettings_Id])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]') AND parent_object_id = OBJECT_ID(N'[dbo].[TA_Tbl_YearClosure]'))
ALTER TABLE [dbo].[TA_Tbl_YearClosure] CHECK CONSTRAINT [FK_TA_Tbl_YearClosure_TA_Tbl_YearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroupById]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroupById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCCGroupById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIdsByUserGroup]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailIdsByUserGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmailIdsByUserGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyDeviation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyDeviation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation_New]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyDeviation_New]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyDeviation_New]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptFirstInPunchDifference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference_email]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptFirstInPunchDifference_email]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference_email]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrs_New]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrsNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMyCalendar]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMyCalendar]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMyCalendar]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWeeklyWorkHours_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportMasterData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ImportMasterData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ImportMasterData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_PayrollProcessDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_PayrollProcessDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_PayrollProcessDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateDelete_CCGroup]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateDelete_CCGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateDelete_CCGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveBalanceImport]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveBalanceImport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LeaveBalanceImport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCCGroups]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCCGroups]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCCGroups]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToGetLunchHours]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ToGetLunchHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ToGetLunchHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_PayrollProcessDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_PayrollProcessDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_PayrollProcessDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPayrollDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPayrollDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCCGroupExists]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCCGroupExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCCGroupExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePayrollLeaveDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePayrollLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeletePayrollLeaveDetails]
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunchDifference]'))
DROP VIEW [dbo].[TA_VW_FirstInPunchDifference]
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference_Test]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunchDifference_Test]'))
DROP VIEW [dbo].[TA_VW_FirstInPunchDifference_Test]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLevel_MusterRoll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLevel_MusterRoll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employee_ForShiftReAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employee_ForShiftReAllocation1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBonusLeave]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeBonusLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeBonusLeave]
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeeLog]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_EmployeeLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TA_Proc_EmployeeLog]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpType_MusterRoll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpType_MusterRoll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterpriseGradeUpdation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterpriseGradeUpdation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EnterpriseGradeUpdation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportLeaveData]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportLeaveData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ExportLeaveData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_LeaveSummaryDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_rptAbsent]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpCategory_MusterRoll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpCategory_MusterRoll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftRoster]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreShiftRoster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RestoreShiftRoster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMasterData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertMasterData]
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPattern]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternById]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPatternById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectShiftPatternById]
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternDeleteById]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPatternDeleteById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectShiftPatternDeleteById]
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyData]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDiscrepancyData]
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataIFFCO]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataIFFCO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDiscrepancyDataIFFCO]
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataOMAN]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataOMAN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDiscrepancyDataOMAN]
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataTiffany]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataTiffany]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDiscrepancyDataTiffany]
GO
/****** Object:  StoredProcedure [dbo].[ReProcessEmpData]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReProcessEmpData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReProcessEmpData]
GO
/****** Object:  StoredProcedure [dbo].[sampleCount]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sampleCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sampleCount]
GO
/****** Object:  StoredProcedure [dbo].[TotalLeavesAvailedDetails_Employee]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TotalLeavesAvailedDetails_Employee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TotalLeavesAvailedDetails_Employee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteCommaSeparated]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteCommaSeparated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AutoCompleteCommaSeparated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtender]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteExtender]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AutoCompleteExtender]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtenderForReports]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteExtenderForReports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AutoCompleteExtenderForReports]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoShiftConfiguration_Import]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoShiftConfiguration_Import]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AutoShiftConfiguration_Import]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportPrevLeaveBalance]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkImportPrevLeaveBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_BulkImportPrevLeaveBalance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DetailAttendanceforExportTally]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DetailAttendanceforExportTally]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DetailAttendanceforExportTally]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employees_ForShiftReAllocation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employees_ForShiftReAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Employees_ForShiftReAllocation]
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_EarlyExit]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_EarlyExit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TA_EarlyExit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForSearch]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForSearch]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForUpdate]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTSanction]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeOTSanction]
GO
/****** Object:  StoredProcedure [dbo].[GetPreviousLeaveApplicationDaysValues]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetPreviousLeaveApplicationDaysValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetPreviousLeaveApplicationDaysValues]
GO
/****** Object:  StoredProcedure [dbo].[ImportOvertTimeData]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ImportOvertTimeData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ImportOvertTimeData]
GO
/****** Object:  StoredProcedure [dbo].[Pro_Update_RouteMaster_BYId]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Pro_Update_RouteMaster_BYId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Pro_Update_RouteMaster_BYId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Approvaldatacount]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Approvaldatacount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Approvaldatacount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthCloseDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteMonthCloseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteMonthCloseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftPattern]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoaster]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftRoaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftRoaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitle]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTitle]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTitle]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosuredetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearClosuredetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteYearClosuredetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearsetting]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearsetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteYearsetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListing]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationListing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CompensationListing]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListingByEmpId]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationListingByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CompensationListingByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompOffCalculation]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompOffCalculation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CompOffCalculation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGrade]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountGrade]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CountGrade]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeeChildrenDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplication_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Update]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRoute_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternRestore]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternRestore]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftPatternRestore]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosed]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckYearClosed]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureExistOrNot]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosureExistOrNot]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckYearClosureExistOrNot]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExists]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearSettingExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckYearSettingExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Update]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTitle_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectDesignation]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CMITechSelectDesignation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CMITechSelectDesignation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDateForHoliday]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDateForHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckDateForHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetRouteDetails]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetRouteDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GetRouteDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingAutoShiftConfiguration]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GettingAutoShiftConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GettingAutoShiftConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GettingNearShiftDetailsUsingInpunch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]
GO
/****** Object:  StoredProcedure [dbo].[proc_OtCalculation]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_OtCalculation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_OtCalculation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_SelectWeekday]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_SelectWeekday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_SelectWeekday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForService]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidayForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayBasedOnLevel]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayBasedOnLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidayBasedOnLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicyDatesExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosureProcessFlag]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMonthClosureProcessFlag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMonthClosureProcessFlag]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermanentDelete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermanentDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermanentDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetQuotaDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetQuotaDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetQuotaDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getRawData]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getRawData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getRawData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarTeamData]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMyCalendarTeamData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMyCalendarTeamData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetnotificationDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetnotificationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetnotificationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeaves]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeaves]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeaves]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftExchangeDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftExchangeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftExchangeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftRoasterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetailsById]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftRoasterDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Surguru]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTheDashboardInformation_Surguru]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Surguru]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Working]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTheDashboardInformation_Working]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Working]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTitleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleFirstDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleFirstDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTitleFirstDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleMappingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTitleMappingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleMappingDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTitleMappingDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleNameById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleNameById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTitleNameById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_MappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_MappingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportation_MappingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_RouteDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportation_RouteDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetailsByID]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_RouteDetailsByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportation_RouteDetailsByID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_VehicleDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_VehicleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportation_VehicleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationRouteDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationRouteDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCountSanctionDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveCountSanctionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveCountSanctionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveMasterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveMasterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetailsById]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveMasterDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveMasterDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDate]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMonthClosureEndDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDateForService]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMonthClosureEndDateForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDateForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Designation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroup_Designation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCCGroup_Designation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsForSearch]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetailsForSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsForSearch]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsUpdated]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetailsUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDashboardInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDashboardInformation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignation]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDesignation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDesignation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignationByLevelId]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDesignationByLevelId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDesignationByLevelId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delOrgLevels]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delOrgLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_delOrgLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org_Updated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ExportShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportTempShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ExportTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllShiftPatterns]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAllShiftPatterns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetAllShiftPatterns]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShowCMITechEmployeeInGrid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSwipesHandling]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSwipesHandling]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSwipesHandling]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectWorkingDays]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectWorkingDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectWorkingDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosuredetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearClosuredetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearClosuredetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosureDetailsForModify]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearClosureDetailsForModify]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearClosureDetailsForModify]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultSE]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDefaultSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateDefaultSE]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosure]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateYearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByEncashment]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureByEncashment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByEncashment]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureModify]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureModify]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateYearClosureModify]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompany]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompany]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompany]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyForOverTime]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyForOverTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompanyForOverTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectDiscrepancyEmployee]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_SelectDiscrepancyEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_ta_SelectDiscrepancyEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployee]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeCode]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsNew]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsNew]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsUpdated]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeEmailId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeEmailId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeEmailId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeeFlexi]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectEmployeeFlexi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectEmployeeFlexi]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupPolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForPopup]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForPopup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeForPopup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForShiftAlloc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpName]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmpName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmpName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradeLevel]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGradeLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectGradeLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGrades]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGrades]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectGrades]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectHoliday]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesForEncashment]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesForEncashment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveTypesForEncashment]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesOfEmployees]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntry]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDuty]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDuty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDuty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyByID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDutyByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyByID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDutyForTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxPayrollClosureDate]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxPayrollClosureDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaxPayrollClosureDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthCloseDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthCloseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMonthCloseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureById]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthClosureById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMonthClosureById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMovementsEntryXtraGrid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOnDutyEntryByID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectOnDutyEntryByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectOnDutyEntryByID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOtType]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollMonthClosureDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermissionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPreviousYearLeaveDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPreviousYearLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPreviousYearLeaveDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShift]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPatternDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternForShiftRoster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternId]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftPatternId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoaster]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRoaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftRoaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoasterById]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRoasterById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftRoasterById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeavSancAuthority]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeavSancAuthority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LeavSancAuthority]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ManualTimeEntryExport]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ManualTimeEntryExport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ManualTimeEntryExport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosure]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearclosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertYearclosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadFirstYearLeaveQuota]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadFirstYearLeaveQuota]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LoadFirstYearLeaveQuota]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSMSLogDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSMSLogDetailsForNotification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_MonthClosure]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_MonthClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_MonthClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ImportLeaveData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ImportLeaveData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ImportLeaveData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_HolidayInsert_YearCreation]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_HolidayInsert_YearCreation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_HolidayInsert_YearCreation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDataAfterYearClosure]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDataAfterYearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertDataAfterYearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpLeavePolicydetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpLeavePolicydetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmpLeavePolicydetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertHoliday]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertImportMasterData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertImportMasterData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationByAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptYearClosure]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptYearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptYearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAddlWeekOffDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAddlWeekOffDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAddlWeekOffDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTempShiftAllocation]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTimeSheet]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTimeSheet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTimeSheet]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalDaysWorked]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalDaysWorked]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTotalDaysWorked]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalHoursList]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalHoursList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTotalHoursList]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalWorkingDays]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalWorkingDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTotalWorkingDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWagesReport]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWagesReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptWagesReport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWeeklyWorkHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ScriptEntryForDiscrepancy]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ScriptEntryForDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ScriptEntryForDiscrepancy]
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectAbsentRecords]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_SelectAbsentRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_ta_SelectAbsentRecords]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttandanceCode]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttendanceXtraGrid]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAttendanceXtraGrid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAttendanceXtraGrid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyWithApprovalSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOnDutyEntry]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOnDutyEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptOnDutyEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOverTimewithAmountDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMovementsEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_NotMatched]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry_NotMatched]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_NotMatched]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeavePolicyNotAllocated]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeavePolicyNotAllocated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeavePolicyNotAllocated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLessHoursWorked]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLessHoursWorked]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLessHoursWorked]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptManualTimeEntry]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptManualTimeEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptManualTimeEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthClosure]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Detail]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceLabour]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendanceLabour]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceLabour]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayroll]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayroll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPayroll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPayslip]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_General]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip_General]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPayslip_General]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_GeneralExport]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip_GeneralExport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPayslip_GeneralExport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShift]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermanentShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPermanentShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermission]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPermission]
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_rptPunctuality]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_rptPunctuality]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_ta_rptPunctuality]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptRawData]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_rptRawData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_rptRawData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptRawDataPunches_Dashboard]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptRawDataPunches_Dashboard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptRawDataPunches_Dashboard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation_Surguru]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftAllocation_Surguru]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptShiftAllocation_Surguru]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftNotAllocated]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftNotAllocated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptShiftNotAllocated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptSummary]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary_Old]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummary_Old]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptSummary_Old]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummaryCount]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummaryCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptSummaryCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTawazunMonthlyAttendance]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTawazunMonthlyAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTawazunMonthlyAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShift]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTemporaryShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTemporaryShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGeneralMonthlyAttendance]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGeneralMonthlyAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptGeneralMonthlyAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptHeadCountDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptHeadCountDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountSummary]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptHeadCountSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptHeadCountSummary]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateExit]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateExit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLateExit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateIn]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLateIn]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Angler]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeave_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveAnalysis]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeaveAnalysis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeaveAnalysis]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAuditTrail]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAuditTrail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAuditTrail]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptCanteenReport]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptCanteenReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptCanteenReport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyAttendance]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicExport]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamicExport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicExport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamicNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_RptDiscrepancy]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_RptDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_ta_RptDiscrepancy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptDocumentExpiry]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptDocumentExpiry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptDocumentExpiry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyEntry]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEarlyEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEarlyEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployee]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeCompOffStatus]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeCompOffStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeCompOffStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistoryNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOut]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOut]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOut]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeaves]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyLeaves]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves_Email]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeaves_Email]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyLeaves_Email]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyPermission]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission_email]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyPermission_email]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyPermission_email]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyWagesPenalty]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyWagesPenalty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyWagesPenalty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Reprocess_HolidayData]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Reprocess_HolidayData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Reprocess_HolidayData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllException]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAllException]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAllException]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Payroll]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Payroll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Payroll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByAttandance]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PayrollByAttandance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_PayrollByAttandance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByOverTime]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PayrollByOverTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_PayrollByOverTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectReport_Mesmack]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProjectReport_Mesmack]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ProjectReport_Mesmack]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxUserLevel]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxUserLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMaxUserLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpDesignation_MusterRoll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpDesignation_MusterRoll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTSanction]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffOTSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffRequestionCount]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffRequestionCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeCompOffRequestionCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffSanction]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeCompOffSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosure_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMonthClosure_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMonthClosure_Insert]
GO
/****** Object:  StoredProcedure [dbo].[UpdateDefaultGradeForSEFromDemo]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateDefaultGradeForSEFromDemo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateDefaultGradeForSEFromDemo]
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunches]'))
DROP VIEW [dbo].[TA_VW_FirstInPunches]
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches_Test]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunches_Test]'))
DROP VIEW [dbo].[TA_VW_FirstInPunches_Test]
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftPatternId]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_ShiftPatternId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Temp_ShiftPatternId]
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftRoaster]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_ShiftRoaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Temp_ShiftRoaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntryById]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualEntryById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetManualEntryById]
GO
/****** Object:  View [dbo].[TA_VW_LunchInPunches]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_LunchInPunches]'))
DROP VIEW [dbo].[TA_VW_LunchInPunches]
GO
/****** Object:  View [dbo].[TA_VW_ShiftInPunches]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_ShiftInPunches]'))
DROP VIEW [dbo].[TA_VW_ShiftInPunches]
GO
/****** Object:  StoredProcedure [dbo].[VerifyShift]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VerifyShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[VerifyShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualODEntryById]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualODEntryById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetManualODEntryById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportDataCentena]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportDataCentena]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ExportDataCentena]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLOPLeaveTypeDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLOPLeaveTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLOPLeaveTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLevelName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLevelName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLevelNameUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLevelNameUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevels]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Test]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave_Test]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeave_Test]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAbsenteesDetail]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAbsenteesDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAbsenteesDetail]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGetEmailLog]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGetEmailLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptGetEmailLog]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGAttendance]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptGAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOrgSettings]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOrgSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptOrgSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensation]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompensation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompensation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensationbyID]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompensationbyID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompensationbyID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditColumnNames]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllAuditColumnNames]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllAuditColumnNames]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEncashmentDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEncashmentDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEncashmentDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplication_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicyDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeavePolicyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeavePolicyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPunchTypes_FromDevice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertPunchTypes_FromDevice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompensationEntry]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertCompensationEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertCompensationEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_insertCompOffOTStatus]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_insertCompOffOTStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_insertCompOffOTStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmailIdsForMailTriggering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmp_LeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidayRecursion]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_HolidayRecursion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_HolidayRecursion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GroupManualEntryEmployees]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GroupManualEntryEmployees]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GroupManualEntryEmployees]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_EntranceDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_EntranceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_EntranceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Update_PunchTypes]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Update_PunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_Update_PunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAuditField]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAuditField]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAuditField]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempWeekday]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTempWeekday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTempWeekday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDatatype]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTerminalDatatype]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTerminalDatatype]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTerminalDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTerminalDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailTemplate]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailTemplate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadingPunchTypes]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadingPunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LoadingPunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Modify]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Levels_Modify]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Levels_Modify]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ListofProjects]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ListofProjects]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ListofProjects]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofGolbalHolidays]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_NumberofGolbalHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_NumberofGolbalHolidays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofYearlyHolidays]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_NumberofYearlyHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_NumberofYearlyHolidays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEdit]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OrgEdit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_OrgEdit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNotAllocated]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftNotAllocated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftNotAllocated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRestrictedHolidayDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectRestrictedHolidayDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectRestrictedHolidayDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPunchTypes]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectReceiversForSMS]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectReceiversForSMS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectReceiversForSMS]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectOrgDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectOrgDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_selectOrgDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMinLevel]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMinLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMinLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMatchingDevice]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMatchingDevice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMatchingDevice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxDayMonth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth_Testing]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxDayMonth_Testing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth_Testing]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationById]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicy]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveDetails_YearClosure]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveDetails_YearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveDetails_YearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceINOUTDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceINOUTDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEntranceINOUTDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectforcheckLP]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectforcheckLP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectforcheckLP]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEntranceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeesForBL]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectEmployeesForBL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectEmployeesForBL]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailScheduleBasedOnId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDiscrepancy]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDiscrepancy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailIDByLevel]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailIDByLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmailIDByLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectChildrenDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectChildrenDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectChildrenDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateSMSTemplateDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateSMSTemplateDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateSMSTemplateDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateOndutyForImport]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateOndutyForImport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ValidateOndutyForImport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDepartmentToCCMailIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEncashmentDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEncashmentDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateEncashmentDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateHoliday]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplication]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatePermissionApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionApplicationConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatePermissionApplicationConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUsergroupDetailsForSMS]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectUsergroupDetailsForSMS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectUsergroupDetailsForSMS]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllcation_Import]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllcation_Import]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllcation_Import]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSTemplateDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSTemplateDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectSMSTemplateDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpouseDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSpouseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSpouseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateFilterDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemplateFilterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTemplateFilterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForEntrance]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetailsForEntrance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForEntrance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsById]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_TemporaryWeekDayLevelDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAuditTableandFields]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAuditTableandFields]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateAuditTableandFields]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBonusLeavesForService]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateBonusLeavesForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdateBonusLeavesForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org_Updated_MailPopup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_get_level_Org]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompanyDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompanyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCompanyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIdForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetCompanyIdForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetCompanyIdForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIds]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetCompanyIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetCompanyIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompOffDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCompOffDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevels]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getChildLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAdditionalWeekOffByLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getChildLevelDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevels]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetChildrenLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetChildrenLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevelsCollectData]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetChildrenLevelsCollectData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetChildrenLevelsCollectData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarData]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMyCalendarData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMyCalendarData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevel]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getMinimumLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getMinimumLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelD]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLevelD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLevelD]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelDetailsForHoiday]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLevelDetailsForHoiday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLevelDetailsForHoiday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelIdForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLevelIdForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLevelIdForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationCancellation]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationCancellation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationCancellation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidayDetailsByHolidayID]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHolidayDetailsByHolidayID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetHolidayDetailsByHolidayID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDepartmentMailIds]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDepartmentMailIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDepartmentMailIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIds]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmailIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEntrance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEntrance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance_Angler]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEntrance_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEntrance_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEquivalentDeviceDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEquivalentDeviceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEquivalentDeviceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetErrorVersionDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetErrorVersionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetErrorVersionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeRequiredPeriod]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeRequiredPeriod]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeRequiredPeriod]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmployeeShiftDateDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingSMSScheduleDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingSMSScheduleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingSMSScheduleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNoOfLOP]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNoOfLOP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRemainingNoOfLOP]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingReceiverDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingReceiverDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingReceiverDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTerminalMappingCount]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTerminalMappingCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTerminalMappingCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingCompanyDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingCompanyDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingCompanyDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSLogDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSMSLogDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetSMSLogDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchTypesByTerminalId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPunchTypesByTerminalId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPunchTypesByTerminalId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchValue]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPunchValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPunchValue]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidayCount]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRestrictedHolidayCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRestrictedHolidayCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSanctionUser]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSanctionUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetSanctionUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetNumberOfHolidaysTaken]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetNumberOfHolidaysTaken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetNumberOfHolidaysTaken]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetODEntryById]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetODEntryById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetODEntryById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePrivateNotes]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeavePrivateNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeavePrivateNotes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionByPermissionId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionByPermissionId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionByPermissionId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionConversation]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetParentLevelidUsingEmpid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPassportExpiryAlert]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPassportExpiryAlert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPassportExpiryAlert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicy]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaycount]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaycount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidaycount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForOnDuty]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayForOnDuty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidayForOnDuty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckApplicableAfterDays]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckApplicableAfterDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckApplicableAfterDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Delete]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckEntrance_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckForHolidayForCollect]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckForHolidayForCollect]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckForHolidayForCollect]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHoliday]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGlobalHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGlobalHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHolidayUpdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGlobalHolidayUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGlobalHolidayUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingTerminalStatus]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingTerminalStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingTerminalStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_ImportOndutyEntry]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ImportOndutyEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_ImportOndutyEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompoffEligibility]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCompoffEligibility]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCompoffEligibility]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOff]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckAdditionalWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckAdditionalWeekOffForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowExists]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckBorrowExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckBorrowExists]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectInReaderId]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_SelectInReaderId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_SelectInReaderId]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectMatchingDevice]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_SelectMatchingDevice]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_SelectMatchingDevice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Child_Levels_Insert]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Child_Levels_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Child_Levels_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDay_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempWeekDay_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTempWeekDay_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeavePolicy]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Available]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypes_Available]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Available]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Delete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypes_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestorePunchTypes]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestorePunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestorePunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekday]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreWeekday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreWeekday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekOff]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteImportErrorData]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteImportErrorData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteImportErrorData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountYearlyHoliday]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountYearlyHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CountYearlyHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicyDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeavePolicyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGlobalHoliday]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountGlobalHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CountGlobalHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntry]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualTimeEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeeSpouseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectCompany]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CMITechSelectCompany]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CMITechSelectCompany]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLevels]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_delLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteSpouseDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteSpouseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteSpouseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOndutyEntry]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOndutyEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteOndutyEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermissionApplication]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermissionApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeletePermissionApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePunchTypes]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeletePunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Pro_TA_ViewProjectbyProjectId]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Pro_TA_ViewProjectbyProjectId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Pro_TA_ViewProjectbyProjectId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTStatus]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeOTStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTLeaveApplication]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeOTLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllocateWeekOff_AutoShift]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AllocateWeekOff_AutoShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AllocateWeekOff_AutoShift]
GO
/****** Object:  StoredProcedure [dbo].[EmpReProcess]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpReProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[EmpReProcess]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_CountNumberOfWorkingDays]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_CountNumberOfWorkingDays]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TA_CountNumberOfWorkingDays]
GO
/****** Object:  StoredProcedure [dbo].[ReminderMailForLeavePolicyUpdationToHR]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReminderMailForLeavePolicyUpdationToHR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReminderMailForLeavePolicyUpdationToHR]
GO
/****** Object:  StoredProcedure [dbo].[select_EmpLeavePolicyDetails_EDR]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[select_EmpLeavePolicyDetails_EDR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[select_EmpLeavePolicyDetails_EDR]
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeePunchMonitor]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_EmployeePunchMonitor]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TA_Proc_EmployeePunchMonitor]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]
GO
/****** Object:  StoredProcedure [dbo].[temp_UpdatePerShiftAllocation]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[temp_UpdatePerShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[temp_UpdatePerShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPermission]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertPermission]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetParentChild]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetParentChild]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TA_GetParentChild]
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_checkHolidayLeaveApplication]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_checkHolidayLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TA_Tbl_checkHolidayLeaveApplication]
GO
/****** Object:  View [dbo].[TA_VW_BreakFirstInPunches]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakFirstInPunches]'))
DROP VIEW [dbo].[TA_VW_BreakFirstInPunches]
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakInPunches]'))
DROP VIEW [dbo].[TA_VW_BreakInPunches]
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches_Test]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakInPunches_Test]'))
DROP VIEW [dbo].[TA_VW_BreakInPunches_Test]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterDataLevelsParent]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMasterDataLevelsParent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertMasterDataLevelsParent]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNearingShiftDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertNearingShiftDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertNearingShiftDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateMasterDataLevelsParent]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateMasterDataLevelsParent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateMasterDataLevelsParent]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delEmployee]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_delEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteChildrenDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteChildrenDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteChildrenDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DataBaseArcheive]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DataBaseArcheive]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DataBaseArcheive]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDeviceMappingInEntrance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingEachDropDown]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingEachDropDown]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckingEachDropDown]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent_Email]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsent_Email]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_rptAbsent_Email]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntryWithLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_header]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Rpt_header]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header_Email]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_header_Email]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Rpt_header_Email]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetParentIds]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetParentIds]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_GetParentIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateTrigger]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CreateTrigger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CreateTrigger]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsAlready]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataExistsAlready]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingDataExistsAlready]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays_GlobalDate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidays_GlobalDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidays_GlobalDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysUpdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidaysUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicy]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLeavePolicy]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_ReportingTo]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetMappedEmployees_ReportingTo]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TA_GetMappedEmployees_ReportingTo]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetDateTimeFormat]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetDateTimeFormat]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_GetDateTimeFormat]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_SancAuthority]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetMappedEmployees_SancAuthority]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TA_GetMappedEmployees_SancAuthority]
GO
/****** Object:  UserDefinedFunction [dbo].[SplitupEmployeeCode]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitupEmployeeCode]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitupEmployeeCode]
GO
/****** Object:  UserDefinedFunction [dbo].[SplitUpEmployeeName]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitUpEmployeeName]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitUpEmployeeName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBulkConfiguration]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeBulkConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeBulkConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckIgnoreDuplicatePunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIndividualUser]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckIndividualUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckIndividualUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingAllreadyExistsForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysTempWeekDay]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysTempWeekDay]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidaysTempWeekDay]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_EarlyOut]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterReason_EarlyOut]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EnterReason_EarlyOut]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_LateIn]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterReason_LateIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EnterReason_LateIn]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetRemarks]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetRemarks]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_GetRemarks]
GO
/****** Object:  View [dbo].[ta_view]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ta_view]'))
DROP VIEW [dbo].[ta_view]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsentCount]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsentCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_rptAbsentCount]
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_TA_GetDateFormat]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Fun_TA_GetDateFormat]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Fun_TA_GetDateFormat]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_AbsentDate]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_AbsentDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_AbsentDate]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpCategory]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpCategory]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_EmpCategory]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpDesignation]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpDesignation]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_EmpDesignation]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpLevel]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpLevel]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_EmpLevel]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpType]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpType]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_EmpType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormat]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateandTimeFormat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DateandTimeFormat]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormatUpdation]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateandTimeFormatUpdation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DateandTimeFormatUpdation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCountry]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCountry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteCountry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Delete_CompanyDetailsForService]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Delete_CompanyDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_Delete_CompanyDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAddlWeekoff]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAddlWeekoff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteAddlWeekoff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOnDutyApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOnDutyApplicationConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateOnDutyApplicationConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOTRoundoffSettings]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOTRoundoffSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateOTRoundoffSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOtType]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOvertimeHours]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOvertimeHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateOvertimeHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateLevels]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_updateLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_updateLevels]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualEntryApplicationSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateManualNotation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateManualNotation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdateManualNotation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualTimeEntry]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualTimeEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateManualTimeEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReprocessEmpData]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReprocessEmpData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ReprocessEmpData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ResetBonusLeaveForService]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ResetBonusLeaveForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ResetBonusLeaveForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ResetPassword]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ResetPassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ResetPassword]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreAttandanceCode]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RestoreAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNews]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertNews]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertNews]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntry]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOnDutyEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntryForTable]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOnDutyEntryForTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntryForTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertorUpdateEmployeeLingual]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertorUpdateEmployeeLingual]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertorUpdateEmployeeLingual]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOtType]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry_Group]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntry_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMobileClockIn]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMobileClockIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertMobileClockIn]
GO
/****** Object:  StoredProcedure [dbo].[Temp_UpdateShift]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_UpdateShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Temp_UpdateShift]
GO
/****** Object:  StoredProcedure [dbo].[RemoveDuplicateData]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDuplicateData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveDuplicateData]
GO
/****** Object:  StoredProcedure [dbo].[RemoveTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[RemoveTemporaryShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[ReProcess_EmpLogs]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReProcess_EmpLogs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReProcess_EmpLogs]
GO
/****** Object:  StoredProcedure [dbo].[SelectReportingToSanctionAuthorityForPermission]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectReportingToSanctionAuthorityForPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelectReportingToSanctionAuthorityForPermission]
GO
/****** Object:  StoredProcedure [dbo].[Template_LogInsert]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_LogInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Template_LogInsert]
GO
/****** Object:  StoredProcedure [dbo].[EmpReEntry]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpReEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[EmpReEntry]
GO
/****** Object:  UserDefinedFunction [dbo].[TimeOnly]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TimeOnly]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TimeOnly]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetEmployeeWorkingHours]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetEmployeeWorkingHours]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_TA_GetEmployeeWorkingHours]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BindProjectdetails]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BindProjectdetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_BindProjectdetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutomaticLeaveCancellation]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutomaticLeaveCancellation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AutomaticLeaveCancellation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DomainLogin]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DomainLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DomainLogin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVEmployeeCreation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVEmployeeCreation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DVEmployeeCreation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVLevelCreation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVLevelCreation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DVLevelCreation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVYearSetting]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVYearSetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DVYearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkLeaveSanction]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkLeaveSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_BulkLeaveSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculateOTDays]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CalculateOTDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CalculateOTDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_Proc_checkGroupName]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Proc_checkGroupName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TA_Tbl_Proc_checkGroupName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delUserGroup]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delUserGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_delUserGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeProcessBonusLeave]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeProcessBonusLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeProcessBonusLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeLeaveDetailsByDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EditDeleteImportErrorData]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EditDeleteImportErrorData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EditDeleteImportErrorData]
GO
/****** Object:  StoredProcedure [dbo].[Insert_Update_CustomFormatForExportData]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Insert_Update_CustomFormatForExportData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Insert_Update_CustomFormatForExportData]
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDevice]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertIrisLogsFromDevice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InsertIrisLogsFromDevice]
GO
/****** Object:  StoredProcedure [dbo].[GetDatetime]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDatetime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetDatetime]
GO
/****** Object:  StoredProcedure [dbo].[InsertMariaLogsInToReportsList]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertMariaLogsInToReportsList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InsertMariaLogsInToReportsList]
GO
/****** Object:  StoredProcedure [dbo].[Proc_CheckNewsInYearSettings]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_CheckNewsInYearSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_CheckNewsInYearSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_editLevel]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_editLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_editLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Get_VehicleDetailsByRouteId]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Get_VehicleDetailsByRouteId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Get_VehicleDetailsByRouteId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetEmployeeDetails]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GetEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]
GO
/****** Object:  View [dbo].[OrderByEmployeeCodeId]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[OrderByEmployeeCodeId]'))
DROP VIEW [dbo].[OrderByEmployeeCodeId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProgressDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteProgressDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteProgressDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProject]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteProject]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOTRoundoffSettings]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOTRoundoffSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteOTRoundoffSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOtType]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTempShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminal]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTerminal]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalDatatype]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminalDatatype]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTerminalDatatype]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalMapping]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminalMapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTerminalMapping]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShift]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftId]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLookup]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delLookup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_delLookup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitleMapping]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTitleMapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteTitleMapping]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternOverlapping]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternOverlapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftPatternOverlapping]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountTitle]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountTitle]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CountTitle]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CountTotInAndOutPunches]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CountTotInAndOutPunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CountTotInAndOutPunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CounShift]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CounShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CounShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpName]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmpName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpNameGroupPolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEntranceDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEntranceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEntranceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeedetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeedetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmployeedetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeesFromTempTable]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeesFromTempTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmployeesFromTempTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveType]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLevelWiseRights]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLevelWiseRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLevelWiseRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLogo]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLogo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLogo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLookupData]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLookupData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLookupData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualEntry]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmailLogData]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmailLogData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteEmailLogData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGrade]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteGrade]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteGrade]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRoute]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreReligion]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreReligion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreReligion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminal]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreTerminal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreTerminal]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminalDataType]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreTerminalDataType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreTerminalDataType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRawFormat]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRawFormat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRawFormat]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReferranceReligion]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReferranceReligion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckReferranceReligion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReligion_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReligion_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckReligion_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckreligionType]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckreligionType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckreligionType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReportingPerson]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReportingPerson]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckReportingPerson]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreEntrance]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreEntrance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreEntrance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeaveType]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRestoreLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSanctioningPerson]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckSanctioningPerson]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckSanctioningPerson]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShift]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftDelete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftTime]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftRestore]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftRestore]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftRestore]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSuperAdminUser]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckSuperAdminUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckSuperAdminUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTemporaryShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTerminalName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName_Sync]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalName_Sync]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTerminalName_Sync]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalNameUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTerminalNameUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitleName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTitleName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleNameBYID]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitleNameBYID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTitleNameBYID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDelete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTypeDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicate]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDuplicate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicateForRestore]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDuplicateForRestore]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicateForRestore]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUnProcessedDataExists]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUnProcessedDataExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckUnProcessedDataExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserExists]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckUserExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserRights]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckUserRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserStatus]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckUserStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectRBMSRawDataForService]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CollectRBMSRawDataForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CollectRBMSRawDataForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectTerminalDetailsForService]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CollectTerminalDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CollectTerminalDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationEntryByID]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationEntryByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CompensationEntryByID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Update]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicle_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]
GO
/****** Object:  StoredProcedure [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]
GO
/****** Object:  StoredProcedure [dbo].[CheckApplicationDateExistsinYearsettings]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckApplicationDateExistsinYearsettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CheckApplicationDateExistsinYearsettings]
GO
/****** Object:  StoredProcedure [dbo].[CheckLeaveBeforeAfterWithPermission]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckLeaveBeforeAfterWithPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CheckLeaveBeforeAfterWithPermission]
GO
/****** Object:  StoredProcedure [dbo].[CheckVehicleNoExists]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckVehicleNoExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CheckVehicleNoExists]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_LeaveDate]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_LeaveDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_LeaveDate]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_MusterRoll_OD_Notation]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_MusterRoll_OD_Notation]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_MusterRoll_OD_Notation]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_OnDuty]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_OnDuty]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_OnDuty]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PendingLeaveDate]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_PendingLeaveDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_PendingLeaveDate]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PermissionDate]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_PermissionDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_PermissionDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowLeaveExists]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckBorrowLeaveExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckBorrowLeaveExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDelete]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCategoryDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDuplicate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDuplicateForAdding]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Insert]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAddlWeekOff_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Update]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAddlWeekOff_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompOffMapped]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCompOffMapped]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCompOffMapped]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckConcurrentUserCount]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckConcurrentUserCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckConcurrentUserCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountFacorLeaveTypes]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCountFacorLeaveTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCountFacorLeaveTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCount]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckDefaultShiftCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmailID]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmailID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmailID]
GO
/****** Object:  StoredProcedure [dbo].[proc_lateEntry]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_lateEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_lateEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseExpiryDate]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseExpiryDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_OL_SelectLicenseExpiryDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestID]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseRequestID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseRequestIDReactivation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllEmployees]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AllEmployees]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_AllEmployees]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActiveEmployeeDetails]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ActiveEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ActiveEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Insert]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeave_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeave_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Update]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeave_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeave_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplication_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationUpdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForGivenDate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForGivenDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForGivenDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForManualEntry_OD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForOnDuty]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForOnDuty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForOnDuty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForProcessing]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForProcessing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForProcessing]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForwardingPerson]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForwardingPerson]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveForwardingPerson]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGEOLocationUtilization]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGEOLocationUtilization]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGEOLocationUtilization]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Update]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGradeName_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeStandard]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGradeStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHalfDayLeave]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHalfDayLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHalfDayLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Insert]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckEntrance_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntranceMap]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntranceMap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckEntranceMap]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckExactDuplicateRecordExists]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckExactDuplicateRecordExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckExactDuplicateRecordExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAttandanceCode]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_checkDuplicationUsergroup]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_checkDuplicationUsergroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_checkDuplicationUsergroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEmployeePFESI]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEmployeePFESI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckEmployeePFESI]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavepolicyName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavepolicyName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeavepolicyName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveSanctioningPerson]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveSanctioningPerson]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveSanctioningPerson]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingIgnorePunches]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingIgnorePunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingIgnorePunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType_LeaveApp]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveType_LeaveApp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveType_LeaveApp]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveOnSameDay]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveOnSameDay]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveOnSameDay]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckOtType]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPageExistsInLicense]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPageExistsInLicense]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPageExistsInLicense]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPassword]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPassword]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry_OD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForProcessing]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForProcessing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionForProcessing]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionHours]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckPermissionUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedData]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedManualEntryId]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcessedManualEntryId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckProcessedManualEntryId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollConfigurationDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPayrollConfigurationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPayrollConfigurationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPenaltyPercentageDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPenaltyPercentageDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPenaltyPercentageDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRawDataFromManualEntry]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRawDataFromManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRawDataFromManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReaderDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReaderDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetReaderDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveSanction]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRecordsCountLeaveSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionDetailsById]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReligionDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetReligionDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionTypeDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReligionTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetReligionTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNewsById]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getNewsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getNewsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyConversation]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOnDutyConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatus]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetOverTimeApprovalStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPageName]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPageName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPageName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSaturday_WorkHrs]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSaturday_WorkHrs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetSaturday_WorkHrs]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetScheduleDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetScheduleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetScheduleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftByWeekDayId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getShiftByWeekDayId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getShiftByWeekDayId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRouteCountFromEmployee]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRouteCountFromEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRouteCountFromEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPage]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountAllPage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPageStandard]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountAllPageStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPageStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPage]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountInPage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRowsCountInPage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPageStandard]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountInPageStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetRowsCountInPageStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportsForEmailSchedule]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReportsForEmailSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetReportsForEmailSchedule]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportToAndSanctionAuthority]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReportToAndSanctionAuthority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetReportToAndSanctionAuthority]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousLeaveDetails]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPreviousLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPreviousLeaveDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousNextLeave]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPreviousNextLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetPreviousNextLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetShiftId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetShiftId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdBeforeWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIDForParticularDate]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIDForParticularDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftIDForParticularDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftSettings]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getShiftSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getShiftSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComId]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftSettingsByComId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortName]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftShortName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftShortName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortNameWithOutTime]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftShortNameWithOutTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftShortNameWithOutTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftUsingID]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftUsingID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftUsingID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSTemplateStatus]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSMSTemplateStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetSMSTemplateStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSubMenus]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSubMenus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetSubMenus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTaskDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetTaskDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetTaskDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTaskDetails_ParticularProject]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTaskDetails_ParticularProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTaskDetails_ParticularProject]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingBLCountForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingBLCountForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingBLCountForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDataFromClockDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingDataFromClockDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingDataFromClockDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDeviceDataBaseDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingDeviceDataBaseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingDeviceDataBaseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingIsAutoShiftEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingLeaveDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingLeaveDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingLeaveDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLunchDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingLunchDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingLunchDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeRemarks]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeRemarks]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeRemarks]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingRawDatasForservice]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingRawDatasForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingRawDatasForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingNonProcessedRawDataRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingOTRoundOffValuesForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOverTimeParametersForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingOverTimeParametersForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingOverTimeParametersForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPermissionDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPermissionDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingPermissionDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingResponseStatus]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingResponseStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingResponseStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForSMS]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsForSMS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForSMS]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedData]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingUnProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedDataForService]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingUnProcessedDataForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedDataForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingVersionNumber]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingVersionNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingVersionNumber]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationMappingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationMappingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationMappingDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationMappingDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedData]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUnProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationVehicleDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetTransportationVehicleDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearAvailedLeaveDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearAvailedLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetYearAvailedLeaveDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingId]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearSettingId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetYearSettingId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetYearSettingIdForService]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetYearSettingIdForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetYearSettingIdForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingIdForWin]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearSettingIdForWin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetYearSettingIdForWin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUsergroupDetails]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUsergroupDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUsergroupDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroupName]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getUserGroupName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getUserGroupName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroups]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getUserGroups]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getUserGroups]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenu]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserMenu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUserMenu]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenus]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserMenus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUserMenus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserRights]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetUserRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetVehicleDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetVehicleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetVehicleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getGroupNameById]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getGroupNameById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getGroupNameById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetGroupNameForEmployee]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetGroupNameForEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetGroupNameForEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHelpContent]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHelpContent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetHelpContent]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeSpecificDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeSpecificDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeSpecificDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetExpInfo]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetExpInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetExpInfo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetFirstInDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetFirstInDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetFirstInDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInDetailsForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetFirstInDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetFirstInDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInPunchTypeForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetFirstInPunchTypeForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetFirstInPunchTypeForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailScripts]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailScripts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmailScripts]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmpforShift]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmpforShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmpforShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoId]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeAutoId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoIdForImport]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeAutoIdForImport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoIdForImport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeCodeID]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeCodeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeCodeID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailReportNotSendedDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailReportNotSendedDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmailReportNotSendedDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailSchedule]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmailSchedule]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeFromCMITechDevice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeLingual]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeLingual]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeLingual]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeName]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeOTEligible]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeOTEligible]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeOTEligible]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidaySettings]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHolidaySettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetHolidaySettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetInAndOutPunchDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetInAndOutPunchDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInformToEmployee]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetInformToEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetInformToEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLanguageDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLanguageDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLanguageDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastLogin]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLastLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLastLogin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastOutDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLastOutDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLastOutDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutDetailsForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLastOutDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForService]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLastOutForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutForServiceDataProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCommentsById]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveCommentsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveCommentsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveConversation]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetailsById]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeDetailsById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveTypeDetailsById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLeaveTypeForservice]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLeaveTypeForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetLeaveTypeForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeName]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveTypeName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSettingsByComId]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSettingsByComId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveSettingsByComId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSummary]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveSummary]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTakenInMonth]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTakenInMonth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveTakenInMonth]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelName]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevelName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getLevelName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevelDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getLevelDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetClockID_FirstData]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetClockID_FirstData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetClockID_FirstData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCommaSeparatedValues]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCommaSeparatedValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCommaSeparatedValues]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCityDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCityDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCityDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getAllNews]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getAllNews]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getAllNews]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Details]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroup_Details]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCCGroup_Details]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetChildMenu]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetChildMenu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetChildMenu]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays_Angler]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompOffDays_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCompOffDays_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountFlexibleTimings]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCountFlexibleTimings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCountFlexibleTimings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDateOfJoining]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDateOfJoining]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDateOfJoining]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDatesWithFormat]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDatesWithFormat]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDatesWithFormat]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCurrentDateProgressDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCurrentDateProgressDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCurrentDateProgressDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetDuplicatePunches]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetDuplicatePunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetDuplicatePunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDeviceLogTableDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDeviceLogTableDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDeviceLogTableDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDevices]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDevices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetDevices]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Get_ReportingToEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Get_SanctioningEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_get_Total_Level]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_get_Total_Level]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_get_Total_Level]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAccessDeniedSettingEntries]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAccessDeniedSettingEntries]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetAccessDeniedSettingEntries]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveLanguageDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetActiveLanguageDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetActiveLanguageDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveYearSettingDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetActiveYearSettingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetActiveYearSettingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetApprovalAuthority]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetApprovalAuthority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetApprovalAuthority]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetApprovalStatus]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetApprovalStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetApprovalStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAttendanceData]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAttendanceData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetAttendanceData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetBasicShiftSettingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetBrandDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetBrandDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetBrandDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_FillTempProcessTable]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_FillTempProcessTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_FillTempProcessTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FinalProgressUpdation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_FinalProgressUpdation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_FinalProgressUpdation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_one]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_one]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_get_level_one]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockProcess]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateClockProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateClockProcess]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBLStatusByService]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateBLStatusByService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdateBLStatusByService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateConcurrentUser]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateConcurrentUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateConcurrentUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultRights]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDefaultRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateDefaultRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveTypeDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LeaveTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_LeaveTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateActiveLanguage]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateActiveLanguage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateActiveLanguage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateAttandanceCode]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_updateAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_updateAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance_Eastman]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAttendance_Eastman]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateAttendance_Eastman]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToCheckLastOutIsManual]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ToCheckLastOutIsManual]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ToCheckLastOutIsManual]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UnUsedTerminalsinProject]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UnUsedTerminalsinProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UnUsedTerminalsinProject]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_TotalBreakHours]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_TotalBreakHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_TotalBreakHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Delete]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Transportation_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Mapping_Delete]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Mapping_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Transportation_Mapping_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsByIdForService]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftDetailsByIdForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftDetailsByIdForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShrinkDatabase]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShrinkDatabase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShrinkDatabase]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SkipErroredDataForService]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SkipErroredDataForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SkipErroredDataForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SuccessiveYearSettings]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SuccessiveYearSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SuccessiveYearSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SwipeCardNoExists]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SwipeCardNoExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SwipeCardNoExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempInsertEmployee]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Tbl_TempInsertEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Tbl_TempInsertEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempUpdateEmployee]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Tbl_TempUpdateEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Tbl_TempUpdateEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalName]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSuccessiveDates]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSuccessiveDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSuccessiveDates]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpellCountByLeaveType]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSpellCountByLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSpellCountByLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationReprocess]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocationReprocess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocationReprocess]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUserName]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectUserName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectUserName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectVersion]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectVersion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectVersion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_RawData]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_RawData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_RawData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSetting]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingbyId]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettingbyId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearSettingbyId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingForLeaveReport]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettingForLeaveReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearSettingForLeaveReport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettings]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectYearSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails_CMITech]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetails_CMITech]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails_CMITech]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectType]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTypeDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionSanction]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionSanction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatePermissionSanction]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePerShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePerShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatePerShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedData]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlag]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedDataFlag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlag]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessflag]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessflag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateProcessflag]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRawDataFlag]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRawDataFlag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateRawDataFlag]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCount]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRowsCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateRowsCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCountStandard]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRowsCountStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateRowsCountStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationConversation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationConversation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationMaster]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePassword]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatePassword]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExistingUserStatusFalse]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateExistingUserStatusFalse]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateExistingUserStatusFalse]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExpInfo]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateExpInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateExpInfo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeFlexi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi_All]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeFlexi_All]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi_All]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateSelectedLeavePolicy]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateSelectedLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ValidateSelectedLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleMapping]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TitleMapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_TitleMapping]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_Transportation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_Transportation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationMapping]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TransportationMapping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_TransportationMapping]
GO
/****** Object:  StoredProcedure [dbo].[Proc_UpdateOTHours]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_UpdateOTHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_UpdateOTHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserLogin]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UserLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UserLogin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_WriteErrorDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_WriteErrorDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_WriteErrorDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_InsertResponseDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_InsertResponseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TC_InsertResponseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_SelectLicenseReqDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_SelectLicenseReqDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TC_SelectLicenseReqDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_UpdateResponseDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_UpdateResponseDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TC_UpdateResponseDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftReport]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftReport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftSettings]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTimesheetEntry]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateTimesheetEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateTimesheetEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserProfile]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateUserProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateUserProfile]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserStatus]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateUserStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateUserStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateVoidUnVoid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid_Group]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateVoidUnVoid_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearsetting]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearsetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateYearsetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatingSMSGatewayDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatingSMSGatewayDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdatingSMSGatewayDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectClockDetailsByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategory]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCategory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategoryDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCategoryDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCategoryDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceFromBiostar]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDeviceFromBiostar]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDeviceFromBiostar]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyGroup]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectCompanyGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailByEmpId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmailByEmpId]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectEmployeeDetailsForTesting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpDemo]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmpDemo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmpDemo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeShift]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeSwipeCardNo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesByIds]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeesByIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeesByIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeGroupName]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeGroupName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeGroupName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeLevel]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSatDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeSatDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeSatDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradesStandard]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGradesStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectGradesStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectLeaveDetailsForService]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectLeaveDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectLeaveDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectImportErrorData]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectImportErrorData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectImportErrorData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveAnalysisNotes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveType]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLevelRights]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLevelRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLevelRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxEmpID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxEmpID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaxEmpID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxHoliday]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaxHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaximumNoOfHolidays]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaximumNoOfHolidays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMaximumNoOfHolidays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXLeavePolicyID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXLeavePolicyID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMAXLeavePolicyID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectLocation]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_selectLocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogDownloaded]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLogDownloaded]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLogDownloaded]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLoginDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLoginDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginLock]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLoginLock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLoginLock]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogo]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLogo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLogo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLookupData]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLookupData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLookupData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureDetails]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthClosureDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectMonthClosureDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextShiftId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectNextShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectNextShiftId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextYearSetting]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectNextYearSetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectNextYearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPreviousLevelCount]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectPreviousLevelCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectPreviousLevelCount]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPermissionDetailsForService]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectPermissionDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectPermissionDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectParentLevel]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectParentLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_selectParentLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNames]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNames]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNames]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReligion]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReligion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectReligion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthority]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReportingToSanctionAuthority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthority]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRawDataFormats]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectRawDataFormats]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectRawDataFormats]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectReaderBasicInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo_New]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectReaderBasicInfo_New]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo_New]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShift]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSearchShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSearchShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShiftByShortName]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSearchShiftByShortName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectSearchShiftByShortName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftForShiftPattern]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftForShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftForShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftByCompany]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftByCompany]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftByCompany]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForService]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftIdForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNameById]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftNameById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftNameById]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForFieldDuty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForOnDuty]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForOnDuty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftIdForOnDuty]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSGateWayDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSGateWayDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectSMSGateWayDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSLogDeatils]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSLogDeatils]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectSMSLogDeatils]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OndutyApplicationApproved]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OndutyApplicationApproved]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_OndutyApplicationApproved]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MaxHoliday]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_MaxHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_MaxHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDiscrepancyData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDiscrepancyData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertDiscrepancyData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NotProcessedDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_NotProcessedDataDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_NotProcessedDataDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Insert]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Levels_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Levels_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_MappingCorrespondingPunches]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_MappingCorrespondingPunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_MappingCorrespondingPunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUserOwn]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutUserOwn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LogoutUserOwn]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LookupTable]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LookupTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LookupTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadLeaveTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LoadLeaveTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadShiftByLevelsId]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadShiftByLevelsId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LoadShiftByLevelsId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LocationNameExists]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LocationNameExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LocationNameExists]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoginOrNot]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoginOrNot]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LoginOrNot]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutAdmin]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutAdmin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LogoutAdmin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearSetting]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearSetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertYearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_IsAuditTrailSaved]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_IsAuditTrailSaved]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_IsAuditTrailSaved]
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_LateEntry]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_LateEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TA_LateEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveAvailedinMonth]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveAvailedinMonth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LeaveAvailedinMonth]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_LeaveBonusAbsentees]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_LeaveBonusAbsentees]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_LeaveBonusAbsentees]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateInDetailsForService]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertUpdateInDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertUpdateInDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateLeaveSettings]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateLeaveSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateLeaveSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateProject]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateProject]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateType]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUserName]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUserName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUserName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateActiveLanguage]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateActiveLanguage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateActiveLanguage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateApprovalSettings]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateApprovalSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateApprovalSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory_Angler]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCategory_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCompanyGroup]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCompanyGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateCompanyGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTATblPage]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTATblPage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTATblPage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTempShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTempShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertTimeSheetEntryDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTrace]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTrace]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTrace]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogin]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LastLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogin]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogout]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LastLogout]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogout]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LoginLock]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LoginLock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdate_LoginLock]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftExchange]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftExchange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertShiftExchange]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMailConfiguration]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMailConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertMailConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPrevPermission_Eastman]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPrevPermission_Eastman]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertPrevPermission_Eastman]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertProcessedData]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAutoShiftDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAutoShiftDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAutoShiftDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdateProcessedData]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAndUpdateProcessedData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAndUpdateProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAttandanceCode]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAccessDeniedSettings]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAccessDeniedSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAccessDeniedSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_Transportation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_MappingDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation_MappingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_Transportation_MappingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TransportationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_TransportationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveTypeDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveTypeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_LeaveTypeDetails]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_ReligionDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_ReligionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_ReligionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Title_MappingDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Title_MappingDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_Title_MappingDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InserAuditTable]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InserAuditTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InserAuditTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidaySettings]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_HolidaySettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_HolidaySettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmpDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailScheduleStatus]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmailScheduleStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmailScheduleStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertDashboardRightsDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertDashboardRightsDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertDashboardRightsDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDemoInfo]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDemoInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertDemoInfo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterDataStandard]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertImportMasterDataStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertImportMasterDataStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertInAndOutPunchDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertInAndOutPunchDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertInDetailsForService]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertInDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertInDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveAnalysisNotes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeEntranceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpName]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmpName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpNameGroupPolicy]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpNameGroupPolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertEmpNameGroupPolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertRawDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertRawDataDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertRawDataDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShift]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLevelWiseRights]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLevelWiseRights]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLevelWiseRights]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogDownloaded]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLogDownloaded]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLogDownloaded]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogo]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLogo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLogo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGeofenceDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertGeofenceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertGeofenceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationMaster]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicy]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditTableNames]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllAuditTableNames]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllAuditTableNames]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RstoreOtType]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RstoreOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RstoreOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_TerminalforView]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_TerminalforView]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Select_TerminalforView]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_UserGroupName]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_UserGroupName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Select_UserGroupName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllNews]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllNews]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllNews]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllType]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllYearSetting]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllYearSetting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllYearSetting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectApprovalSettings]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectApprovalSettings]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectApprovalSettings]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDashBoardRightsDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDashBoardRightsDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDashBoardRightsDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetailsGroupPolicy]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDetailsGroupPolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDetailsGroupPolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyExit]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEarlyExit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEarlyExit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RecursionLeaveDays]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RecursionLeaveDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RecursionLeaveDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OverTimeRoundOff]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OverTimeRoundOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_OverTimeRoundOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ParentIDs]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ParentIDs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ParentIDs]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RemoveImportMasterErrData]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RemoveImportMasterErrData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RemoveImportMasterErrData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplaceInDetailsForService]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ReplaceInDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ReplaceInDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReplaceReportingPerson]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReplaceReportingPerson]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ReplaceReportingPerson]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteOtType]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PermanentDeleteOtType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_PermanentDeleteOtType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PolicyName]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PolicyName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_PolicyName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Preferences]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Preferences]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Preferences]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProInsertShiftLocation]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProInsertShiftLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ProInsertShiftLocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectDuplicate]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProjectDuplicate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ProjectDuplicate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetail]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAttendanceDetail]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetailold]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetailold]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAttendanceDetailold]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAttendanceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenu]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReportsSubMenu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ReportsSubMenu]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenuForExpress]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReportsSubMenuForExpress]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ReportsSubMenuForExpress]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic1]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamic1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic1]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeavesUnplanned]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeavesUnplanned]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDailyLeavesUnplanned]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLocationDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLocationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLocationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayroll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForPayroll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayroll]
GO
/****** Object:  StoredProcedure [dbo].[EmpINReEntry]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpINReEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[EmpINReEntry]
GO
/****** Object:  StoredProcedure [dbo].[EmpOUTReEntry]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpOUTReEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[EmpOUTReEntry]
GO
/****** Object:  StoredProcedure [dbo].[EmpProcessStatus]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpProcessStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[EmpProcessStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTStatus]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffOTStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeaveAvailed]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeaveAvailed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLeaveAvailed]
GO
/****** Object:  StoredProcedure [dbo].[DeleteCustomDataBasedOnOptionType]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteCustomDataBasedOnOptionType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteCustomDataBasedOnOptionType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPage]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMandatoryPage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMandatoryPage]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPageStandard]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMandatoryPageStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMandatoryPageStandard]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry_Group]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntry_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualEntry_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryForImport]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntryForImport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualEntryForImport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMailConfiguration]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMailConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetMailConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelName_FromLevelID]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLevelName_FromLevelID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLevelName_FromLevelID]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getmastersSubMenu]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getmastersSubMenu]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getmastersSubMenu]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveWithPermission]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveWithPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveWithPermission]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntry]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualODEntry]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryForODUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntryForODUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualODEntryForODUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntryUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualODEntryUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMaxHoliday]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMaxHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMaxHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMinTime]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMinTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckMinTime]
GO
/****** Object:  StoredProcedure [dbo].[VerifyWarningAlertMsgTriggerredAlready]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VerifyWarningAlertMsgTriggerredAlready]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[VerifyWarningAlertMsgTriggerredAlready]
GO
/****** Object:  View [dbo].[VW_FetchDataFromProcessedData]    Script Date: 03/25/2021 10:22:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VW_FetchDataFromProcessedData]'))
DROP VIEW [dbo].[VW_FetchDataFromProcessedData]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMaxLevel]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMaxLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetMaxLevel]
GO
/****** Object:  StoredProcedure [dbo].[GetActiveLanguage]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetActiveLanguage]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetActiveLanguage]
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFieldNameForExportData]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCustomFieldNameForExportData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetCustomFieldNameForExportData]
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFormatForExportData]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCustomFormatForExportData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetCustomFormatForExportData]
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonth]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDateMonth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetDateMonth]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateFTPConfiguration]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateFTPConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertUpdateFTPConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectFTPConfiguration]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectFTPConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectFTPConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonthYear]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDateMonthYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetDateMonthYear]
GO
/****** Object:  UserDefinedFunction [dbo].[udf_CompleteWeekRange]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_CompleteWeekRange]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_CompleteWeekRange]
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_Delete_LeaveType]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_Delete_LeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[proc_TA_Delete_LeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveType]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_LeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveTypeExist]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveTypeExist]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LeaveTypeExist]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_LeaveType]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_LeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Select_LeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Template_Enroll]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Enroll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Template_Enroll]
GO
/****** Object:  StoredProcedure [dbo].[Template_Read]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Read]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Template_Read]
GO
/****** Object:  StoredProcedure [dbo].[DEVICEMASTER_INSERT]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DEVICEMASTER_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DEVICEMASTER_INSERT]
GO
/****** Object:  StoredProcedure [dbo].[DEVICEENR_TEMP_DELETE]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DEVICEENR_TEMP_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DEVICEENR_TEMP_DELETE]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntryUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckManualEntryUpdate]
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekday]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteWeekday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteWeekday]
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekOff]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[DeleteWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLogFileSize]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLogFileSize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLogFileSize]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllSwipe]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAllSwipe]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptAllSwipe]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteAttandanceCode]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PermanentDeleteAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_PermanentDeleteAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplacingSMSContent]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ReplacingSMSContent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_ReplacingSMSContent]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RegionNameByCid]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RegionNameByCid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RegionNameByCid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailedAttendance]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailedAttendance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptDetailedAttendance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeDetails]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptEmployeeDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistory]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptEmployeeSchedule]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_rptEmployeeSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_rptEmployeeSchedule]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveDetail]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeaveDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLeaveDetail]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateInstance]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateInstance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptLateInstance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDevice]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDevice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDevice]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceDetails]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDeviceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectDeviceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectBLDetailsForService]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectBLDetailsForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_SelectBLDetailsForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllTableNames]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllTableNames]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllTableNames]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllColumnNames]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllColumnNames]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectAllColumnNames]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SearchShiftExchange]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SearchShiftExchange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SearchShiftExchange]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Select]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountSummary]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOverTimewithAmountSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountSummary]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShit]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTemporaryShit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptTemporaryShit]
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_RPTRAWDATAPUNCHES]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_RPTRAWDATAPUNCHES]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PROC_TA_RPTRAWDATAPUNCHES]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShit]    Script Date: 03/25/2021 10:22:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermanentShit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RptPermanentShit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGrade]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertGrade]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertGrade]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLookupTable]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLookupTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertLookupTable]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDepartment]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDepartment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertDepartment]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_IgnoreDuplicatePunches]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_IgnoreDuplicatePunches]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_IgnoreDuplicatePunches]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_AddlWeekOffDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_AddlWeekOffDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_AddlWeekOffDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TitleFirstDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TitleFirstDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_TitleFirstDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveMasterDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveMasterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_LeaveMasterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationVehicleDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TransportationVehicleDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_TransportationVehicleDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_RouteDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation_RouteDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Insert_Transportation_RouteDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationChild]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAllocationChild]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAllocationChild]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationMaster]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAllocationMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertAllocationMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertChildrendetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertChildrendetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertChildrendetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompanyDetails]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertCompanyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertCompanyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSpousedetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSpousedetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertSpousedetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftPattern]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftRoaster]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftRoaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertShiftRoaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateMusterRoll]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertUpdateMusterRoll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_InsertUpdateMusterRoll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUser]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_LogoutUser]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NonProcessedDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_NonProcessedDataDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_NonProcessedDataDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEditUpdated]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OrgEditUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_OrgEditUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId_Group]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftId_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftId_Group]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftAllocationDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftAllocationDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectShiftAllocationDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftForDate]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentShiftForDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftForDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLICPendingForwardedRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManual]    Script Date: 03/25/2021 10:22:13 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupManual]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupManual]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingSMSTemplateStaus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserAccessRights_MobileApp]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UserAccessRights_MobileApp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UserAccessRights_MobileApp]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftRoaster]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftRoaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftRoaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleFirst]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TitleFirst]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_TitleFirst]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_userRightsInsert]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_userRightsInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_userRightsInsert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateLeavePolicyByFilters]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateLeavePolicyByFilters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ValidateLeavePolicyByFilters]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTempShiftAlloc]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateTempShiftAlloc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateTempShiftAlloc]
GO
/****** Object:  StoredProcedure [dbo].[ReducePermissionHoursFromTotalHours]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReducePermissionHoursFromTotalHours]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReducePermissionHoursFromTotalHours]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationVehicle]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TransportationVehicle]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_TransportationVehicle]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation_Route]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_Transportation_Route]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Update_TA_TBL_Transportation_Route]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ViewLeavePolicyDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ViewLeavePolicyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ViewLeavePolicyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateFlagInDeviceDatabase]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplication]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplication]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateInAndOutPunchDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateInAndOutPunchDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateScheduleStatus]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateScheduleStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateScheduleStatus]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShift]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShift]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_UpdateShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateProcessedDataForService]    Script Date: 03/25/2021 10:22:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateProcessedDataForService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_UpdateProcessedDataForService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationView]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocationView]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftAllocationView]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTransportation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTransportation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTransportation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftForDate]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporaryShiftForDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftForDate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftId]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporaryShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftId]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTempPayrollDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTempPayrollDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTempPayrollDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDatatype]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDatatype]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_SelectTerminalDatatype]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAllocation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_ShiftReAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Route_Delete]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Route_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Transportation_Route_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Vehicle_Delete]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Vehicle_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Transportation_Vehicle_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LastLogout]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LastLogout]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_LastLogout]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveMasterDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LeaveMasterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_LeaveMasterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ReligionDetails]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_ReligionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_ReligionDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_ShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_Update_ShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountInterveningWeekOff]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCountInterveningWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetCountInterveningWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevelUpdated]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getMinimumLevelUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getMinimumLevelUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePolicyDetails]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeavePolicyDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetLeavePolicyDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeEmailIds]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeEmailIds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeEmailIds]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeWorkedDays]    Script Date: 03/25/2021 10:22:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeWorkedDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetEmployeeWorkedDays]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]    Script Date: 03/25/2021 10:22:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdForWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdForWeekOff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_GetShiftIdForWeekOff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNews]    Script Date: 03/25/2021 10:22:07 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getNews]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_getNews]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckProcName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcNameUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckProcNameUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Update]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckEntrance_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Updates]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Updates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGradeName_Updates]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Insert]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckGradeName_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveMaster_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveMaster_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Update]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveMaster_Update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckLeaveMaster_Update]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCode]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountryInsertUpdate]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCountryInsertUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckCountryInsertUpdate]
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_ProperCase]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_ProperCase]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Func_TA_ProperCase]
GO
/****** Object:  UserDefinedFunction [dbo].[ConvertHoursToMinites]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConvertHoursToMinites]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[ConvertHoursToMinites]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleNo]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleNo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicleNo]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Updates]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Updates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTitle_Updates]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_ForModification]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_ForModification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicle_ForModification]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Insert]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckVehicle_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTitle_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalDatatype]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalDatatype]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckTerminalDatatype]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortName]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftShortName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftShortName]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftShortNameUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftShortNameUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckStateCityInsertUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckStateCityInsertUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckStateCityInsertUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftExchangeEmployee]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftExchangeEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftExchangeEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPattern]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternDelete]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternDelete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftPatternDelete]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternNameUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckShiftPatternNameUpdate]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_ForModification]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_ForModification]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRoute_ForModification]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Insert]    Script Date: 03/25/2021 10:22:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckRoute_Insert]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveMaster]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteLeaveMaster]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteHoliday]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteHoliday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteHoliday]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGeoLocation]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteGeoLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteGeoLocation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteType]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoasterDetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftRoasterDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftRoasterDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftAll]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftAll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteShiftAll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthClosureDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteMonthClosureDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteMonthClosureDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentCategory]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermanentCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeletePermanentCategory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentType]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermanentType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeletePermanentType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreAddlWeekoff]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreEntranceDetails]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreEntranceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreEntranceDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreGrade]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreGrade]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreGrade]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLeavePolicy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeavePolicy]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeaveType]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLeaveType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeaveType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLookupdata]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLookupdata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreLookupdata]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreNews]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreNews]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreNews]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestorePunchTypes]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestorePunchTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestorePunchTypes]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreReligion]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreReligion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreReligion]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreShiftAll]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreShiftAll]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreShiftAll]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminal]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTerminal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminal]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTerminalDatatype]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTitle]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTitle]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreTitle]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreWeekday]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreWeekday]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteRestoreWeekday]
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDeviceTesting]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertIrisLogsFromDeviceTesting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InsertIrisLogsFromDeviceTesting]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpCategory]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_KeepNumInt]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_KeepNumInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_KeepNumInt]
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_RptEmployee]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_RptEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[TA_Proc_RptEmployee]
GO
/****** Object:  StoredProcedure [dbo].[Template_Delete]    Script Date: 03/25/2021 10:22:16 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Template_Delete]
GO
/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[Split]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryImport]    Script Date: 03/25/2021 10:22:09 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntryImport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryImport]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPayrollLeaveDetails]    Script Date: 03/25/2021 10:22:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPayrollLeaveDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_InsertPayrollLeaveDetails]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreCategory]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RestoreCategory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftPattern]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreShiftPattern]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RestoreShiftPattern]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreType]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RestoreType]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevel]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RPT_FilterLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RPT_FilterLevel]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevelUpdated]    Script Date: 03/25/2021 10:22:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RPT_FilterLevelUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_RPT_FilterLevelUpdated]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation]    Script Date: 03/25/2021 10:22:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpDesignation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_EmpDesignation]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAttandanceCode]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAttandanceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteAttandanceCode]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCategory]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCategory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteCategory]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCCGroup]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCCGroup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DeleteCCGroup]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateDifference]    Script Date: 03/25/2021 10:22:04 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateDifference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_DateDifference]
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysRestore]    Script Date: 03/25/2021 10:22:02 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysRestore]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Proc_TA_CheckHolidaysRestore]
GO
/****** Object:  UserDefinedFunction [dbo].[ConvertMinsToHours]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConvertMinsToHours]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[ConvertMinsToHours]
GO
/****** Object:  StoredProcedure [dbo].[CrossTab]    Script Date: 03/25/2021 10:22:01 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CrossTab]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CrossTab]
GO
/****** Object:  UserDefinedFunction [dbo].[CSVToTable]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CSVToTable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[CSVToTable]
GO
/****** Object:  UserDefinedFunction [dbo].[DateOnly]    Script Date: 03/25/2021 10:22:17 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DateOnly]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[DateOnly]
GO
/****** Object:  UserDefinedFunction [dbo].[DateOnly]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DateOnly]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE  function [dbo].[DateOnly](@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
    begin
    return dateadd(dd,0, datediff(dd,0,@DateTime))
    end
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[CSVToTable]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CSVToTable]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE(id int not null)
AS
BEGIN    
	SET @InStr = REPLACE(@InStr + '','', '',,'', '','')
	DECLARE @SP INT
	DECLARE @VALUE VARCHAR(1000)
	WHILE PATINDEX(''%,%'', @INSTR ) <> 0 
	BEGIN
	   SELECT  @SP = PATINDEX(''%,%'',@INSTR)
	   SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
	   SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '''')
	   INSERT INTO @TempTab(id) VALUES (@VALUE)
	END
	RETURN
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[CrossTab]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CrossTab]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROC [dbo].[CrossTab]
  @table       AS sysname,        -- Table to crosstab
  @onrows      AS nvarchar(128),  -- Grouping key values (on rows)
  @onrowsalias AS sysname = NULL, -- Alias for grouping column
  @oncols      AS nvarchar(128),  -- Destination columns (on columns)
  @avgcol      AS sysname = NULL  -- Data cells
AS
DECLARE
  @sql AS varchar(8000),
  @NEWLINE AS char(1)
SET @NEWLINE = CHAR(10)
-- step 1: beginning of SQL string
SET @sql =
  ''SELECT'' + @NEWLINE + 
  ''  '' + @onrows +
  CASE
    WHEN @onrowsalias IS NOT NULL THEN '' AS '' + @onrowsalias
    ELSE ''''
  END
CREATE TABLE #keys(keyvalue nvarchar(100) NOT NULL PRIMARY KEY)
DECLARE @keyssql AS varchar(1000)
SET @keyssql = 
  ''INSERT INTO #keys '' +
  ''SELECT DISTINCT CAST('' + @oncols + '' AS nvarchar(100)) '' +
  ''FROM '' + @table
EXEC (@keyssql)
DECLARE @key AS nvarchar(100)
SELECT @key = MIN(keyvalue) FROM #keys
WHILE @key IS NOT NULL
BEGIN
  SET @sql = @sql + '',''                   + @NEWLINE +
    ''  AVG(CASE CAST('' + @oncols +
                     '' AS nvarchar(100))'' + @NEWLINE +
    ''        WHEN N'''''' + @key +
           '''''' THEN '' + CASE
                          WHEN @avgcol IS NULL THEN ''1''
                          ELSE @avgcol
                        END + @NEWLINE +
    ''        ELSE 0''                      + @NEWLINE +
    ''      END) AS AvgRespons'' 
  SELECT @key = MIN(keyvalue) FROM #keys
  WHERE keyvalue > @key
END
SET @sql = @sql         + @NEWLINE +
  ''FROM '' + @table      + @NEWLINE +
  ''WHERE NOT '' + @avgcol + '' = -1 '' +@NEWLINE +
  ''AND NOT '' + @onrows + ''= 1'' +@NEWLINE +
  ''GROUP BY '' + @onrows + @NEWLINE +
  ''ORDER BY '' + @onrows
EXEC (@sql)
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[ConvertMinsToHours]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConvertMinsToHours]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
--select dbo.ConvertMinsToHours(100)
-- =============================================
CREATE FUNCTION [dbo].[ConvertMinsToHours]
(
	@Mins int
)
RETURNS varchar(10)
AS
BEGIN
	Declare @Converted varchar(10)
	SELECT	@Converted=CASE WHEN @Mins!=0 THEN
			CASE	WHEN LEN(@Mins/60)=1 THEN ''0''+(CONVERT(VARCHAR(10),CONVERT(INT,(@Mins/60))))
					ELSE (CONVERT(VARCHAR(10),CONVERT(INT,(@Mins/60))))
			END 
			+'':''+
			CASE	WHEN LEN(@Mins%60)=1 then ''0''+CONVERT(varchar(10),convert(int,(@Mins%60)))
					ELSE CONVERT(VARCHAR(10),CONVERT(INT,(@Mins%60)))
			END
			else ''00:00''
		END
		
	RETURN @Converted
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysRestore]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysRestore]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	:	Proc_TA_CheckHolidaysRestore  
Description 	:	check holidays Duplicate while Restore Proc_TA_CheckHolidaysRestore ''136'',''Global Holiday'',''09/25/2008'',''10/01/2008'',''f''
Tables Included :	TA_Tbl_Holiday  
Created By 	:	Janakaraj.P 
Created On 	:	20-Aug-2007
Modified By 	:	Prabakaran.P  
Modified On 	:  	08-Feb-08
*/  
CREATE     PROCEDURE [dbo].[Proc_TA_CheckHolidaysRestore]      
(    
	@HolidayId int,    
	@HolidayType nvarchar(30),    
	@HolidayFdate datetime,  
	@HolidayTodate datetime,   
	@HolidayDescription nvarchar(50))      
AS      
BEGIN 
	Declare @Sql as varchar(2000)
	set @Sql=''''
	set @Sql=''SELECT COUNT(Holiday_Id) as HCount FROM TA_Tbl_Holiday where((((Holiday_FromDate between '''''' + cast(@HolidayFdate as varchar(20)) + '''''' and  '''''' + cast(@HolidayTodate as varchar(20)) + '''''') or (Holiday_ToDate between '''''' + cast(@HolidayTodate as varchar(20)) + '''''' and '''''' + cast(@HolidayTodate as varchar(20)) + '''''')) and Holiday_Id<>'''''' + cast(@HolidayId as varchar(100)) + '''''') or ((Holiday_Description=N'''''' +  @HolidayDescription + '''''' and Holiday_Id<>'''''' + cast(@HolidayId as varchar(100)) + ''''''))) and Isdeleted=0''
	EXEC(@Sql)
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateDifference]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateDifference]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DateDifference  
Description : Proc to find the months diffrences between from and to date.
Tables Included : Nil  
Created By : Abul  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Proc [dbo].[Proc_TA_DateDifference]
@FromDate datetime,
@ToDate datetime
As
select datediff(mm, @FromDate, @ToDate)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCCGroup]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCCGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Deletes the existing CC groups.
-- Modified by Gopinath on 14thJun14 for adding OD approval mailing group
-- =============================================
--Proc_TA_DeleteCCGroup ''4'',''A''
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCCGroup] 
(
  @CCGroupID varchar(8000),
  @Parameter varchar(5)
)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Script varchar(8000)
	set @Script=''''
	  if(@Parameter=''A'')
		  BEGIN
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_Planned where CCGroupID in (''+@CCGroupID+'')''
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_UnPlanned where CCGroupID in (''+@CCGroupID+'')''
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_Others where CCGroupID in (''+@CCGroupID+'')''
		     set @Script = @Script + ''Delete from TA_tbl_CcMailGroup where CCGroupID in (''+@CCGroupID+'')''
			 set @Script = @Script + ''Delete from TA_Tbl_CCGroup_ODApproval where CCGroupID in (''+@CCGroupID+'')''
		  END
	  else if(@Parameter=''P'')
		  BEGIN
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_Planned where CCGroupID in (''+@CCGroupID+'')''
		  END
	  else if(@Parameter = ''U'')
		  BEGIN
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_UnPlanned where CCGroupID in (''+@CCGroupID+'')''
		  END
      else if(@Parameter = ''O'')
		  BEGIN
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_Others where CCGroupID in (''+@CCGroupID+'')''
		  END
	   else if(@Parameter = ''OD'')
		  BEGIN
		     set @Script = @Script + ''Delete from TA_Tbl_CCGroup_ODApproval where CCGroupID in (''+@CCGroupID+'')''
		  END
		  exec(@Script)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCategory]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Category set IsDeleted=1,EmpId=''+cast(@EmpID as nvarchar(20))+'' where CategoryId IN (''+ @CategoryID +'')''
	Execute(@Query)
	--update TA_Tbl_Category set IsDeleted=1,EmpId = @EmpID where CategoryId=@CategoryID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAttandanceCode]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_DeleteAttandanceCode ''3,7'',1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAttandanceCode]
	@AttandanceID as varchar(2000),	
	@EmpID as int
AS
BEGIN
	--update  TA_Tbl_AttandanceCode set IsDeleted=1,EmpID=@EmpID where AttandanceID=@AttandanceID
	declare @Query varchar(2000)
	set @Query=''''
	set @Query = @Query + ''update  TA_Tbl_AttandanceCode set IsDeleted=1,EmpID='' + cast(@EmpID as varchar(10)) + '' where AttandanceID in ('' +@AttandanceID + '')''
	exec (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpDesignation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_EmpDesignation]''2014-11-23'',''100,105,'',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpDesignation]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@DesignationId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql=''	select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
				select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
				inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 ''
	if (@Employee_Code_Id<>'''')
	begin
		if(@DesignationId<>0 and @DesignationId!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and ED.DesignationId=''+convert(varchar(20),@DesignationId)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	end
	else 
		if(@DesignationId<>0 and @DesignationId!='''')
			BEGIN					
				Set @sql=@sql+'' and ED.DesignationId=''+convert(varchar(20),@DesignationId)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	Set @sql=@sql + '' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and ED.DesignationId is not null ''	
	execute(@sql)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevelUpdated]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RPT_FilterLevelUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_RPT_FilterLevelUpdated]  
(  
	@lid varchar(1000)  ,
	@TotLevels varchar(5000)
)  
AS  
BEGIN  
	declare @qry as varchar(7000)  
	set @qry = (''select id from ta_tbl_leveldetails where isdeleted=0 and parentid in ('' + @lid + '') and id in (''+ @TotLevels + '') '')  
	exec (@qry)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RPT_FilterLevel]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RPT_FilterLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RPT_FilterLevel]  
(  
  @lid varchar(1000)  
)  
AS  
BEGIN  
declare @qry as varchar(7000)  
set @qry = (''select id from ta_tbl_leveldetails where isdeleted=0 and parentid in ('' + @lid + '')'')  
exec (@qry)  
/*  
 DECLARE @lelid int, @lelName varchar(30)  
 SET @lelName = (SELECT min(id) FROM ta_tbl_leveldetails WHERE isdeleted=0 and parentid = @lid)  
 --INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES (@lid,@lelName)  
 SET @lelid = (SELECT min(ID) FROM ta_tbl_leveldetails WHERE isdeleted=0 and parentid = @lid)  
 if (@lelid <8)  
 BEGIN  
  EXEC dbo.proc_ta_rpt_filterlevel @lelid  
 END    
*/  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreType]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Type set IsDeleted=0,EmpId=''+cast(@EmpID as nvarchar(20))+'' where TypeId IN (''+ @TypeID +'')''
	Execute(@Query)
	--update TA_Tbl_Type set IsDeleted=0,EmpId = @EmpID where TypeId=@TypeID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftPattern]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by	:	P.Prabakaran
Created on	:	05-Feb_08
Description	:	Restore Shift Pattern Based on their Id''s
*/
CREATE PROCEDURE [dbo].[Proc_TA_RestoreShiftPattern] 
@ShiftPatternIds varchar(1000)
as
DECLARE @restore NVARCHAR
SET @restore=0
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_ShiftPattern SET IsDeleted= '' + @restore + '' WHERE ShiftPattern_Id IN (''+ @ShiftPatternIds +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreCategory]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Category set IsDeleted=0,EmpId=''+cast(@EmpID as nvarchar(20))+'' where CategoryId IN (''+ @CategoryID +'')''
	Execute(@Query)
	--update TA_Tbl_Category set IsDeleted=0,EmpId = @EmpID where CategoryId=@CategoryID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPayrollLeaveDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPayrollLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_InsertPayrollLeaveDetails]
(
   @MonthCloseId int,
   @LeaveType Varchar(25),
   @EmployeeId NVarchar(20)
)
AS
begin
	SET NOCOUNT ON;
	Declare @query as Varchar(3000)
	Declare @query1 as Varchar(3000)
	Declare @query2 as Varchar(3000)
	Declare @query3 as Varchar(3000)
	Declare @LeaveType_Id as Varchar(25)
	Declare @MonthClosureId as int
	create table #Temp(LeaveType_Id int)
	create table #Temp1(MonthClosure_Id int)
	set @query = ''select LeaveType_Id from TA_Tbl_LeaveType where LeaveType = '''''' + @LeaveType + ''''''''
	insert into #Temp EXEC(@query)
	set @LeaveType_Id=(select * from #Temp)
	set @query1 = ''select MonthClosure_Id from TA_Tbl_PayrollProcessLeaveDetails where MonthClosure_Id = '' + Cast(@MonthCloseId as Varchar) + '' and Employee_Id = '' + @EmployeeId + '' and LeaveType_id = '' + Cast(@LeaveType_Id as Varchar)
	insert into #Temp1 EXEC(@query1)
	set @MonthClosureId = (select * from #Temp1)
	set @MonthClosureId = isnull(@MonthClosureId,-1)
	if(@MonthClosureId = -1)
	begin
	   set @query2 = ''insert into TA_Tbl_PayrollProcessLeaveDetails(MonthClosure_Id,Employee_Id,LeaveType_id,Leave_Count)VALUES('' + Cast(@MonthCloseId as Varchar) + '', '' + @EmployeeId + '','' + Cast(@LeaveType_Id as Varchar) +'',1)''
	   EXEC(@query2)
	end
	else if(@MonthClosureId > 0)
	begin
	   set @query3 =  ''UPDATE TA_Tbl_PayrollProcessLeaveDetails SET Leave_Count = Leave_Count + 1 WHERE MonthClosure_Id = '' + Cast(@MonthCloseId as Varchar) + ''and LeaveType_id = '' + Cast(@LeaveType_Id as Varchar) + '' and Employee_Id = '' + @EmployeeId + '' ''
	   EXEC(@query3)
	end
	drop table #Temp
	drop table #Temp1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryImport]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntryImport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : Gopinath.K  
--  Created On         : 26-Aug-14  
--  Description         : This Procedure is used to insert the Manual Time Entry by import functionality 
-- ================================================================================  
CREATE  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryImport]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),  
	@ManualEntry_Date DATETIME,  
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImport INT
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0  
	DECLARE @sql nvarchar(4000)
	SET @sql = ''''    
	IF(@InDate = '' '')  
	   BEGIN  
		 SET @sql = ''''
		 SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)''
		 SET @sql = @sql + '' VALUES('''''' + @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @OutDate + '''''',N'''''' + @OutTime + '''''',N'''''' +@OutPunchType + '''''','''''' + cast(@OutReader_Id as nvarchar(10)) +  '''''',N'''''' 
		 SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(@TimeStamp as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''' ,'''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@IsImport as nvarchar(10)) + '''''')'' 
	   END  
	ELSE IF(@OutDate = '' '')  
	  BEGIN  
		SET @sql = ''''
		SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)''
		SET @sql = @sql + '' VALUES(''''''+ @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @InDate + '''''',N'''''' + @InTime + '''''',N'''''' + @InPunchType + '''''','''''' + cast(@InReader_Id as nvarchar(10)) +  '''''',N'''''' 
		SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(@TimeStamp as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''','''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@IsImport as nvarchar(10)) + '''''')''   
	  END  
	ELSE
	  BEGIN
		SET @sql = ''''
		SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)''
		SET @sql = @sql + '' VALUES(''''''+ @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @InDate + '''''',N'''''' + @InTime + '''''',N'''''' + @InPunchType + '''''',N'''''' + @OutDate + '''''',N'''''' + @OutTime + '''''',N'''''' +@OutPunchType + '''''','''''' + cast(@InReader_Id as nvarchar(10)) +  '''''','''''' + cast(@OutReader_Id as nvarchar(10)) +  '''''',N'''''' 
		SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(@TimeStamp as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''','''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@IsImport as nvarchar(10)) + '''''')''   
	  END
	EXEC (@sql)
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Split]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[Split](
 @String nvarchar (max),
 @Delimiter nvarchar (10)
 )
returns @ValueTable table (Id int identity, [Value] nvarchar(4000))
begin
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @CommaCheck nvarchar(1)
 --Initialize
 set @NextString = ''''
 set @CommaCheck = right(@String,1) 
 --Check for trailing Comma, if not exists, INSERT
 --if (@CommaCheck <> @Delimiter )
 set @String = @String + @Delimiter
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0)  
 begin
  set @NextString = substring(@String,1,@Pos - 1)
  insert into @ValueTable ( [Value]) Values (@NextString)
  set @String = substring(@String,@pos +1,len(@String))
  set @NextPos = @Pos
  set @pos  = charindex(@Delimiter,@String)
 end
 return
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Template_Delete]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Template_Delete]
AS
BEGIN
--DELETE FROM TBL_TEMPLATEMASTER
RETURN (@@ROWCOUNT)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_RptEmployee]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_RptEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- Create date: 04August08
-- Description:	Report Employee Details
-- =============================================
CREATE  PROCEDURE [dbo].[TA_Proc_RptEmployee]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(18) 
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery = @sqlQuery + '' ,Employee_firstName + Space(1) + Employee_LastName as empname,dbo.TA_Tbl_Employee.DateofBirth,dbo.TA_Tbl_Employee.Nationality,''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title.TitleName,dbo.Ta_Tbl_levelDetails.name''		
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_Employee INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 1)''
		set @sqlQuery = @sqlQuery + '' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
		set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		if not(@EmployeeName='''' or @EmployeeName=''0'')
		begin
			set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		end
		if not (@empId='''' or @empId=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and ta_tbl_processedData.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
		if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.LevelId = '' + cast (@LevelId as nvarchar(50)) 
		end			
		exec(@sqlQuery)
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_KeepNumInt]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_KeepNumInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE function [dbo].[fn_KeepNumInt](@mixedNumStr varchar(15)) 
returns int as
begin
        BEGIN 
WHILE PATINDEX(''%[^0-9]%'',@mixedNumStr)> 0 
SET @mixedNumStr = REPLACE(@mixedNumStr,SUBSTRING(@mixedNumStr,PATINDEX(''%[^0-9]%'',@mixedNumStr),1),'''') 
END 
        return CAST(@mixedNumStr as int)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_EmpCategory]''2014-09-11'',''787,788,789,8,888'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpCategory]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeCategory int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here		
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql=''
		select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 ''
	if (@Employee_Code_Id<>'''')
		if(@employeeCategory<>0 and @employeeCategory!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and ec.CategoryId=''+convert(varchar(20),@employeeCategory)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	else 
		if(@employeeCategory<>0 and @employeeCategory!='''')
			BEGIN					
				Set @sql=@sql+'' and ec.CategoryId=''+convert(varchar(20),@employeeCategory)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	Set @sql=@sql+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and ECategory.CategoryId is not null ''	
	execute(@sql)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]''2014-09-11'',''787,788,789,8,888'',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpType]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeType int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	Declare @sql varchar(max)
	Set @sql=''
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 ''
	if (@Employee_Code_Id<>'''')
		if(@employeeType<>0 and @employeeType!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and et.TypeId=''+CONVERT(varchar(20),@employeeType)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	else 
		if(@employeeType<>0 and @employeeType!='''')
			BEGIN					
				Set @sql=@sql+'' and et.TypeId=''+CONVERT(varchar(20),@employeeType)
			End
		else
			Begin				
				Set @sql=@sql 
			end				
	Set @sql=@sql+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102)  and EType.TypeId is not null''	
	execute(@sql)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDeviceTesting]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertIrisLogsFromDeviceTesting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[InsertIrisLogsFromDeviceTesting]
	@LogData XML = NULL
AS
BEGIN
	SET NOCOUNT ON;
	Declare @local_LogData XML = @LogData
	DECLARE @XMLParams INT
	
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LogData	
			
			SELECT	AdditionalData,
					EventType,
					Info,
					LogUID,
					SubjectUID,
					Timestamp
					FROM OPENXML (@XMLParams, ''/DocumentElement/IrisLog_Table'', 2) WITH 
					(
						AdditionalData varchar(max),
						EventType  varchar(max),
						Info varchar(max),
						LogUID int,
						SubjectUID varchar(max),
						Timestamp datetime
					) Tbl			where SubjectUID is not null and AdditionalData=''Allowed''
			
		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreWeekday]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreWeekday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_DeleteRestoreWeekday 
Description : delete the weekday 
Tables Included : TA_Tbl_TemWeekday  
Created By : Christopher S   
Created On : 07-Feb-2008
Modified By :  Manikandan.R
Modified On :  14-Mar-2012
*/  
--[Proc_TA_DeleteRestoreWeekday] ''TemporaryDelete'',6,1
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteRestoreWeekday] 
(
	@type nvarchar(20),
    @WeedayId varchar(100),
	@auditEmpId int	
)	
AS
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	BEGIN
		SET NOCOUNT ON;
		if(@type=''PermanentDelete'')  --permanently delete temporary week day
			begin		 		
				SET @Query= ''UPDATE TA_Tbl_TemWeekday SET Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TempWeekday_Id  IN ('' + @WeedayId + '')''
				EXEC (@Query) 		
				SET @Query=''''		
				set @Query=''Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in ('' + @WeedayId + ''))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate''
				EXEC (@Query) 
				SET @Query=''''
				SET @Query= ''DELETE FROM Ta_Tbl_Temp_WeeklyOff_Levels WHERE TempWeekday_Id  in ('' + @WeedayId + '')''
				EXEC (@Query) 
				SET @Query=''''
				SET @Query= ''DELETE FROM Ta_Tbl_Temporary_WeeklyOff_Levels WHERE TempWeekday_Id  in ('' + @WeedayId + '')''
				EXEC (@Query) 
				SET @Query=''''
				SET @Query=''DELETE FROM TA_Tbl_TemWeekday WHERE TempWeekday_Id  in ('' + @WeedayId + '')''
				EXEC (@Query) 
			end
		else if(@type=''TemporaryDelete'')  --inactivate the temporary week day
			begin
				SET @Query= ''UPDATE TA_Tbl_TemWeekday SET IsDeleted = 1, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TempWeekday_Id  IN ('' + @WeedayId + '')''
				EXEC (@Query)
				set @Query=''''			
				set @Query=''Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in ('' + @WeedayId + ''))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate''				 
				EXEC (@Query)
			end
		else if(@type=''Restore'')    -- restore the temporary week day
			begin
				SET @Query= ''UPDATE TA_Tbl_TemWeekday SET IsDeleted = 0, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TempWeekday_Id  IN ('' + @WeedayId + '')''
				EXEC (@Query)	    
				set @Query=''''
				set @Query=''Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
				 select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
				 inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
				 INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId  	
				 inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id WHERE WL.TempWeekday_Id in ('' + @WeedayId + ''))as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
				 and TemEmployee.TempWeekday_ToDate''
				EXEC (@Query) 
			end     
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTitle]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTitle]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Modified By : Kumuthini.L
-- Modified On : 8-Feb-08
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteRestoreTitle]
(
	@Type CHAR(25),
	@TitleIds NVARCHAR(100),
	@auditEmpId int
)
AS	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''TemporaryDelete'') -- In Activating the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Title SET IsDeleted = 1, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TitleId IN  ('' + @TitleIds + '')''
		EXEC (@Query)
	END
IF (@Type=''PermanentDelete'')-- Permanently Deleting the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Title SET Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TitleId IN  ('' + @TitleIds + '')''
		EXEC (@Query)
		SET @Query = ''DELETE FROM TA_Tbl_Title WHERE TitleId IN  ('' + @TitleIds + '')''
		EXEC (@Query)
	END
IF (@Type=''Restore'')-- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Title SET IsDeleted = 0, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE TitleId IN  ('' + @TitleIds + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTerminalDatatype]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminalDatatype]
(
	@Type CHAR(20),
	@TerminalDataTypes NVARCHAR(max),
	@auditEmpId int
)
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF (@Type=''TemporaryDelete'')
		BEGIN
			SET @Query= ''UPDATE TA_tbl_TerminalDatatype SET IsDeleted = 1, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))
		END
	ELSE IF (@Type=''PermanentDelete'')
		BEGIN		
			SET @Query= ''DELETE FROM TA_tbl_TerminalDatatype''
		END
	ELSE IF (@Type=''Restore'')
		BEGIN
			SET @Query= ''UPDATE TA_tbl_TerminalDatatype SET IsDeleted = 0, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))
		END
	EXEC (@Query+'' WHERE TerminalDatatype_ID IN ('' + @TerminalDataTypes + '')'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreTerminal]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreTerminal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Procedure Name - Proc_TA_DeleteRestoreTerminal
-- Tables Used - TA_Tbl_Terminal
-- Modified By -  Kumuthini.L
-- Modified On - 07-Feb-2008
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreTerminal]
(
	@Type CHAR(25),
	@Terminals NVARCHAR(500),
	@auditEmpId int	
)
AS	
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @Query= ''UPDATE TA_Tbl_Terminal SET IsDeleted = 1, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))
	END
	IF (@Type=''PermanentDelete'')
	BEGIN		
		SET @Query= ''DELETE FROM TA_Tbl_Terminal ''
	END
	IF (@Type=''Restore'')
	BEGIN
		SET @Query= ''UPDATE TA_Tbl_Terminal SET IsDeleted = 0, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))
	END
	EXEC (@Query +'' WHERE Terminal_Id IN ('' + @Terminals + '')'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreShiftAll]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreShiftAll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
For Temporary Deleting or Permanent Delete or Restoring multiple shifts 
Modified by	:	P.Prabakaran
Modified on	:	05-Feb_08
Description	:	@del default value modified from 0 to 1
Option Given for Permanent Delete , Temporary Delete and Restore Records
*/
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreShiftAll] 
(
	@ShiftIds varchar(200),
	@DeleteRestoreOption nvarchar(50),
	@auditEmpId int
)
as
	DECLARE @del NVARCHAR
	DECLARE @restore NVARCHAR
	SET @del=1
	SET @restore=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
if(@DeleteRestoreOption=''TemporaryDelete'') -- In Activating the Single or Multiple Records
	BEGIN
		/*UPDATE TA_Tbl_Shift SET Isdeleted=0 WHERE Shift_Id=@ShiftId*/
		SET @Query = ''UPDATE TA_Tbl_Shift SET IsDeleted= '' + @del + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Shift_Id IN (''+ @ShiftIds +'')''
		EXEC (@Query)
	END
else if(@DeleteRestoreOption=''PermanentDelete'')-- Permanently Deleting the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Shift SET  Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Shift_Id IN (''+ @ShiftIds +'')''
		EXEC (@Query)
		SET @Query = ''''
		SET @Query = ''DELETE FROM TA_Tbl_Shift WHERE Shift_Id IN (''+ @ShiftIds +'')''
		EXEC (@Query)
	END
else if(@DeleteRestoreOption=''Restore'')-- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Shift SET IsDeleted= '' + @restore + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Shift_Id IN (''+ @ShiftIds +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreReligion]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreReligion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreReligion] 
(     
	@Type CHAR(25),		
	@ID NVARCHAR(500),
	@auditEmpId int
)
AS	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''TemporaryDelete'') -- In Activating the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Religion SET IsDeleted = 1 WHERE ID IN (''+ cast(@ID as nvarchar(500)) +'')''
        EXEC (@Query)
	END
ELSE IF (@Type=''PermanentDelete'') -- Permanently Deleting the Single or Multiple Records
	BEGIN
		--SET @Query = ''UPDATE TA_Tbl_Religion SET SET 1=1 WHERE ID IN (''+ @ID +'')''
        --EXEC (@Query)
		SET @Query =''''
		SET @Query = ''DELETE FROM TA_Tbl_Religion WHERE ID IN (''+ @ID +'')''
        EXEC (@Query)
	END
ELSE IF (@Type=''Restore'') -- Restoring the Single or Multiple Records
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Religion SET IsDeleted = 0 WHERE ID IN (''+ @ID +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestorePunchTypes]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestorePunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestorePunchTypes]
	@Type CHAR(25),
	@PunchType_Ids NVARCHAR(500),
	@auditEmpId int
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_PunchTypes SET IsDeleted=1, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))
	END
	ELSE IF (@Type=''PermanentDelete'')
	BEGIN
		SET @Query = ''DELETE FROM TA_Tbl_PunchTypes ''			
	END
	ELSE IF (@Type=''Restore'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_PunchTypes SET IsDeleted=0, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))
	END
	EXEC (@Query+'' WHERE PunchType_Id IN  ('' + @PunchType_Ids + '')'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreNews]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreNews]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Christopher S
-- ALTER  date: 07-Feb-08
-- Description:	Delete & Restore News/Events
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreNews]
(
	@type NVARCHAR(20),
    @newsId varchar(1000),
	@empId int
)
AS
declare @SQLQuery varchar(2000)
set @SQLQuery = ''''
if(@type=''PermanentDelete'')
	BEGIN
		set @SQLQuery = @SQLQuery + ''update ta_tbl_newsEvents set emp_Id= '' + cast(@empId as varchar(20)) + '' where NewsEvent_Id in ('' + cast(@newsId as varchar(1000)) +'')''
		set @SQLQuery = @SQLQuery + ''delete ta_tbl_newsEvents where NewsEvent_Id in ('' + cast(@newsId as varchar(1000)) + '')''
		exec (@SQLQuery)
	END
else if(@type=''TemporaryDelete'')
	BEGIN
		set @SQLQuery = @SQLQuery + ''update ta_tbl_newsEvents set isDeleted=1,timeStamp=getDate(),emp_Id='' + cast(@empId as varchar(20)) + ''where NewsEvent_Id in ( '' + cast(@newsId as varchar(1000)) + '')''
		exec (@SQLQuery)
	END
else if(@type=''Restore'')
	BEGIN
		set @SQLQuery = @SQLQuery + ''update ta_tbl_newsEvents set isDeleted=0,timeStamp=getDate(),emp_Id= '' + cast(@empId as varchar(20)) + '' where NewsEvent_Id in ( '' + cast(@newsId as varchar(1000)) + '')''
		exec (@SQLQuery)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLookupdata]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLookupdata]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_DeleteRestoreLookupdata]
(
	@Type nvarchar (20),		
	@Ids NVARCHAR(25),
	@auditEmpId int
)
AS
	DECLARE @del NVARCHAR
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''PermanentDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Lookup SET Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE ID IN (''+ @Ids +'')''
		EXEC (@Query)
		SET @Query = ''DELETE FROM TA_Tbl_Lookup WHERE ID IN (''+@Ids+'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @del=1
		SET @Query = ''UPDATE TA_Tbl_Lookup SET IsDeleted= '' + @del + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE ID IN (''+ @Ids +'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''Restore'')
	BEGIN
		SET @del=0
		SET @Query = ''UPDATE TA_Tbl_Lookup SET IsDeleted= '' + @del + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE ID IN (''+ @Ids +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeaveType]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Procedure Name - Proc_TA_DeleteRestoreLeaveType
-- Tables Used - TA_Tbl_LeaveType
-- Created By -  Kumuthini.L
-- Created On - 05-Feb-2008
-- Proc_TA_DeleteRestoreLeaveType ''PermanentDelete'',''5,8,6'',1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeaveType]   
(     
	@Type CHAR(25),
	@Leaves NVARCHAR(500),
	@auditEmpId int
)
AS	
begin
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_LeaveType SET IsDeleted = 1, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE LeaveType_Id IN (''+ @Leaves +'')''
        EXEC (@Query)
	END
ELSE IF (@Type=''PermanentDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_LeaveType SET Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE LeaveType_Id IN (''+ @Leaves +'')''
        EXEC (@Query)
		SET @Query =''''
		SET @Query = ''DELETE FROM TA_Tbl_YearClosure WHERE LeaveTypeID IN (''+ @Leaves +'')''
		EXEC (@Query)
		SET @Query =''''
		SET @Query = ''DELETE FROM TA_Tbl_LeaveType WHERE LeaveType_Id IN (''+ @Leaves +'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''Restore'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_LeaveType SET IsDeleted = 0, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE LeaveType_Id IN (''+ @Leaves +'')''
        EXEC (@Query)
	END
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =======================================================
-- Procedure Name : Proc_TA_DeleteRestoreLeavePolicy
-- Tables Used : TA_Tbl_LeavePolicy,TA_Tbl_LeavePolicyDetails
-- Author:   Arun vinoth
-- ALTER  date : 28 June 2007
-- Last Modified By: Kumuthini.L
-- Last Modified On: 07-Feb-2008
-- Description:	Leave Policy - Delete
-- =======================================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreLeavePolicy]
	@Type CHAR(25),		
	@LeavePolicies NVARCHAR(500),
	@auditEmpId int	
AS
begin
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	DECLARE @Query1 NVARCHAR(2000)
	SET @Query=''''
	SET @Query1=''''
	IF (@Type=''TemporaryDelete'') -- In Activating the Records
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_LeavePolicyDetails SET Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
			SET @Query = ''''
			SET @Query = ''UPDATE TA_Tbl_LeavePolicy SET IsDeleted= 1, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
		END
	ELSE IF (@Type=''PermanentDelete'') -- Permanently Deleting the Records
		BEGIN			
			SET @Query1 = ''''
			SET @Query1 = ''DELETE FROM TA_Tbl_LeavePolicyDetails WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query1)
			SET @Query = ''''
			SET @Query = ''DELETE FROM TA_Tbl_LeavePolicy WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
		END
	ELSE IF (@Type=''Restore'')  -- Restoring the Records
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_LeavePolicyDetails SET Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
			SET @Query = ''''
			SET @Query = ''UPDATE TA_Tbl_LeavePolicy SET IsDeleted = 0, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
		END
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreGrade]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreGrade]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_DeleteRestoreGrade ''TemporaryDelete'',''15,16,17''
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteRestoreGrade]
		@Type NVARCHAR(20),		
		@GradeIds NVARCHAR(50),
		@auditEmpId int
	AS
	DECLARE @DEL VARCHAR
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''PermanentDelete'')
	BEGIN	
		SET @Query =''DELETE FROM TA_Tbl_Grade WHERE Grade_Id IN (''+@GradeIds+'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @DEL=1
		SET @Query = ''UPDATE TA_Tbl_Grade SET IsDeleted='' + @DEL + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Grade_Id IN  ('' + @GradeIds + '')''
		EXEC (@Query)
	END
ELSE IF (@Type=''Restore'')
	BEGIN
		SET @DEL=0
		SET @Query = ''UPDATE TA_Tbl_Grade SET IsDeleted='' + @DEL + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Grade_Id IN  ('' + @GradeIds + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreEntranceDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreEntranceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteRestoreEntranceDetails]
(
	@Type CHAR(25),		
	@Entrances NVARCHAR(500),
	@auditEmpId int
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Entrance SET IsDeleted = 1, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Entrance_Id IN (''+ @Entrances +'')''
	END
	ELSE IF (@Type=''PermanentDelete'')
	BEGIN				
		SET @Query = ''DELETE FROM TA_Tbl_Entrance_INOUTDetails WHERE Entrance_Id IN (''+ @Entrances +'');''		
		SET @Query = @Query +'' DELETE FROM TA_Tbl_Entrance WHERE Entrance_Id IN (''+ @Entrances +'')''		
	END
	ELSE IF (@Type=''Restore'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Entrance SET IsDeleted = 0, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Entrance_Id IN (''+ @Entrances +'')''
	END	
	EXEC (@Query)	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteRestoreAddlWeekoff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DeleteRestoreAddlWeekoff  
Description : delete and restore additional week off 
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Christopher S
Created On : 08-Feb-2008 
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteRestoreAddlWeekoff]
(
	@type nvarchar(20),
	@WeedayId varchar(100),
	@auditEmpId int
)
AS
        DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF(@type=''PermanentDelete'')
		BEGIN
			SET @Query=''UPDATE TA_Tbl_Additional_WeeklyOff SET Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE 
			Addl_WeeklyOff_Id in ('' + @WeedayId + '')''   
			EXEC (@Query)
			SET @Query=''''
			set  @Query=''delete from TA_Tbl_Additional_WeeklyOff_Levels where Addl_WeeklyOff_Id in(''+ @WeedayId +'')''
			SET @Query= @Query +''DELETE FROM TA_Tbl_Additional_WeeklyOff  WHERE Addl_WeeklyOff_Id IN (''+@WeedayId+'')''
            EXEC (@Query) 
		END
	ELSE IF(@type=''TemporaryDelete'')
		BEGIN
			SET @Query=''UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=1, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' 
			WHERE Addl_WeeklyOff_Id in ('' + @WeedayId + '')''   
			EXEC (@Query) 
		END
	ELSE IF(@type=''Restore'')
		BEGIN
			SET @Query=''UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=0, Emp_Id = ''+cast(@auditEmpId as nvarchar(20))+'' 
			WHERE Addl_WeeklyOff_Id in ('' + @WeedayId + '')''   
			EXEC (@Query) 
		END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentType]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermanentType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeletePermanentType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Type set EmpId=''+cast(@EmpID as nvarchar(20))+'' where TypeId IN (''+ @TypeID +'')''
	EXEC (@Query)
	--update TA_Tbl_Type set EmpId = @EmpID where TypeId=@TypeID	
	SET @Query = ''Delete from TA_Tbl_Type where TypeId IN (''+ @TypeID +'')''
	EXEC (@Query)
	--Delete from ta_tbl_type where TypeID=@TypeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermanentCategory]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermanentCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeletePermanentCategory]
	@CategoryID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Category set EmpId=''+cast(@EmpID as nvarchar(20))+'' where CategoryId IN (''+ @CategoryID +'')''
	Execute(@Query)
	--update TA_Tbl_Category set EmpId = @EmpID where CategoryId=@CategoryID
	--Delete from Ta_tbl_Category where CategoryId=@CategoryID
	SET @Query = ''Delete from Ta_tbl_Category where CategoryId IN (''+ @CategoryID +'')''
	Execute(@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthClosureDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteMonthClosureDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created By 	:	Prabakaran.P
Created On	:	4-Mar-09
--Proc_TA_DeleteMonthClosureDetails [51,59],1
*/
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteMonthClosureDetails]
(
@MonthCloseID varchar(8000),
@EmpAutoId int
)
AS
BEGIN
DECLARE @SqlQuery1 as varchar(8000)
DECLARE @SqlQuery2 as varchar(8000)
DECLARE @SqlQuery3 as varchar(8000)
DECLARE @SqlQuery4 as varchar(8000)
set @SqlQuery1=''''
set @SqlQuery2=''''
set @SqlQuery3=''''
set @SqlQuery4=''''
set @SqlQuery1=''UPDATE TA_Tbl_MonthClosure SET Emp_Id = ''+cast(@EmpAutoId as nvarchar(20))+'' WHERE MonthClosure_Id IN ('' + Convert(varchar(8000),@MonthCloseID) + '')''
Exec(@SqlQuery1)
set @SqlQuery2=''DELETE FROM TA_Tbl_PayrollProcessDetails WHERE MonthClosure_Id IN ('' + Convert(varchar(8000),@MonthCloseID) + '')''
Exec(@SqlQuery2)
set @SqlQuery3=''DELETE FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id IN ('' + Convert(varchar(8000),@MonthCloseID) + '')''
Exec(@SqlQuery3)
set @SqlQuery4=''DELETE FROM TA_Tbl_MonthClosure WHERE MonthClosure_Id IN ('' + Convert(varchar(8000),@MonthCloseID) + '')''
Exec(@SqlQuery4)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftAll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftAll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
For Deleting multiple shifts
*/
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteShiftAll] 
(@ShiftIds varchar(200))
as
BEGIN
	DECLARE @del NVARCHAR
	SET @del=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	/*UPDATE TA_Tbl_Shift SET Isdeleted=0 WHERE Shift_Id=@ShiftId*/
	SET @Query = ''UPDATE TA_Tbl_Shift SET IsDeleted= '' + @del + '' WHERE Shift_Id IN (''+ @ShiftIds +'')''
	EXEC (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_DeleteYearClosureLeaveTypedetails 11,[1,2,3],4,1
CREATE PROCEDURE [dbo].[Proc_TA_DeleteYearClosureLeaveTypedetails] 
(
@EmployeeId int,
@mappedLeaveTypes nvarchar(4000),
@YearsettingId int,
@auEmpId int
)
as
BEGIN
if(@mappedLeaveTypes!='''')
	BEGIN
		SET NOCOUNT ON;
		DECLARE @Query NVARCHAR(2000)
		SET @Query=''''
		SET @Query = ''DELETE FROM TA_TBL_YEARCLOSURE WHERE LeaveTypeId NOT IN (''+ @mappedLeaveTypes +'') and EMPLOYEE_ID='' + cast(@EmployeeId as nvarchar(20)) + '' and YEAR_SETTINGID='' + cast(@YearsettingId as nvarchar(20)) + '' ''
		EXEC (@Query)
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoasterDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftRoasterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
	Modified By		:	A.K.T.MOORTHI
	Modified Date	:	17-Dec-2013
	Description		:	Delete Shift Roster Details Based On Shift Roster Ids
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftRoasterDetails]
	@RoasterIds NVARCHAR(MAX),
	@DeleteType BIT
AS
BEGIN
	DECLARE @Query NVARCHAR(MAX)
	SET @Query=''''
	IF(@RoasterIds <> '''')
	BEGIN
		IF (@DeleteType = 1)
			SET @Query = ''DELETE FROM TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id IN (''+ @RoasterIds +'')''
		ELSE
			SET @Query = ''UPDATE TA_Tbl_ShiftRoaster SET IsDeleted = 1 WHERE ShiftRoaster_Id IN (''+ @RoasterIds +'')''
		EXEC (@Query)
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteType]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteType]
	@TypeID NVARCHAR(500),
	@EmpID as int
AS
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''update TA_Tbl_Type set IsDeleted=1,EmpId=''+cast(@EmpID as nvarchar(20))+'' where TypeId IN (''+ @TypeID +'')''
	Execute(@Query)
	--update TA_Tbl_Type set IsDeleted=1,EmpId = @EmpID where TypeId=@TypeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGeoLocation]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteGeoLocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-Aug-2020 10:21 AM,,>
-- Description:	It will delete the created geo location
-- Proc_TA_DeleteGeoLocation ''18,21,22''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteGeoLocation]
	@landmarkID varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET @Query = ''delete from Ta_tbl_LandMarks WHERE ID IN (''+ @landmarkID +'')''
	EXEC (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteHoliday]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified by	: 	Prabakaran.p 
Proc_TA_DeleteHoliday ''219'',''PermanentDelete'',1
Modified on	:	08-Feb-08
Description	:	Permanent Delete and Restore option Added	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteHoliday]
(
	@HolidayId NVARCHAR(1000),
	@strType NVARCHAR(50),
	@auditEmpId int
)
as  
BEGIN
	set nocount on
	DECLARE @Query NVARCHAR(2000)  
	SET @Query=''''	
	if(@strType=''TemporaryDelete'')
		begin  
			SET @Query = ''UPDATE TA_Tbl_Holiday SET IsDeleted= 1, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Holiday_Id IN (''+ @HolidayId +'')''  
		end  
	if(@strType=''PermanentDelete'')
		begin  
			SET @Query = ''DELETE FROM TA_Tbl_HolidayChildTable WHERE Holiday_Id IN (''+ @HolidayId +'');''  
			SET @Query = @Query+''DELETE FROM TA_Tbl_Holiday WHERE Holiday_Id IN (''+ @HolidayId +'')''  
		end  
	if(@strType=''Restore'')
		begin  
			SET @Query = ''UPDATE TA_Tbl_Holiday SET IsDeleted= 0, Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE Holiday_Id IN (''+ @HolidayId +'')''  
		end	
	EXEC (@Query)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveMaster]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeaveMaster]    
  @Id INT    
 AS    
SET NOCOUNT ON;     
 DECLARE @DEL BIT    
 SET @DEL=0    
 BEGIN    
  UPDATE TA_Tbl_LeaveMaster SET IsDeleted=@DEL WHERE Id=@Id  
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckRoute_Insert  
Description : check route before insert, is already there or not
Tables Included : TA_Tbl_RouteMaster  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckRoute_Insert]      
(      
@intVehicleID int,   
@RouteName NVARCHAR(50)      
)       
AS      
declare @sql as nvarchar(3000)
Declare @Isdel int      
--SET @Isdel=1      
 BEGIN      
  --SELECT COUNT(Route_Name) AS RName FROM TA_Tbl_RouteMaster WHERE Route_Name=@RouteName AND Isdeleted=0     
  set @sql = ''SELECT COUNT(Route_Name) AS RName FROM TA_Tbl_RouteMaster WHERE Route_Name=N''''''+@RouteName+'''''' AND Isdeleted=0''
  exec(@sql)
 END      
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_ForModification]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_ForModification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckRoute_ForModification]
	@RouteName NVARCHAR(50),      
	@RouteId int      
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)
	set @sql = ''Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>''+cast(@RouteId as nvarchar(25))+'' And Route_Name=N''''''+@RouteName+'''''' AND Isdeleted=0''
	exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternNameUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckShiftPatternNameUpdate  
Description : check for shift pattern while update   
Tables Included : TA_Tbl_ShiftPattern  
Created By : Janakaraj  
Created On : 10-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftPatternNameUpdate] 
	-- Add the parameters for the stored procedure here
	@shhiftPatternId INT,
    @shiftPatternName NVARCHAR(50)
AS
 DECLARE @Isdel int
 declare @sql as nvarchar(3000)
 SET @Isdel=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
--	SELECT count(ShiftPattern_Id)  AS PatternID FROM TA_Tbl_ShiftPattern 
--	WHERE Pattern_Name=@shiftPatternName and ShiftPattern_Id<>@shhiftPatternId and Isdeleted=@Isdel
    set @sql =  ''SELECT count(ShiftPattern_Id)  AS PatternID FROM TA_Tbl_ShiftPattern WHERE Pattern_Name=N''''''+@shiftPatternName+'''''' and ShiftPattern_Id<>''+cast(@shhiftPatternId as nvarchar(25))+'' ''
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternDelete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name 	: Proc_TA_CheckShiftPatternDelete
Description 	: check for shift pattern while delete
Tables Included : Ta_tbl_PermanentShiftAllocation, Ta_tbl_TemporaryShiftAllocation  
Created By 	: Janakaraj  
Created On 	: 10-Aug-2007
Modified By 	:  
Modified On 	:  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckShiftPatternDelete] 
@ShiftId int
as
declare @loop as int
declare @count as int
declare @count1 as int
declare @query as varchar(2000)
create table #Temp(Result int)
set @loop=1
set @count=0
set @count1=0
/* For getting count from Ta_tbl_PermanentShiftAllocation */
while @loop<=31
begin
set @query=''select count(*) as Result  from Ta_tbl_PermanentShiftAllocation where Day'' + Cast(@loop as Varchar(3)) + ''Shift='' + Cast(@ShiftId as varchar(2000))
insert into #Temp EXEC(@query)
set @loop=@loop+1
end
set @count=(select sum(Result) from #Temp)
delete from #Temp
set @loop=1
/*------------------*/
/* For getting count from Ta_tbl_TemporaryShiftAllocation */
while @loop<=31
begin
set @query=''select count(*) as Result  from Ta_tbl_TemporaryShiftAllocation where Day'' + Cast(@loop as Varchar(3)) + ''Shift='' + Cast(@ShiftId as varchar(2000))
insert into #Temp EXEC(@query)
set @loop=@loop+1
end
set @count1=(select sum(Result) from #Temp)
delete from #Temp
set @count=@count+ @count1
if(@count>1)
begin
set @count=1
end
select @count as ShiftCount
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPattern]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckShiftPattern  
Description : check for shift pattern while insert   
Tables Included : TA_Tbl_ShiftPattern  
Created By : Janakaraj  
Created On : 10-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckShiftPattern]
(
@companyId int,
@ShiftPattern nvarchar(50)
)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
	--SELECT COUNT(Pattern_Name) AS SCount from TA_Tbl_ShiftPattern WHERE Pattern_Name=@ShiftPattern and Isdeleted=@Isdel
    set @sql =''SELECT COUNT(Pattern_Name) AS SCount from TA_Tbl_ShiftPattern WHERE Pattern_Name=N''''''+@ShiftPattern+'''''' and Level_Id=''+cast(@companyId as nvarchar(8))
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftExchangeEmployee]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftExchangeEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckShiftExchangeEmployee  
Description : To Check the Employees
Tables Included : ta_tbl_employee,ta_tbl_employeelevel,ta_tbl_leveldetails
Created By : Sasireka  
Created On : 15-Jan-2009 
Modified By :  
Modified On :  
Proc_TA_CheckShiftExchangeEmployee ''1,2,3,47,113,132,133,134,135,137,138,140,150'',''3''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftExchangeEmployee]
(
	@levels nvarchar(500),
	@EmployeeId int
)
AS
BEGIN 
--set @levels = ''1,2,3,47,113,132,133,134,135,137,138,140,150''
declare @sql as varchar(6000)
set @sql= ''select count(*) as RecCount from ta_tbl_employee inner join ta_tbl_employeelevel on ta_tbl_employee.Employee_Id = ta_tbl_employeelevel.employeeid''
set @sql = @sql + '' inner join ta_tbl_leveldetails on ta_tbl_leveldetails.id=ta_tbl_employeelevel.levelid''
set @sql = @sql + '' where ta_tbl_employeelevel.levelid in ('' + @levels + '') and ta_tbl_employee.Employee_Id= '' + cast (@EmployeeId as nvarchar(10))
--select @sql as lev
exec (@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckStateCityInsertUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckStateCityInsertUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckStateCityInsertUpdate  
Description : check state and city while insert and update 
Tables Included : Ta_tbl_lookup  
Created By : P.Prabakaran    
Created On : 27-10-2007   
Modified By :  
Modified On :  
*/       
CREATE PROCEDURE [dbo].[Proc_TA_CheckStateCityInsertUpdate]  
@Mode char(1),      
@ID int,      
@Title nvarchar(50),      
@Parent int,
@TypeId int      
as      
declare @sql as nvarchar(3000)
/* For Insert */      
if(@Mode=''I'')      
begin      
  set @sql = ''select count(*) as StateCityCount  from Ta_tbl_lookup where Type=''+cast(@TypeId as nvarchar(25))+'' and Title=N''''''+@Title+'''''' and Parent=''+cast(@Parent as nvarchar(25))+''''      
  exec(@sql)
end      
/* For Modify */      
if(@Mode=''M'')      
begin      
   set @sql = ''select count(*) as StateCityCount  from Ta_tbl_lookup where Type=''+cast(@TypeId as nvarchar(25))+'' and Title=N''''''+@Title+'''''' and Parent=''+cast(@Parent as nvarchar(25))+'' and ID<>''+cast(@ID as nvarchar(25))+''''      
   exec(@sql)
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckShiftUpdate  
Description : check shift name before update, is already there or not
Tables Included : TA_Tbl_Shift  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftUpdate]  
(
@companyId int,
@ShiftId int,
@ShiftName nvarchar(50)
)
AS
declare @sql as nvarchar(3000)
BEGIN
	--SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> @ShiftId and Shift_Name=@ShiftName and Isdeleted=1
    set @sql = ''SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> ''+cast(@ShiftId as nvarchar(25))+'' and Shift_Name=N''''''+@ShiftName+'''''' and Level_Id=''+cast(@companyId as nvarchar(8))	
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftShortNameUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckShiftShortNameUpdate    
Description 	: check shift short name before update, is already there or not  
Tables Included : TA_Tbl_Shift    
Created By : Prabakaran.P    
Created On : 02-June-09
Modified By :    
Modified On :    
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftShortNameUpdate]    
(  
@companyId int,  
@ShiftId int,  
@ShiftShortName nvarchar(50)  
)  
AS  
declare @sql as nvarchar(3000)  
BEGIN  
 --SELECT COUNT(Shift_Name) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> @ShiftId and Shift_Name=@ShiftName and Isdeleted=1  
    set @sql = ''SELECT COUNT(*) as SName FROM TA_Tbl_Shift WHERE Shift_Id <> ''+cast(@ShiftId as nvarchar(25))+'' and Shift_ShortName=N''''''+ @ShiftShortName +'''''' and Level_Id=''+cast(@companyId as nvarchar(20))   
    exec(@sql)  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftShortName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftShortName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckShift    
Description : check shift name before insert, is already there or not  
Tables Included : TA_Tbl_Shift    
Created By :  Janakaraj.P    
Created On : 19-Aug-2007  
Modified By :    
Modified On :    
Proc_TA_CheckShift 151,''test10''  
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftShortName]  
(  
@companyId int,  
@ShiftShortName nvarchar(50)  
)  
AS  
DECLARE @Isdel int  
declare @sql as nvarchar(3000)  
SET @Isdel=0  
BEGIN  
 --SELECT COUNT(Shift_Name) AS SCount from TA_Tbl_Shift WHERE Shift_Name=@ShiftName and Isdeleted=@Isdel  
    set @sql = ''SELECT COUNT(*) AS SCount from TA_Tbl_Shift WHERE Shift_ShortName=N''''''+ @ShiftShortName +''''''''  
 set @sql = @sql +'' and Level_Id=''+cast(@companyId as nvarchar(8))   
    exec(@sql)  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalDatatype]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalDatatype]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/********************************************************************
    Purpose  - To Check Duplicates for Terminal DataTypes
    Author     - Kumuthini.L 
  Proc_TA_CheckTerminalDatatype ''U'',0,''RDBMS'',''RDBMS'','''','''',0,'''','''','''','''',0,'''','''','''','''',0,0,0,0,0,0,0,0,0,0,0,0,0,''server=Angler38'',''Timecheck'','''','''',0,'''','''','''','''',''ReaderNo'',''CardNo'',1,'''','''',''DateTime'',''Type''
**********************************************************************/
CREATE PROCEDURE 	 [dbo].[Proc_TA_CheckTerminalDatatype]
(
	@Type Char(1),
	@TerminalDatatypeId INT=0,
	@RawDataFormat NVARCHAR(25),
	@FileType NVARCHAR(15), 
	@FileSourcePath NVARCHAR(2000), 
	@FileBackupPath NVARCHAR(2000), 
	@NoOfFields int, 
	@Delimiter CHAR(5),  
	@StringEnclosedBy CHAR(5),  
	@Del_ReaderNo NVARCHAR(10),  
	@Del_CardNo NVARCHAR(10),  
	@Del_DateTimeBit int,  
	@Del_Date NVARCHAR(10),  
	@Del_Time NVARCHAR(10),  
	@Del_DateTime NVARCHAR(10),  
	@Del_Type NVARCHAR(10),  
	@FL_ReaderNoFrom int,  
	@FL_ReaderNoTo int,   
	@FL_CardNoFrom int,  
	@FL_CardNoTo int,  
	@FL_DateTimeBit int,  
	@FL_DateFrom int,  
	@FL_DateTo int,  
	@FL_TimeFrom int,  
	@FL_TimeTo int,  
	@FL_DateTimeFrom int,  
	@FL_DateTimeTo int,  
	@FL_TypeFrom int,  
	@FL_TypeTo int,  
	@ConnectionString  NVARCHAR(2000),  
	@TableName NVARCHAR(50),  
	@MDB_ReaderNo NVARCHAR(25),  
	@MDB_CardNo NVARCHAR(25),  
	@MDB_DateTimeBit int,  
	@MDB_Date NVARCHAR(25),   
	@MDB_Time NVARCHAR(25),  
	@MDB_DateTime NVARCHAR(25),  
	@MDB_Type NVARCHAR(25),  
	@RDBMS_ReaderNo NVARCHAR(25),  
	@RDBMS_CardNo NVARCHAR(25),  
	@RDBMS_DateTimeBit int,
	@RDBMS_Date NVARCHAR(25), 
	@RDBMS_Time NVARCHAR(25),
	@RDBMS_DateTime NVARCHAR(25), 
	@RDBMS_Type NVARCHAR(25),
	@RDBMS_MDB_Flag NVARCHAR(25)
)
AS
BEGIN
	DECLARE @sql nvarchar(2000)
	IF(@Type = ''I'')
	BEGIN
		set @sql=''SELECT TerminalDatatype_ID FROM  TA_tbl_TerminalDatatype WHERE (File_SourcePath=N'''''' + @FileSourcePath + '''''' AND File_BackupPath=N'''''' + @FileBackupPath + '''''' AND Delimiter_NoOfFields='' + cast(@NoOfFields as nvarchar(20)) + '' AND Delimiter_Delimiter='''''' + @Delimiter + ''''''
		AND Delimiter_StringEnclosedBy='''''' + @StringEnclosedBy + '''''' AND Delimiter_ReaderNo='''''' + cast(@Del_ReaderNo as nvarchar(20)) + '''''' AND Delimiter_CardNo='''''' + cast(@Del_CardNo as nvarchar(20)) + ''''''AND Delimiter_DateTimeBit='''''' + cast(@Del_DateTimeBit as nvarchar(20)) + '''''' AND Delimiter_Date=N'''''' + @Del_Date + '''''' AND 
		Delimiter_Time=N'''''' + @Del_Time + '''''' AND Delimiter_DateTime=N'''''' + @Del_DateTime + '''''' AND Delimiter_Type='''''' + @Del_Type + '''''' AND FixedLength_ReaderNoFrom='''''' + cast(@FL_ReaderNoFrom as nvarchar(20)) + '''''' AND FixedLength_ReaderNoTo='''''' + cast(@FL_ReaderNoTo as nvarchar(20)) + '''''' AND 
		FixedLength_CardNoFrom='''''' + cast(@FL_CardNoFrom as nvarchar(20)) + '''''' AND FixedLength_CardNoTo='''''' + cast(@FL_CardNoTo as nvarchar(20)) + '''''' AND FixedLength_DateTimeBit='''''' + cast(@FL_DateTimeBit as nvarchar(20)) + '''''' AND FixedLength_DateFrom='''''' + cast(@FL_DateFrom as nvarchar(20)) + ''''''  AND FixedLength_DateTo='''''' + cast(@FL_DateTo as nvarchar(20)) + ''''''
		AND FixedLength_TimeFrom='' + cast(@FL_TimeFrom as nvarchar(20)) + '' AND FixedLength_TimeTo='' + cast(@FL_TimeTo as nvarchar(20)) + '' AND FixedLength_DateTimeFrom='' + cast(@FL_DateTimeFrom as nvarchar(20)) + '' AND FixedLength_DateTimeTo='' + cast(@FL_DateTimeTo as nvarchar(20)) + '' AND
		FixedLength_TypeFrom='''''' + cast(@FL_TypeFrom as nvarchar(20)) + '''''' AND FixedLength_TypeTo='''''' + cast(@FL_TypeTo as nvarchar(20)) + '''''' AND ConnectionString=N'''''' + @ConnectionString + '''''' AND TableName=N'''''' + @TableName + '''''' AND MDB_ReaderNo='''''' + cast(@MDB_ReaderNo as nvarchar(20)) + '''''' AND MDB_CardNo='''''' + cast(@MDB_CardNo as nvarchar(20)) + ''''''
		AND MDB_DateTimeBit='''''' + cast(@MDB_DateTimeBit as nvarchar(20)) + '''''' AND MDB_Date='''''' + cast(@MDB_Date as nvarchar(20)) + '''''' AND MDB_Time=N'''''' + @MDB_Time + '''''' AND MDB_DateTime=N'''''' + @MDB_DateTime + '''''' AND MDB_Type=N'''''' + @MDB_Type + '''''' AND RDBMS_ReaderNo='''''' + cast(@RDBMS_ReaderNo as nvarchar(20)) + ''''''
		AND RDBMS_CardNo='''''' + cast(@RDBMS_CardNo as nvarchar(20)) + '''''' AND RDBMS_DateTimeBit='''''' + cast(@RDBMS_DateTimeBit as nvarchar(20) )+ '''''' AND RDBMS_Date=N'''''' + @RDBMS_Date  + '''''' AND RDBMS_Time=N'''''' + @RDBMS_Time + '''''' AND RDBMS_DateTime=N'''''' + @RDBMS_DateTime + ''''''
		AND RDBMS_Type=N'''''' + @MDB_Type + '''''' AND RDBMS_MDB_Flag='''''' + @RDBMS_MDB_Flag + '''''' AND FileType=N'''''' + @FileType + '''''' AND Raw_Data_Format <> N'''''' + @RawDataFormat + '''''' AND IsDeleted=0) OR (Raw_Data_Format = N'''''' + @RawDataFormat + '''''')''
	END
	ELSE IF(@Type = ''U'')
	BEGIN
		set @sql=''SELECT TerminalDatatype_ID FROM  TA_tbl_TerminalDatatype WHERE (File_SourcePath=N'''''' + @FileSourcePath + '''''' AND File_BackupPath=N'''''' + @FileBackupPath + '''''' AND Delimiter_NoOfFields='' + cast(@NoOfFields as nvarchar(20)) + '' AND Delimiter_Delimiter='''''' + @Delimiter + ''''''
		AND Delimiter_StringEnclosedBy='''''' + @StringEnclosedBy + '''''' AND Delimiter_ReaderNo='''''' + cast(@Del_ReaderNo as nvarchar(20)) + '''''' AND Delimiter_CardNo='''''' + cast(@Del_CardNo as nvarchar(20)) + '''''' AND Delimiter_DateTimeBit='' + cast(@Del_DateTimeBit as nvarchar(20)) + '' AND Delimiter_Date=N'''''' + @Del_Date + '''''' AND 
		Delimiter_Time=N'''''' + @Del_Time + '''''' AND Delimiter_DateTime=N'''''' + @Del_DateTime + '''''' AND Delimiter_Type='''''' + @Del_Type + '''''' AND FixedLength_ReaderNoFrom='''''' + cast(@FL_ReaderNoFrom as nvarchar(20)) + '''''' AND FixedLength_ReaderNoTo='''''' + cast(@FL_ReaderNoTo as nvarchar(20)) + '''''' AND 
		FixedLength_CardNoFrom='''''' + cast(@FL_TimeFrom as nvarchar(20)) + '''''' AND FixedLength_CardNoTo='''''' + cast(@FL_CardNoTo as nvarchar(20)) + '''''' AND FixedLength_DateTimeBit='''''' + cast(@FL_DateTimeBit as nvarchar(20)) + '''''' AND FixedLength_DateFrom='''''' + cast(@FL_DateTimeFrom as nvarchar(20)) + '''''' AND FixedLength_DateTo='''''' + cast(@FL_DateTimeTo as nvarchar(20)) + ''''''
		AND FixedLength_TimeFrom='''''' + cast(@FL_TypeFrom as nvarchar(20)) + '''''' AND FixedLength_TimeTo='''''' + cast(@FL_TimeTo as nvarchar(20)) + '''''' AND FixedLength_DateTimeFrom='''''' + cast(@FL_DateTimeFrom as nvarchar(20)) + '''''' AND FixedLength_DateTimeTo='''''' + cast(@FL_DateTimeTo as nvarchar(20)) + '''''' AND
		FixedLength_TypeFrom='''''' + cast(@FL_TimeFrom as nvarchar(20)) + '''''' AND FixedLength_TypeTo='''''' + cast(@FL_TypeTo as nvarchar(20)) + '''''' AND ConnectionString=N'''''' + @ConnectionString + '''''' AND TableName=N'''''' + @TableName + '''''' AND MDB_ReaderNo='''''' + cast(@MDB_ReaderNo as nvarchar(20)) + '''''' AND MDB_CardNo='''''' + cast(@MDB_CardNo as nvarchar(20)) + ''''''
		AND MDB_DateTimeBit='''''' + cast(@MDB_DateTimeBit as nvarchar(20)) + '''''' AND MDB_Date='''''' + cast(@MDB_Date as nvarchar(20)) + '''''' AND MDB_Time=N'''''' + @MDB_Time + '''''' AND MDB_DateTime=N'''''' + @MDB_DateTime + '''''' AND MDB_Type=N'''''' + @MDB_Type + '''''' AND RDBMS_ReaderNo='''''' + cast(@RDBMS_ReaderNo as nvarchar(20)) + ''''''
		AND RDBMS_CardNo='''''' + cast(@RDBMS_CardNo as nvarchar(20)) + '''''' AND RDBMS_DateTimeBit='''''' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + '''''' AND RDBMS_Date=N'''''' + @RDBMS_Date + '''''' AND RDBMS_Time=N'''''' + @RDBMS_Time + '''''' AND RDBMS_DateTime=N'''''' + @RDBMS_DateTime + ''''''
		AND RDBMS_Type=N'''''' + @MDB_Type + '''''' AND RDBMS_MDB_Flag='''''' + @RDBMS_MDB_Flag + '''''' AND FileType=N'''''' + @FileType + ''''''  AND Raw_Data_Format <> N'''''' + @RawDataFormat + '''''' AND TerminalDatatype_ID <> '''''' + cast(@TerminalDatatypeId as nvarchar(20)) + '''''' AND IsDeleted=0) OR (Raw_Data_Format=N'''''' + @RawDataFormat + '''''' AND TerminalDatatype_ID <> '''''' + cast(@TerminalDatatypeId as nvarchar(20)) + '''''')''
	END
	exec(@sql)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckTitle_Insert  ''GH'',5
Description : check title before insert  
Tables Included : TA_Tbl_Title  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTitle_Insert]  
(  
 @TitleName NVARCHAR(50),
 @LevelId int
)   
AS  
Declare @Isdel int  
declare @sql as nvarchar(max)
SET @Isdel=0  
 BEGIN    
   set @sql = ''SELECT COUNT(TitleName) AS TName FROM TA_Tbl_Title WHERE upper(TitleName)=upper(N''''''+@TitleName+'''''') and LevelID in (''+cast(@LevelId as nvarchar)+'') ''  
   exec(@sql)
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Insert]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : Proc_TA_CheckVehicle_Insert  
Description : check vehicle before insert, is exist or not    
Tables Included : TA_Tbl_Transportation_Vehicle    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE PROCEDURE [dbo].[Proc_TA_CheckVehicle_Insert]  
(  
	@VehicleNo NVARCHAR(50)     
)   
AS
	declare @sql as nvarchar(3000)  
	--Declare @Isdel int  
	--SET @Isdel=0    
 BEGIN  
	--SELECT COUNT(VehicleNo) AS VNO FROM TA_Tbl_Transportation_Vehicle WHERE VehicleNo=@VehicleNo AND Isdeleted=@Isdel  
	set @sql =''SELECT COUNT(VehicleNo) AS VNO FROM TA_Tbl_Transportation_Vehicle WHERE VehicleNo=N''''''+@VehicleNo+'''''''' 
	--AND Isdeleted=''+cast(@Isdel as nvarchar(25))+''''
	exec(@sql)
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_ForModification]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_ForModification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [dbo].[Proc_TA_CheckVehicle_ForModification]''asdfas'',7
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckVehicle_ForModification]
	@VehicleNo NVARCHAR(50),  
	@VehicleId int  
AS
declare @sql as nvarchar(3000)
DECLARE @Isdel INT  
SET @Isdel=0  
BEGIN  
   --Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>@VehicleId And VehicleNo=@VehicleNo AND Isdeleted=@Isdel
   set @sql = ''Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>''+cast(@VehicleId as nvarchar(25))+'' And VehicleNo=N''''''+@VehicleNo+'''''' AND Isdeleted=''+cast(@Isdel as nvarchar(25))+''''   
   exec(@sql)
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Updates]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Updates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckTitle_Insert    
Description : check title before insert    
Tables Included : TA_Tbl_Title    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTitle_Updates]
(  
	@TitleName NVARCHAR(50),
	@TitleID int,
	@LevelId int
)   
AS  
Declare @Isdel int  
declare @sql as nvarchar(3000)
SET @Isdel=0  
BEGIN
	set @sql = ''SELECT COUNT(TitleName) AS TName FROM TA_Tbl_Title WHERE upper(TitleName)=upper(N''''''+@TitleName+'''''') and TitleId<>''+cast(@TitleID as	nvarchar(250))+'' and LevelID in (''+cast(@LevelId as nvarchar)+'')''  
	exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckYearSettingExistsWhileYearClosing ''1/1/2007'',''12/31/2008'',''35,18''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckYearSettingExistsWhileYearClosing]
	-- Add the parameters for the stored procedure here
	@fromDate nvarchar(30),
	@toDate nvarchar(30),
	@yearSettingId nvarchar(1000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @query nvarchar(2000)
	set @query = ''''
	set @query = ''(SELECT count(*) FROM TA_Tbl_YearSetting where (FromDate between CONVERT(DATETIME, ''''''+cast(@toDate as nvarchar(30))+'''''', 102) and CONVERT(DATETIME, ''''''+cast(@fromDate as nvarchar(30))+'''''', 102) or ToDate between CONVERT(DATETIME, ''''''+cast(@toDate as nvarchar(30))+'''''', 102) and CONVERT(DATETIME, ''''''+cast(@fromDate as nvarchar(30))+'''''', 102)) and yearsettings_id not in (''+@yearSettingId+''))''
	exec (@query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleNo]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleNo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckVehicleNo  
Description : check vehicle no    
Tables Included : TA_Tbl_RouteMaster    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  
*/
CREATE Procedure [dbo].[Proc_TA_CheckVehicleNo]       
(         
	@VehicleId NVARCHAR(100)        
)         
As	
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	BEGIN                
		--Select Count(VehicleID)as VNO from TA_Tbl_RouteMaster where VehicleId=@VehicleId  AND Isdeleted=0
		SET @Query = ''Select Count(VehicleID)as VNO from TA_Tbl_RouteMaster where VehicleId IN (''+ @VehicleId +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[ConvertHoursToMinites]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConvertHoursToMinites]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
--select dbo.ConvertMinsToHours(100)
-- =============================================
CREATE FUNCTION [dbo].[ConvertHoursToMinites](@Hours time)
returns int	
Begin
		RETURN (select LTRIM(DATEDIFF(MINUTE, 0, @Hours)))
	
END

' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_ProperCase]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_ProperCase]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
create function [dbo].[Func_TA_ProperCase](@Text as varchar(8000))
returns varchar(8000)
as
begin
   declare @Reset bit;
   declare @Ret varchar(8000);
   declare @i int;
   declare @c char(1);
   select @Reset = 1, @i=1, @Ret = '''';
   while (@i <= len(@Text))
   	select @c= substring(@Text,@i,1),
               @Ret = @Ret + case when @Reset=1 then UPPER(@c) else LOWER(@c) end,
               @Reset = case when @c like ''[a-zA-Z]'' then 0 else 1 end,
               @i = @i +1
   return @Ret
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountryInsertUpdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCountryInsertUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckCountryInsertUpdate  
Description : check country before insert and update, is already there
Tables Included : Ta_tbl_lookup  
Created By : P.Prabakaran  
Created On : 27-10-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckCountryInsertUpdate]  
@Mode char(1),  
@ID int,  
@Title nvarchar(50)  
as
declare @sql as nvarchar(3000)  
/* For Insert */  
if(@Mode=''I'')  
begin  
  set @sql = ''select count(*) as CountryCount from Ta_tbl_lookup where Type=1  and Title=N''''''+@Title+''''''''  
  exec(@sql)
end  
/* For Modify */  
if(@Mode=''M'')  
begin  
  set @sql = ''select count(*) as CountryCount  from Ta_tbl_lookup where Type=1 and Title=N''''''+@Title+'''''' and ID<>''+cast(@ID as nvarchar(25))+''''  
  exec(@sql)
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
Procedure Name : Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate    
Description : check employee code is already there or not to avoid duplication    
Tables Included : TA_Tbl_Employee    
Created By : Arun Vinoth.T    
Created On : 27-Aug-2007    
Modified By :    
Modified On :    
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeSwipeCardAddupdate]   
(  
@SwipeCardNo NVARCHAR(15),  
@Empid nvarchar(15),
@inType nvarchar(15)
)  
AS  
  BEGIN  
declare @sql as varchar(3000)  
if(@inType=''Add'') 
BEGIN  
 set @sql = ''SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE SwipeCardNo=N''''''+@SwipeCardNo+'''''' AND Isdeleted=0''  
END  
else if (@inType=''Modify'')
BEGIN  
 set @sql = ''SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE SwipeCardNo=N''''''+@SwipeCardNo+'''''' AND Employee_Id<>''+cast(@Empid as nvarchar(25))+'' AND Isdeleted=0''  
END  
 exec(@sql)  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckDuplicateEmployeeCodeupdate  
Description : check employee code is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007  
Modified By :  A.K.T.MOORTHI
Modified On :  08-Apr-2014
Description  :  When Demo Mode Remove Condition For IsDeleted = 0 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCodeupdate] 
(
@EmpCode NVARCHAR(15),
@Empid int,
@ApplnMode BIT
)
AS
declare @sql as varchar(3000)
BEGIN
	set @sql = ''SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE Employee_Code_Id=N''''''+@EmpCode+'''''' AND Employee_Id<>'' + CAST(@Empid as nvarchar(25)) +  (CASE WHEN @ApplnMode = 1 THEN ''AND Isdeleted = 0'' ELSE '''' END)
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmployeeCode]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmployeeCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: Proc_TA_CheckDuplicateEmployeeCode  
Description 	: check employee code is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By 	: Arun Vinoth.T  
Created On 	: 27-Aug-2007  
Modified By 	:  A.K.T.MOORTHI
Modified On	 :  08-Apr-2014
Description  :  When Demo Mode Remove Condition For IsDeleted = 0 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmployeeCode] 
(
	@EmpCode NVARCHAR(10),
	@LevelId int,
	@ApplnMode BIT
)
AS
BEGIN
	set nocount on
	declare @sql as varchar(3000)
	set @sql = ''SELECT COUNT(Employee_Code_Id) AS EID FROM TA_Tbl_Employee WHERE Employee_Code_Id = N'''''' + @EmpCode + '''''''' + (CASE WHEN @ApplnMode = 1 THEN ''AND Isdeleted = 0'' ELSE '''' END)
    exec(@sql)	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Update]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveMaster_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_CheckLeaveMaster_Update]            
(           
@Id int, 
 @Company_Id int,    
@Region_Id int,    
@Branch_Id int,    
@Department_Id int,    
@Section_Id int,    
@Title_Id int,    
@LeaveId int           
)             
As            
DECLARE @Isdel INT            
SET @Isdel=1            
 BEGIN         
	SET NOCOUNT ON;   
	Select Count(Id)as [Id] from TA_Tbl_LeaveMaster            
	where Company_Id=@Company_Id AND Region_Id=@Region_Id AND Branch_Id=@Branch_Id     
	AND Department_Id=@Department_Id AND Section_Id=@Section_Id AND Title_Id=@Title_Id AND LeaveType_Id=@LeaveId AND IsDeleted=1    
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveMaster_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveMaster_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_CheckLeaveMaster_Insert]  
(            
 @Company_Id int,    
@Region_Id int,    
@Branch_Id int,    
@Department_Id int,    
@Section_Id int,    
@Title_Id int,   
@LeaveId int           
)             
As            
DECLARE @Isdel INT            
SET @Isdel=1            
 BEGIN            
	SET NOCOUNT ON;            
	Select Count(Id)as [Id] from TA_Tbl_LeaveMaster where LeaveType_Id=@LeaveId AND Company_Id=@Company_Id AND Region_Id=@Region_Id AND Branch_Id=@Branch_Id AND Department_Id=@Department_Id AND Section_Id=@Section_Id AND Title_Id=@Title_Id AND IsDeleted=1    
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Insert]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckGradeName_Insert 
Description : check grade name before insert, is already there  
Tables Included : Ta_Tbl_Grade  
Created By : Arun Vinoth.T  
Created On : 21-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeName_Insert]      
( 
	@Grade_Name NVARCHAR(50)            
)       
AS	
BEGIN
	Declare @Isdel int      
	declare @sql as nvarchar(3000)
	SET @Isdel=0
	set @sql = ''SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N''''''+@Grade_Name+'''''' ''      
	exec(@sql)	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Updates]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Updates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name : Proc_TA_CheckGradeName_Update   
Description : check grade name before update, is already there    
Tables Included : Ta_Tbl_Grade    
Created By : Arun Vinoth.T    
Created On : 21-Aug-2007  
Modified By :
Modified On : 
*/
create PROCEDURE [dbo].[Proc_TA_CheckGradeName_Updates]    
(    
	@GradeId int,@Grade_Name nvarchar(50)
)     
AS    
	Declare @Isdel int    
	declare @sql as nvarchar(3000)	    
	SET @Isdel=0    
BEGIN	
	set @sql = ''SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N''''''+@Grade_Name+'''''' AND Grade_ID<>''+cast(@GradeId as	nvarchar(250))+'' ''
	exec(@sql)    
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Update]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckEntrance_Update
Description	:	Checking the entrance name already exists in the same level while updating
Tables Included	:	ta_tbl_entrance
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:   Manikandan.R       
Modified On	:   23-11-2016 12.43
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Update]    
( 
	@EntranceId INT,   
	@EntranceName NVARCHAR(50),
	@OrgLevel INT 
)     
AS    
BEGIN    
	SET NOCOUNT ON
	DECLARE @sql as nvarchar(2000)
	SET @sql=''Select Count(Entrance_Name) AS EntranceNameCount FROM TA_Tbl_Entrance    
	WHERE Entrance_Id <> '' + cast(@EntranceId as nvarchar(20)) + '' AND Entrance_Name=N'''''' + @EntranceName + '''''' AND OrgLevel_Id = '' + cast(@OrgLevel as nvarchar(20)) + ''''    
	EXEC(@sql)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		manikandan.R
-- Create date: 09-June-2012
-- Description:	To check whether the leave types are used or not
-- =============================================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveTypeForPermanentDelete]
	-- Add the parameters for the stored procedure here
	@id varchar(500)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(2000)
	set @sql=''select COUNT(leavetype_id)as Ltype from TA_Tbl_LeavePolicyDetails where LeaveType_Id in(''+@id+'')''
	Execute(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcNameUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_CheckProcNameUpdate  
Description		:	check for shift roaster while update   
Tables Included :	TA_Tbl_ShiftRoaster  
Created By		:	Janakaraj  
Created On		:	30-Nov-07  
Modified By		:  A.K.T.MOORTHI
Modified On		:  17-Dec-2013
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcNameUpdate](
	@companyId INT,
	@RoasterName NVARCHAR(50),
	@ShiftRoasterId INT)
AS
BEGIN
	DECLARE @sql NVARCHAR(3000)
	--SELECT COUNT(*) FROM TA_Tbl_ShiftRoaster where ShiftRoaster_Name=@RoasterName AND IsDeleted=0 and ShiftRoaster_Id <> @ShiftRoasterId
    SET @sql = ''SELECT COUNT(ShiftRoaster_Name) FROM TA_Tbl_ShiftRoaster WHERE IsDeleted = 0 AND ShiftRoaster_Name = N'''''' + @RoasterName + '''''' AND ShiftRoaster_Id <> '' + CAST(@ShiftRoasterId AS NVARCHAR(25)) + '' AND Level_Id = '' + CAST(@companyId AS NVARCHAR(8))
    EXEC(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
	Procedure Name : Proc_TA_CheckProcName  
	Description : check for shift roaster while insert   
	Tables Included : TA_Tbl_ShiftRoaster  
	Created By : Janakaraj  
	Created On : 30-Nov-07  
	Modified By :  A.K.T.MOORTHI
	Modified On :  17-Dec-2013
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcName](
	@companyId INT,
	@RoasterName NVARCHAR(50))
AS
BEGIN
	DECLARE @sql NVARCHAR(3000)
	--SELECT COUNT(*) FROM TA_Tbl_ShiftRoaster where ShiftRoaster_Name=@RoasterName AND IsDeleted=0
	SET @sql =''SELECT COUNT(IsDeleted) FROM TA_Tbl_ShiftRoaster WHERE IsDeleted = 0 AND ShiftRoaster_Name = N'''''' + @RoasterName + '''''' AND Level_Id = '' + CAST(@companyId AS NVARCHAR(8))
	EXEC(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNews]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getNews]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
	created by : senthil
	created on : 10 Aug 2007
	Description : Getting news/Events
---  Proc_TA_getNews  ''LeftNewsEvent''
*/
CREATE  procedure [dbo].[Proc_TA_getNews]
(
	@pos as nvarchar(25)
)
as 
Begin
	declare @sqlQuery as nvarchar(500)
	--set @sqlQuery = ''select top 1* from ta_tbl_newsEvents where NewsEventDate=convert(varchar(10),getdate(),101) and isdeleted=0 and NewsEventactive=1 and '' + cast(@pos as nvarchar(20)) + '' =1 order by newid()''  
		set @sqlQuery = ''select * from ta_tbl_newsEvents where (convert(varchar(10),getdate(),101) between NewsEventFromDate and NewsEventToDate) and isdeleted=0 and NewsEventactive=1 and '' + cast(@pos as nvarchar(20)) + '' =1 order by newsEvent_Id''  
	exec (@sqlQuery)
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdForWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdForWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_GetShiftIdForWeekOff 
Description		:	Get ShiftId for a Given From Date
Tables Included		:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By		:	Prabakaran
Created On		:	02-Dec-08
Modified By		:
Modified On		:
[Proc_TA_GetShiftIdForWeekOff] 157,''08/25/2008'',''08/25/2008'',''A''
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetShiftIdForWeekOff]
@EmployeeId int,
@SearchDate datetime
as
Begin
	declare @query as Varchar(3000)
	Declare @TempShiftId as int
	create table #Temp(ShiftTemp int)
	create table #Temp1(ShiftTemp int)
	set @query = (''select Day'' + Cast(Day(@SearchDate) as Varchar(25)) + ''Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year('''''' + cast(@SearchDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@SearchDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
	insert into #Temp EXEC(@query)
	set @TempShiftId=(select * from #Temp)
	drop table #Temp
	if @TempShiftId=-1 or @TempShiftId>0
	begin
	select @TempShiftId as ShiftId
	end
	else if @TempShiftId=0 or @TempShiftId is null
	begin
	set @query = (''select Day'' + Cast(Day(@SearchDate) as Varchar(25)) + ''Shift from  TA_Tbl_PermanentShiftAllocation where Year = year('''''' + cast(@SearchDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@SearchDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
	insert into #Temp1 EXEC(@query)
	set @TempShiftId=(select * from #Temp1)
	select @TempShiftId as ShiftId
	drop table #Temp1
	end	
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <23-02-2017 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_TA_GettingNearShiftDetails_ShiftAllocation ''2017/02/01'',''100'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingNearShiftDetails_ShiftAllocation]
	@FROMDAT datetime,
	@EMPLOYEEID VARCHAR(MAX),
	@CompanyId bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	CREATE TABLE #TEMPPROCESSEDDATA(EMPLOYEE_CODE_ID VARCHAR(20),INTIME NVARCHAR(25),DATE DATETIME)
	SET @SQLTEMPPROCESSEDDATA1=
	''INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			PD.DATE
	FROM TA_TBL_PROCESSEDDATA PD
	WHERE PROCESSFLAG=1 AND (PD.DATE= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102))and intime is not null and intime<>''''00:00'''' '' 
	IF(@EMPLOYEEID<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + '' AND PD.EMPLOYEE_CODE_ID= ''+  CAST (@EMPLOYEEID AS NVARCHAR(50))
		END
	--print(@SQLTEMPPROCESSEDDATA1)
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	--select * from #TEMPPROCESSEDDATA
	CREATE TABLE #TEMPMONTHLYATTENDANCE(CloseShifts varchar(max),ShiftID int)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''
	SET @SQLQUERY = ''SELECT 
	(select NearShift from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](''''''+CONVERT(varchar(20),@CompanyId)+'''''',PD.DATE+PD.INTIME,1,PD.DATE)where Orderby=1),
	(select ShiftID from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](''''''+CONVERT(varchar(20),@CompanyId)+'''''',PD.DATE+PD.INTIME,1,PD.DATE)where Orderby=1)''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.swipecardno=PD.EMPLOYEE_CODE_ID''   	
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)''    
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)''
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	(select NearShift from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](''''''+CONVERT(varchar(20),@CompanyId)+'''''',PD.DATE+PD.INTIME,2,PD.DATE)where Orderby=2),
	(select ShiftID from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](''''''+CONVERT(varchar(20),@CompanyId)+'''''',PD.DATE+PD.INTIME,2,PD.DATE)where Orderby=2)''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.swipecardno=PD.EMPLOYEE_CODE_ID''   	
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)''    
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)''     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)
	select  CloseShifts NearestShift,ShiftID
	from #TEMPMONTHLYATTENDANCE
	drop table #TEMPPROCESSEDDATA
	drop table #TEMPMONTHLYATTENDANCE
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration 2,''Friday'',''Thursday'',15,10
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfigurationService]
	-- Add the parameters for the stored procedure here
	@Frequency int,
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateFrom int,
	@DateTo int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Current_WeekStartDay datetime
	declare @Current_WeekEndDay datetime
	declare @Prev_WeekStartDay datetime
	declare @Prev_WeekStartDayFinal datetime
	declare @Prev_WeekEndDay datetime
	Declare @DayFromWeek varchar(10)
	Declare @DayToWeek varchar(10)
    -- Insert statements for procedure here
	if(@Frequency=2)
	begin		
		select @Current_WeekStartDay= DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()),@Current_WeekEndDay=DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate())
		select @Prev_WeekStartDay= DATEADD(day, -7, @Current_WeekStartDay)
		select @Prev_WeekStartDay=case when @DayFrom=''Sunday'' then  @Prev_WeekStartDay
								when @DayFrom=''Monday'' then  DATEADD(d,1,@Prev_WeekStartDay)
								when @DayFrom=''Tuesday'' then  DATEADD(d,2,@Prev_WeekStartDay)
								when @DayFrom=''Wednesday'' then  DATEADD(d,3,@Prev_WeekStartDay)
								when @DayFrom=''Thursday'' then  DATEADD(d,4,@Prev_WeekStartDay)
								when @DayFrom=''Friday'' then  DATEADD(d,5,@Prev_WeekStartDay)
								when @DayFrom=''Saturday'' then  DATEADD(d,6,@Prev_WeekStartDay)
					 end
		set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
		Declare @i int 
		set @i=1
		while @i>0
		begin
			set @DayFromWeek=DATENAME(DW,@Prev_WeekStartDay)
			if(@DayFromWeek=@DayTo)
			begin
				set @Prev_WeekEndDay=@Prev_WeekStartDay
				set @i=0
			end
			else
			begin
				set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
				set @i=@i+1
			end			
		end
		select 		
		replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),'' '',''-'') as Frodate,
		replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),'' '',''-'') as Todate
	end
	if @Frequency=3
	begin
		Declare @CurrentMonth_StartDate datetime
		Declare @PreviousMonth_StartDate datetime
		set @CurrentMonth_StartDate=DATEADD(d,-datepart(d,getdate())+1,getdate())
		set @PreviousMonth_StartDate=DATEADD(MONTH,-1,@CurrentMonth_StartDate)
		select  @CurrentMonth_StartDate,@PreviousMonth_StartDate
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration 3,''Sunday'',''Saturday'',1,31
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetWeekDaysForEmailBasedOnConfiguration]
	-- Add the parameters for the stored procedure here
	@Frequency int,
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateFrom int,
	@DateTo int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Current_WeekStartDay datetime
	declare @Current_WeekEndDay datetime
	declare @Prev_WeekStartDay datetime
	declare @Prev_WeekStartDayFinal datetime
	declare @Prev_WeekEndDay datetime
	Declare @DayFromWeek varchar(10)
	Declare @DayToWeek varchar(10)
	Declare @CurrentMonth_StartDate datetime
	Declare @PreviousMonth_StartDate datetime
	Declare @PreviousMonth_EndDate datetime
	declare @GetmonthNumer int
    -- Insert statements for procedure here
	if(@Frequency=2)
	begin		
		select @Current_WeekStartDay= DATEADD(dd, -(DATEPART(dw, getdate())-1), getdate()),@Current_WeekEndDay=DATEADD(dd, 7-(DATEPART(dw, getdate())), getdate())
		select @Prev_WeekStartDay= DATEADD(day, -7, @Current_WeekStartDay)
		Declare @i int 
		if(ISNUMERIC(@DayFrom)=0)
		begin
			select @Prev_WeekStartDay=case when @DayFrom=''Sunday'' then  @Prev_WeekStartDay
									when @DayFrom=''Monday'' then  DATEADD(d,1,@Prev_WeekStartDay)
									when @DayFrom=''Tuesday'' then  DATEADD(d,2,@Prev_WeekStartDay)
									when @DayFrom=''Wednesday'' then  DATEADD(d,3,@Prev_WeekStartDay)
									when @DayFrom=''Thursday'' then  DATEADD(d,4,@Prev_WeekStartDay)
									when @DayFrom=''Friday'' then  DATEADD(d,5,@Prev_WeekStartDay)
									when @DayFrom=''Saturday'' then  DATEADD(d,6,@Prev_WeekStartDay)
						 end
			set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
			set @i=1
			while @i>0
			begin
				set @DayFromWeek=DATENAME(DW,@Prev_WeekStartDay)
				if(@DayFromWeek=@DayTo)
				begin
					set @Prev_WeekEndDay=@Prev_WeekStartDay
					set @i=0
				end
				else
				begin
					set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
					set @i=@i+1
				end			
			end
			select 	2 as frequency,replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),'' '',''-'') as Fromdate,
			replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),'' '',''-'') as Todate
		end
		else
		begin
			select @Prev_WeekStartDay=case when @DayFrom=''1'' then  @Prev_WeekStartDay
									when @DayFrom=''2'' then  DATEADD(d,1,@Prev_WeekStartDay)
									when @DayFrom=''3'' then  DATEADD(d,2,@Prev_WeekStartDay)
									when @DayFrom=''4'' then  DATEADD(d,3,@Prev_WeekStartDay)
									when @DayFrom=''5'' then  DATEADD(d,4,@Prev_WeekStartDay)
									when @DayFrom=''6'' then  DATEADD(d,5,@Prev_WeekStartDay)
									when @DayFrom=''7'' then  DATEADD(d,6,@Prev_WeekStartDay)
						 end
			set @Prev_WeekStartDayFinal=@Prev_WeekStartDay
			set @i=1
			while @i>0
			begin
				set @DayFromWeek=case when DATENAME(DW,@Prev_WeekStartDay)=''Sunday'' then 1
										when DATENAME(DW,@Prev_WeekStartDay)=''Monday'' then 2
										when DATENAME(DW,@Prev_WeekStartDay)=''Tuesday'' then 3
										when DATENAME(DW,@Prev_WeekStartDay)=''Wednesday'' then 4
										when DATENAME(DW,@Prev_WeekStartDay)=''Thursday'' then 5
										when DATENAME(DW,@Prev_WeekStartDay)=''Friday'' then 6
										else 7 end
				if(@DayFromWeek=@DayTo)
				begin
					set @Prev_WeekEndDay=@Prev_WeekStartDay
					set @i=0
				end
				else
				begin
					set @Prev_WeekStartDay=DATEADD(d,1,@Prev_WeekStartDay)
					set @i=@i+1
				end			
			end
			select 	2 as frequency,replace(CONVERT(varchar(20),@Prev_WeekStartDayFinal,106),'' '',''-'') as Fromdate,
			replace(CONVERT(varchar(20),@Prev_WeekEndDay,106),'' '',''-'') as Todate
		end
	end
	if @Frequency=3
	begin		
		set @CurrentMonth_StartDate=DATEADD(d,-datepart(d,getdate())+1,getdate())
		set @PreviousMonth_StartDate=DATEADD(MONTH,-1,@CurrentMonth_StartDate)
		if(DATEPART(d,@PreviousMonth_StartDate)=@DateFrom)
		begin			
			set @PreviousMonth_StartDate=@PreviousMonth_StartDate
		end
		else
		begin
			set @PreviousMonth_StartDate=DATEADD(d,@DateFrom-1,@PreviousMonth_StartDate)
		end		
		set @i=1
		while @i>0
		begin
			set @PreviousMonth_EndDate=DATEADD(d,@i,@PreviousMonth_StartDate)
			set @GetmonthNumer=DATEPART(MONTH,@PreviousMonth_StartDate)
			if @GetmonthNumer in(2)
			begin
				if @DateFrom=1 and (@DateTo=31 or @DateTo=30 or @DateTo=29)
				begin
					if(DATEPART(year,@PreviousMonth_EndDate)%4=0)
					begin
						set @DateTo=29
					end
					else
					begin
						set @DateTo=28
					end
				end				
			end
			else if @GetmonthNumer in(4,6,9,11)
			begin
				if @DateFrom=1 and @DateTo=31
				begin
					set @DateTo=30
				end
			end
			else if @GetmonthNumer in(1,3,5,7,8,10,12)
			begin
				if @DateFrom=1 and @DateTo=31
				begin
					set @DateTo=31
				end
			end
			if(DATEPART(d,@PreviousMonth_EndDate)=@DateTo)
			begin
				set @PreviousMonth_EndDate=@PreviousMonth_EndDate
				set @i=0
			end
			else
			begin
				set @i=@i+1
			end
		end
		--select @PreviousMonth_StartDate,@PreviousMonth_EndDate
		select 		3 as frequency,
		replace(CONVERT(varchar(20),@PreviousMonth_StartDate,106),'' '',''-'') as Fromdate,
		replace(CONVERT(varchar(20),@PreviousMonth_EndDate,106),'' '',''-'') as Todate
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeWorkedDays]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeWorkedDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- ALTER  date: <ALTER  Date,,>  
-- Description: <Description,,>  
-- =============================================  
--Proc_TA_GetEmployeeWorkedDays ''40716'',[''CL''],''4/1/2008'',''04/30/2008''  
CREATE   PROCEDURE [dbo].[Proc_TA_GetEmployeeWorkedDays]  
 @EmployeeID as nvarchar(50),   
 @FilterBy as nvarchar(200),  
 @FromDate as nvarchar(15),  
 @ToDate as nvarchar(15)   
AS  
BEGIN  
 declare @SqlQuery as varchar(5000)  
 declare @SqlQuery1 as varchar(5000)  
 create table #Temp1(WorkDays1 varchar(20))    
 create table #Temp2(WorkDays2 varchar(20))   
declare @count1 as float
declare @count2 as float  
declare @count3 as float  
set @SqlQuery = ''Select count(FNAttendanceCode) from Ta_tbl_ProcessedData PD INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo=PD.Employee_Code_Id where ED.Employee_Id=''''''+ @EmployeeID + '''''' ''  
Set @SqlQuery = @SqlQuery + '' and  PD.FNAttendanceCode in ('' + @FilterBy + '') and PD.date between CONVERT(DATETIME, '''''' + cast(@FromDate as nvarchar(11)) + '''''', 102) ''  
Set @SqlQuery = @SqlQuery + '' and CONVERT(DATETIME, '''''' + cast(@ToDate as nvarchar(11)) + '''''', 102) ''  
set @SqlQuery1 = ''Select count(ANAttendanceCode) from Ta_tbl_ProcessedData PD INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo=PD.Employee_Code_Id where ED.Employee_Id=''''''+ @EmployeeID + '''''' ''  
Set @SqlQuery1 = @SqlQuery1 + '' and  (PD.ANAttendanceCode in ('' + @FilterBy + '')) and PD.date between CONVERT(DATETIME, '''''' + cast(@FromDate as nvarchar(11)) + '''''', 102) ''  
Set @SqlQuery1 = @SqlQuery1 + '' and CONVERT(DATETIME, '''''' + cast(@ToDate as nvarchar(11)) + '''''', 102) ''  
insert into #Temp1 exec (@SqlQuery)  
insert into #Temp2 exec (@SqlQuery1)  
set @count1=(select isnull(WorkDays1,0) from #Temp1)  
set @count2=(select isnull(WorkDays2,0) from #Temp2)  
if(@count1>0)
begin
set @count1=(@count1)/2
end
if(@count2>0)
begin
set @count2=(@count2)/2
end
drop table #Temp1   
drop table #Temp2  
set @count3=cast(@count1 as float)+ cast(@count2 as float)  
select @count3 as WorkedDays  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeEmailIds]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeEmailIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified by : Thilakraj.C   On : 22-Feb-2013
For : " Com " shown as "Co" - 
SELECT substring(@List,0,LEN(@List)) as Email--- OLD Line No : 40
SELECT substring(@List,1,LEN(@List)) as Email --- New
*/
--Proc_TA_GetEmployeeEmailIds ''1,2,3,4,5,6,7,8''
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeEmailIds]
(
 @EmployeeIds varchar(4000)
)
AS
BEGIN
declare @sql varchar(4000)
set @sql =''''
create table #TempEmail (Email varchar(250))
set @sql = @sql + ''select emailId from TA_Tbl_Employee where Employee_Id in ('' + @EmployeeIds + '')''
insert into #TempEmail exec (@sql)
DECLARE @List VARCHAR(8000)
SELECT @List = COALESCE(@List + '';'', '''') + CAST(Email AS VARCHAR)
FROM   #TempEmail
SELECT substring(@List,1,LEN(@List)) as Email
drop table #TempEmail 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePolicyDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeavePolicyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	[Proc_TA_GetLeavePolicyDetails] '''',null,null,null,null
CREATE Proc [dbo].[Proc_TA_GetLeavePolicyDetails]
(    
    @UserGroupName nVarchar(250),
    @EmployeeCategory varchar(50)=null,
    @EmployeeType varchar(50)=null,
    @Gender varchar(10)=null,
    @Religion varchar(20)=null    
)    
AS      
Begin
	SET NOCOUNT ON;
	DECLARE @SQL NVARCHAR(MAX)
	IF(@UserGroupName = ''SuperAdmin'')    
		BEGIN    		
			SET @SQL=''SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,isnull(isWFH,0) as isWFH FROM TA_Tbl_LeaveType 
			Where IsDeleted=0''						
		END    
	ELSE    
		BEGIN        
			SET @SQL=''SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,isnull(isWFH,0) as isWFH FROM TA_Tbl_LeaveType 
			Where IsDeleted=0''
		END    		
	IF @EmployeeCategory is not null
		begin
			if @EmployeeCategory=0
				begin
					set @SQL= @SQL+ '' and (EmployeeCategory in (select EmployeeCategory from ta_tbl_Leavetype) or EmployeeCategory=0)''
				end
			else
				begin
					set @SQL= @SQL+ '' and (EmployeeCategory='' +CONVERT(varchar(10),@EmployeeCategory) +'' or EmployeeCategory=0)'' 
				end
		end
	IF  @EmployeeType is not null
		if @EmployeeType=0
			begin
				set @SQL= @SQL+ '' and (EmployeeType in (select EmployeeType from ta_tbl_Leavetype) or EmployeeType=0)''
			end
		else			
			begin
				set @SQL= @SQL+ '' and (EmployeeType='' +CONVERT(varchar(10),@EmployeeType)+'' or EmployeeType=0)'' 
			end
	IF  @Gender is not null
		begin
			if @Gender=''Both''
				begin
					set @SQL= @SQL + '' and (Gender=''''Female'''' or Gender=''''Male'''' or Gender=''''Both'''')''
				end
			else
				begin
					set @SQL= @SQL + '' and (Gender=''''''+CONVERT(varchar(10),@gender)+'''''' or Gender=''''Both'''')''
				end
		end
	IF  @Religion is not null-- and @Religion<>0
		IF @Religion=0
			begin
				set @SQL= @SQL + '' and (Religion in(select Religion from Ta_tbl_LeaveType) or Religion=0)''
			end
		else
			begin
				set @SQL= @SQL + '' and (Religion=''+CONVERT(varchar(10),@Religion)+'' or Religion=0)''
			end			
	set @SQL= @SQL+ '' order by LeaveType_Id''
	execute(@sql)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[Proc_TA_GetLeaveLOP_LeaveMaster]  
AS    
BEGIN  
	SET NOCOUNT ON;
	SELECT id,LOP,LOPDescription FROM TA_Tbl_LeaveMasterLOP 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevelUpdated]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getMinimumLevelUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_getMinimumLevelUpdated ''1,2''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getMinimumLevelUpdated]
	@LevelIDs as nvarchar(100)
As
BEGIN
	declare @Query as varchar(7000)		
	set @Query = ''select min(id) as minID  from ta_tbl_leveldetails where isdeleted=0 and id in ('' + @LevelIDs + '')''
	exec (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountInterveningWeekOff]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCountInterveningWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetCountInterveningWeekOff 
Description	:	Get weekly off count exist within given Fromdate and Todate
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By	:	Prabakaran
Created On	:	16-Aug-07
Modified By	:
Modified On	:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetCountInterveningWeekOff] 
@EmployeeId int,
@FromDate datetime,
@ToDate datetime,
@Type varchar(10)
as
declare @query as Varchar(3000)
Declare @TempShiftId as int
Declare @CountDays as int
create table #Temp(ShiftTemp int)
declare @vFromDate as datetime
declare @vToDate as datetime
set @vFromDate=DateAdd(day,-1,@FromDate)
set @vToDate=DateAdd(day,-1,@ToDate)
while(@vFromDate<=@vToDate)
begin
set @vFromDate=DateAdd(day,1,@vFromDate)
if(@Type=''P'')
set @query = (''select Day'' + Cast(Day(@vFromDate) as Varchar(25)) + ''Shift from  TA_Tbl_PermanentShiftAllocation where Year = year('''''' + cast(@vFromDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@vFromDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
if(@Type=''T'')
set @query = (''select Day'' + Cast(Day(@vFromDate) as Varchar(25)) + ''Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year('''''' + cast(@vFromDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@vFromDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
insert into #Temp EXEC(@query)
end
select * from #Temp
drop table #Temp
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLevel]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
    -- Insert statements for procedure here
	Declare @sql varchar(max)
	Set @sql=''	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
				select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
				inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
				where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId				
				AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and EL.LevelId is not null ''	
	if (@Employee_Code_Id<>'''')
		begin					
			Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
		End
	else
		Begin				
			Set @sql=@sql 
		end	
	execute(@sql)		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_ShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,28-November>
-- Description:	<Description,,Delete the Shifts for given period>
-- Proc_TA_Update_ShiftAllocation ''Day21Shift=0'',2009,1,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Update_ShiftAllocation]
(
@ColName varchar(3000),
@Year int,
@Month int,
@loginEmployeeId varchar(50)
)
AS
BEGIN
	DECLARE @sSql  varchar(8000)
	SET @sSql = ''UPDATE TA_Tbl_PermanentShiftAllocation SET  '' + @ColName + '''' 
	SET @sSql = @sSql + '' where EmployeeId in (select EmpId from TA_Tbl_TempShiftAllocation where LoginEmployeeId = ''+@loginEmployeeId+'')''
	SET @sSql = @sSql + '' and [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + ''''
	exec(@sSql)
	DECLARE @sSql1  varchar(8000)
	SET @sSql1 = ''UPDATE TA_Tbl_TemporaryShiftAllocation SET  '' + @ColName + '''' 
	SET @sSql1 = @sSql1 + '' where EmployeeId in (select EmpId from TA_Tbl_TempShiftAllocation where LoginEmployeeId = ''+@loginEmployeeId+'')''
	SET @sSql1 = @sSql1 + '' and [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + ''''
	exec(@sSql1)
	--select * from TA_Tbl_TempShiftAllocation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_ReligionDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_ReligionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_Update_ReligionDetails]        
(        
 @Name NVARCHAR(50),        
 @Description NVARCHAR(250),  
 @ID int  
)        
AS        
 BEGIN        
  declare @sql nvarchar(2000)    
  SET @sql=''UPDATE TA_Tbl_Religion SET Name =N'''''' +  @Name + '''''',Description=N'''''' + @Description + '''''' WHERE ID='' + cast(@ID as nvarchar(20)) + ''''    
  exec(@sql)    
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveMasterDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LeaveMasterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_Update_LeaveMasterDetails]    
(        
  @CompanyId INT,         
  @RegionId INT,        
  @BranchId INT,    
  @DepartmentId INT,    
  @SectionId INT,    
  @TitleId INT,  
  @LeaveType_Id INT,  
  @LOP  VARCHAR (25),    
 @id INT    
)         
As        
BEGIN        
 UPDATE TA_Tbl_LeaveMaster      
 SET        
    Company_Id =@CompanyId,        
    Region_Id = @RegionId,        
    Branch_Id = @BranchId,    
    Department_Id=@DepartmentId,    
    Section_Id=@SectionId,    
    Title_Id=@TitleId,   
    LeaveType_Id=@LeaveType_Id,  
    LOP=@LOP  
  WHERE Id=@Id    
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LastLogout]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LastLogout]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_Update_LastLogout [''emp102'',''hfhf'']
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Update_LastLogout]
	-- Add the parameters for the stored procedure here
	@UserName VARCHAR(2000)	 
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SET @Query=''UPDATE  TA_Tbl_Login SET LastLogoutTime=getdate() WHERE UserName IN (''''''+@UserName+'''''')''	
	EXEC (@Query) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Vehicle_Delete]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Vehicle_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE   PROCEDURE [dbo].[Proc_TA_Transportation_Vehicle_Delete]
@Type NVARCHAR(50),		
@Vehicles NVARCHAR(25),
@auditEmpId int
AS
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
DECLARE @DEL VARCHAR
DECLARE @RESTORE VARCHAR
SET @DEL=1
SET @RESTORE=0
IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Transportation_Vehicle SET IsDeleted= '' + @DEL + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE VehicleId IN (''+ @Vehicles +'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''PermanentDelete'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Transportation_Vehicle SET Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE VehicleId IN (''+ @Vehicles +'')''
		EXEC (@Query)
		SET @Query = ''''
		SET @Query = ''DELETE FROM TA_Tbl_Transportation_Vehicle WHERE VehicleId IN (''+ @Vehicles +'')''
		EXEC (@Query)
	END
ELSE IF (@Type=''Restore'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Transportation_Vehicle SET IsDeleted= '' + @RESTORE + '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE VehicleId IN (''+ @Vehicles +'')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Route_Delete]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Route_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified by	:	P.Prabakaran
Modified on	:	07-Feb-08
*/
CREATE   PROCEDURE [dbo].[Proc_TA_Transportation_Route_Delete]
@Type NVARCHAR(30),
@RouteIds NVARCHAR(50),
@auditEmpId int
AS
DECLARE @DEL VARCHAR
DECLARE @RESTORE VARCHAR
SET @DEL=1
SET @RESTORE=0
DECLARE @QUERY NVARCHAR(2000)
SET @QUERY=''''
IF (@Type=''TemporaryDelete'')
	BEGIN
		SET @QUERY=''UPDATE TA_Tbl_RouteMaster SET IsDeleted='' + @DEL +  '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE [Id] IN  ('' + @RouteIds + '')''
		EXEC (@QUERY)
	END
ELSE IF (@Type=''PermanentDelete'')
	BEGIN
		SET @QUERY=''UPDATE TA_Tbl_RouteMaster SET Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE [Id] IN  ('' + @RouteIds + '')''
		EXEC (@QUERY)
		SET @QUERY=''''
		SET @QUERY=''DELETE FROM TA_Tbl_RouteMaster WHERE [Id] IN  ('' + @RouteIds + '')''
		EXEC (@QUERY)
	END
ELSE IF (@Type=''Restore'')
	BEGIN
		SET @QUERY=''UPDATE TA_Tbl_RouteMaster SET IsDeleted='' + @RESTORE +  '', Emp_ID = ''+cast(@auditEmpId as nvarchar(20))+'' WHERE [Id] IN  ('' + @RouteIds + '')''
		EXEC (@QUERY)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAllocation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	Update the shift Id for shift re-allocation
-- Proc_TA_ShiftReAllocation ''Day1Shift=17,Day2Shift=17,Day3Shift=17,Day4Shift=17,Day5Shift=17,Day6Shift=17,Day7Shift=17,Day8Shift=17,Day9Shift=17,Day10Shift=17,Day11Shift=17,Day12Shift=17,Day13Shift=17,Day14Shift=17,Day15Shift=17'',2011,4,1,''<DocumentElement><Table><EmployeeAutoID>14594</EmployeeAutoID></Table></DocumentElement>''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAllocation]
(
@ColName varchar(3000),
@Year int,
@Month int,
@loginEmployeeId varchar(50),
@xml xml
)
AS
BEGIN
create table #Tempemployee (EmployeeAutoId bigint)
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
  insert into #Tempemployee select xm.EmployeeAutoID
  from OpenXML(@Index, ''/DocumentElement/Table'')
  With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
  Exec sp_xml_removedocument @Index
  DECLARE @sSql  varchar(8000)
  SET @sSql = ''UPDATE TA_Tbl_PermanentShiftAllocation SET  '' + @ColName + '''' 
  SET @sSql = @sSql + '' from TA_Tbl_PermanentShiftAllocation PS inner join #Tempemployee TE on TE.EmployeeAutoId = PS.EmployeeId ''
  SET @sSql = @sSql + '' where [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + ''''
  exec(@sSql)
  DECLARE @sSql1  varchar(8000)
  SET @sSql1 = ''UPDATE TA_Tbl_TemporaryShiftAllocation SET  '' + @ColName + '''' 
  SET @sSql1 = @sSql1 + '' from TA_Tbl_TemporaryShiftAllocation TS inner join  #Tempemployee TE on TE.EmployeeAutoId = TS.EmployeeId ''
  SET @sSql1 = @sSql1 + '' where [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + ''''
  exec(@sSql1)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDatatype]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDatatype]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDatatype] 
(
	@type CHAR(1),
	@TerminalDatatypeId INT=0,
	@UserGroupName nVarchar(100)
)
AS
BEGIN
	Declare @Common varchar(max)
	set @Common=''SELECT	TerminalDatatype_ID, Raw_Data_Format, FileType, File_SourcePath, File_BackupPath, File_BackupType, Delimiter_NoOfFields, Delimiter_Delimiter, 
				Delimiter_StringEnclosedBy, Delimiter_ReaderNo, Delimiter_CardNo, Delimiter_DateTimeBit, Delimiter_Date, Delimiter_Time, Delimiter_DateTime, 
				Delimiter_Type, Delimiter_TransactionIdentifier, FixedLength_ReaderNoFrom, FixedLength_ReaderNoTo, FixedLength_CardNoFrom, FixedLength_CardNoTo, 
				FixedLength_DateTimeBit, FixedLength_DateFrom, FixedLength_DateTo, FixedLength_TimeFrom, FixedLength_TimeTo, FixedLength_DateTimeFrom, 
				FixedLength_DateTimeTo, FixedLength_TypeFrom, FixedLength_TypeTo, FixedLength_TransactionIdentifierFrom, FixedLength_TransactionIdentifierTo, 
				ConnectionString, TableName, MDB_ReaderNo, MDB_CardNo, MDB_DateTimeBit, MDB_Date, MDB_Time, MDB_DateTime, MDB_Type, MDB_TransactionIdentifier, 
				RDBMS_ReaderNo, RDBMS_CardNo, RDBMS_DateTimeBit, RDBMS_Date, RDBMS_Time, RDBMS_DateTime, RDBMS_Type, RDBMS_TransactionIdentifier, RDBMS_MDB_Flag, 
				IsEmployeeId, DateTimeFormat, DateFormat, TimeFormat, IsEncrypted, TransactionIdentifierBit, TransactionIdentifierValue, Emp_Id, TimeStamp,
				case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted , isnull(IsFreeScan,0)IsFreeScan''
	IF @type=''A''
	BEGIN
		IF(@UserGroupName = ''SuperAdmin'') 
		BEGIN
			set @Common=@Common+ '' ,BrandId FROM TA_tbl_TerminalDatatype ''
		END 
		ELSE 
		BEGIN
			set @Common=@Common+ '' ,BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted = 0''
		END 
	END
	ELSE IF @type=''P''
	BEGIN
		IF(@UserGroupName = ''SuperAdmin'') 
		BEGIN
			set @Common=@Common+ '' ,TA_Tbl_TerminalBrand.DisplayName FROM TA_tbl_TerminalDatatype
			inner join TA_Tbl_TerminalBrand on TA_Tbl_TerminalBrand.BrandId=TA_tbl_TerminalDatatype.BrandId
			WHERE TerminalDatatype_ID=''+convert(varchar,@TerminalDatatypeId)
		END 
		ELSE 
		BEGIN
			set @Common=@Common+ '',TA_Tbl_TerminalBrand.DisplayName 
			FROM TA_tbl_TerminalDatatype 
			inner join TA_Tbl_TerminalBrand on TA_Tbl_TerminalBrand.BrandId=TA_tbl_TerminalDatatype.BrandId
			WHERE IsDeleted = 0 AND TerminalDatatype_ID=''+convert(varchar,@TerminalDatatypeId)
		END
	END
	Execute(@Common)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTempPayrollDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTempPayrollDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name : Proc_TA_SelectTempPayrollDetails 9,'''',''''
-- Purpose        : Used to select the payroll details from temporary table
-- Author         : Kumuthini.L
-- Created Date   : 18-May-09
CREATE PROCEDURE [dbo].[Proc_TA_SelectTempPayrollDetails]
(
   @MonthClosure_Id int,
   @EmpId Varchar(25),
   @EmployeeName Varchar(50)
)
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @Query AS VARCHAR(2000)
  SET @Query = ''''
  SET @Query = @Query + ''SELECT E.Employee_Code_Id,ISNULL(E.Employee_FirstName,'''''''') + Space(1) + ISNULL(E.Employee_LastName,'''''''') AS ''''EmployeeName'''',TPD.HrsWork,TPD.NormOT,TPD.OffOT,TPD.HolOT,TPD.LateIn,TPD.EarlyOut,TPD.PresentDays,TPD.LeaveDays,TPD.Holidays,TPD.AbsentDays,TPD.LOPDays,TPD.TotalPermissionHours FROM TA_Tbl_TempPayrollProcessDetails TPD ''  
  SET @Query = @Query + ''INNER JOIN TA_Tbl_Employee E ON TPD.Employee_Id = E.SwipeCardNo '' 
  SET @Query = @Query + ''WHERE TPD.MonthClosure_Id = '''''' + CAST(@MonthClosure_Id AS NVARCHAR(50)) + '''''' ''        
  IF NOT(@EmpId = '''')		
  BEGIN
     SET @Query = @Query + ''AND E.Employee_Code_Id = '''''' + CAST(@EmpId AS NVARCHAR(50)) + '''''' ''
  END
  IF NOT(@EmployeeName = '''')		
  BEGIN
     SET @Query = @Query + ''AND E.Employee_FirstName LIKE '''''' + CAST(@EmployeeName+''%'' AS NVARCHAR(100)) + '''''' ''
  END
  EXEC(@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftId]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporaryShiftId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftId] (@Employeecode varchar(15),@year varchar(5) ,@month varchar(5),@date varchar(2))
AS
DECLARE @Ssql NVARCHAR(2000)
SET @Ssql=''SELECT (psa.Day''+ @date + ''Shift)  from TA_Tbl_TemporaryShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + '' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''''' + @Employeecode +'''''' ''
EXEC(@Ssql)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporaryShiftForDate]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporaryShiftForDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================          
-- Author:  Prabakaran    Proc_TA_SelectTemporaryShiftForDate ''01/01/2009'',''174''  
-- Created  date:   
-- Description: Report Permanent Shift          
-- =============================================          
CREATE   PROCEDURE [dbo].[Proc_TA_SelectTemporaryShiftForDate]           
(          
 @fromDate datetime,  
 @EmployeeId varchar(50)
)          
AS          
BEGIN          
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''''    
 set @sqlQuery = @sqlQuery + '' SELECT  convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId ''       
 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation ''   
 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''          
exec(@sqlQuery)  
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectTemporarayShiftAllocationForDates  ''01/01/2009'',''01/03/2009'',''3''
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07    
*/  
CREATE     PROCEDURE [dbo].[Proc_TA_SelectTemporarayShiftAllocationForDates]  
 @fromDate datetime,  
 @toDate datetime,
 @EmployeeId varchar(50)   
AS  
BEGIN  
  declare @sqlQuery as nvarchar(4000)  
  set @sqlQuery=''''  
  create table #tblShiftDetails (ShiftDate datetime,ShiftId int,EmployeeId int)
while(@fromdate <= @toDate)
begin
	set @sqlQuery = @sqlQuery + '' SELECT  convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId ''     
 	set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation '' 
	set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''        
	set @fromdate=DateAdd(dd,1,@fromdate)
	INSERT INTO #tblShiftDetails exec(@sqlQuery)
set @sqlQuery=''''  
end
select convert(varchar,ShiftDate,101) as ShiftDate,ShiftId ,EmployeeId from #tblShiftDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTransportation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTransportation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectTransportation]
(
	@Type CHAR(1),
	@VehicleNo INT=0
)
AS
	DECLARE @Del BIT
	SET @Del=1
--Select All Title Records
	IF(@Type=''A'')
	 BEGIN 
		SELECT * FROM TA_UI_Transportation WHERE IsDeleted=@Del
	 END
--Select Title Records For CompanyName  Based on TitleId
	IF(@Type=''P'')
	 BEGIN 
		SELECT * FROM TA_UI_Transportation WHERE VehicleNo=@VehicleNo and  IsDeleted=@Del
--		SELECT A.Companyid,A.TitleID,A.titleName,A.TitleDescription,B.Company_Name,B.Company_Id
--		FROM TA_Tbl_Title A
--		INNER JOIN TA_Tbl_CompanyDetails B ON A.Companyid = B.Company_Id
---		WHERE A.titleid = @TitleId
	 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationView]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocationView]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_RptShiftAllocation ''12/17/2007'',''01/31/2008'','''','''','''' 
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By :Kumuthini.L
Created on : 3-Aug-07    
*/  
CREATE      PROCEDURE [dbo].[Proc_TA_ShiftAllocationView] 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(1000), 
 @EmployeeId varchar(50) 
AS  
BEGIN  
  declare @sqlQuery as nvarchar(4000)  
  set @sqlQuery=''''  
  set @sqlQuery = ''select  e.Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.UserId,ps.TimeStamp,ps.DateShift from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId where e.Isdeleted=1 and e.employee_Status=1 and e.Report_exclude=0 ''
  /*set @sqlQuery = @sqlQuery + '' and((month(dateShift) >= month(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102))) or (month(dateShift) <= month(CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102))))''  
  set @sqlQuery = @sqlQuery + '' and((year(dateShift) >= year(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102))) and (year(dateShift) <= year(CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102))))''  
    */
set @sqlQuery=@sqlQuery + '' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat as nvarchar(20)) +'''''', 102 ))as nvarchar(10)),102) ''
set @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102 ))as nvarchar(10)),102)''
if not(@LevelID='''' or @LevelID=''0'')  
  begin  
   set @sqlQuery = @sqlQuery + '' And (e.levelId IN ('' + @LevelID  + ''))''  
  End  
if not(@EmployeeName='''' or @EmployeeName=''0'')  
  begin  
   set @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''  
  end  
if not(@EmployeeId='''' or @EmployeeId=''0'')  
  begin  
   set @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
  end  
  set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,ps.Year,ps.Month''   
exec(@sqlQuery)  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateProcessedDataForService]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateProcessedDataForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateProcessedDataForService]
	-- Add the parameters for the stored procedure here
	@UpdateQuery nvarchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--RETRY: -- Label RETRY
	--BEGIN TRY
	--	BEGIN TRANSACTION		
	Execute(@updateQuery)
	--	COMMIT TRANSACTION
	--END TRY
	--BEGIN CATCH	
	--	ROLLBACK TRANSACTION
	--	IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
	--	BEGIN
	--		WAITFOR DELAY ''00:00:00.05'' -- Wait for 5 ms
	--		GOTO RETRY -- Go to Label RETRY
	--	END
	--END CATCH
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftAllocation]
(
    @Query nVarchar(Max)
)
 AS
BEGIN
      EXEC (@Query)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShift]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,28-November>
-- Description:	<Description,,Delete the Shifts for given period>
-- Proc_TA_UpdateShift ''Day21Shift'',185,2009,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShift](@ColName varchar(20),@EmpId int,@Year int,@Month int)
AS
BEGIN
	CREATE TABLE #TemShift( ShiftCount int )	
	DECLARE @count int
	DECLARE @sSql  nvarchar(200)
	DECLARE @notDeleted  nvarchar(2000)
	set @sSql=''SELECT COUNT(*) FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and EmployeeId='' + cast(@Empid as varchar(10)) + ''''
	INSERT INTO #TemShift EXEC(@sSql)	
	set @count=(SELECT ShiftCount from #TemShift)
	if(@count=0)
		BEGIN	
		SET @sSql=''UPDATE TA_Tbl_PermanentShiftAllocation SET  '' + @ColName + '' = 0 WHERE [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and EmployeeId='' + cast(@Empid as varchar(10)) + ''''
		SET @notDeleted = ''select '' + @ColName +'',  [Year], [Month], EmployeeId  from TA_Tbl_PermanentShiftAllocation where '' + @ColName + '' = 0 and EmployeeId='' + cast(@Empid as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and [Year]= '' + cast(@Year as varchar(10)) + '''' 
		EXEC(@sSql)
		EXEC(@notDeleted)
		END
	else
		BEGIN
--		SET @sSql=''UPDATE TA_Tbl_TemporaryShiftAllocation SET  '' + @ColName + '' = 0 WHERE [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and EmployeeId='' + cast(@Empid as varchar(10)) + ''''
--	
--		
--		EXEC(@sSql)
		SET @sSql=''UPDATE TA_Tbl_PermanentShiftAllocation SET  '' + @ColName + '' = 0 WHERE [Year]= '' + cast(@Year as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and EmployeeId='' + cast(@Empid as varchar(10)) + ''''
		SET @notDeleted = ''select '' + @ColName +'',  [Year], [Month], EmployeeId  from TA_Tbl_PermanentShiftAllocation where '' + @ColName + '' = 0 and EmployeeId='' + cast(@Empid as varchar(10)) + '' and [Month]='' + cast(@Month as varchar(10)) + '' and [Year]= '' + cast(@Year as varchar(10)) + '''' 
		EXEC(@sSql)
		EXEC(@notDeleted)
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateScheduleStatus]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateScheduleStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UpdateScheduleStatus]
(
	@ScheduleIds NVARCHAR(1000),
	@Type varchar(10)
)
AS	
BEGIN
	DECLARE @Query NVARCHAR(3000)
	SET @Query=''''
    if(@Type = ''Delete'')
		BEGIN
			--SET @Query = ''UPDATE TA_Tbl_EmailSchedule set IsDeleted = 1 WHERE ScheduleId IN  ('' + @ScheduleIds + '')''			
			SET @Query = ''DELETE FROM TA_Tbl_EmailScheduleFilters WHERE ScheduleId IN  ('' + @ScheduleIds + '')''			
			SET @Query = @Query+'';delete from ta_tbl_emailtemplate WHERE ScheduleId IN  ('' + @ScheduleIds + '')''
			SET @Query = @Query+'';delete from TA_tbl_MailIdsForTriggeringEmail WHERE ScheduleId IN  ('' + @ScheduleIds + '')''
			SET @Query = @Query+'';DELETE FROM TA_TBL_EMAILSCHEDULE WHERE ScheduleId IN  ('' + @ScheduleIds + '')''			
		END
	else if(@Type = ''Enable'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_EmailSchedule set Enabled = 1 WHERE ScheduleId IN  ('' + @ScheduleIds + '')''
		END
	else if(@Type = ''Disable'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_EmailSchedule set Enabled = 0 WHERE ScheduleId IN  ('' + @ScheduleIds + '')''
		END
	EXEC (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateInAndOutPunchDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Check whether the InTime lies inbetween any InTime and OutTime in the Clock Details Table for particular Employee>
-- [Proc_TA_UpdateInAndOutPunchDetails] 15241,''07/14/2016'',''04:00 PM'',''Out'',''ANNUAL COMPANY TOUR'',''59'','''',''M'',97739,''O'',1,''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateInAndOutPunchDetails]
	@inClk_DeviceId NVARCHAR(20),
	@inClk_Date NVARCHAR(20),
	@inClk_Time NVARCHAR(20),
	@inClk_Type NVARCHAR(20),
	@inClk_Remarks NVARCHAR(20),
	@inClk_User NVARCHAR(20),
	@gstrClockDate NVARCHAR(20),
	@inClk_Status NVARCHAR(20),
	@Clk_Id NVARCHAR(20),
	@Type char(1),
	@RecordFromClockdetails int,
	@strPunchTypeRemarksId NVARCHAR(max)
AS
BEGIN
	SET NOCOUNT ON;
    Declare @Dynamicsql NVARCHAR(max)
	set @Dynamicsql=''UPDATE TA_Tbl_ClockDetails SET ''
    if(@Type=''I'')
    begin
		set @Dynamicsql=@Dynamicsql+'' Clk_InDeviceId = ''''''+@inClk_DeviceId+'''''',Clk_InDate = convert(datetime,''''''+@inClk_Date+''''''),Clk_InTime = ''''''+@inClk_Time+'''''',Clk_InPunchType =N''''''+@inClk_Type+''''''''
		if (@inClk_Status = ''M'')
		begin
			set @Dynamicsql=@Dynamicsql+'',Clk_Remarks =N''''''+@inClk_Remarks +'''''' ,Clk_User = N''''''+@inClk_User + ''''''''
		end
		set @Dynamicsql=@Dynamicsql+'',Clk_Date =convert(datetime,''''''+@gstrClockDate+''''''),Clk_Status =''''''+@inClk_Status +'''''' WHERE Clk_Id = ''''''+@Clk_Id + ''''''''
	end
	else
	begin
		set @Dynamicsql=@Dynamicsql+'' Clk_OutDeviceId = ''''''+@inClk_DeviceId+'''''',Clk_OutDate = convert(datetime,''''''+@inClk_Date+''''''),Clk_OutTime = ''''''+@inClk_Time+'''''',Clk_OutPunchType = N''''''+@inClk_Type+'''''',Clk_Status =N''''''+@inClk_Status+''''''''
		if (@inClk_Status = ''M'') 
		begin                                
			set @Dynamicsql=@Dynamicsql+'',Clk_Remarks = N''''''+@inClk_Remarks+'''''',Clk_User = N''''''+@inClk_User+'''''',PunchType_Remarks =''''''''''
		end                            
		if (@RecordFromClockdetails = 1)
		begin
			set @Dynamicsql=@Dynamicsql+'',Clk_Remarks ='''''''',PunchType_Remarks = N''''''+@strPunchTypeRemarksId + ''''''''
		end
		set @Dynamicsql=@Dynamicsql+'' WHERE Clk_Id = '''''' + @Clk_Id +''''''''
	end
	Execute(@Dynamicsql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplication]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplication]  
(
	--Proc_TA_UpdateLeaveApplication   45,0,'''',0,'''','''','''','''','''',1.0,''''
	@LeaveApplication_Id int,
	@EmployeeID int,
	@Leave_ApplicationDate datetime,
	@LeaveType_id int,
	@Type nvarchar(20),
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@Leave_SessionFrom nvarchar(20),
	@Leave_SessionTo nvarchar(20),
	@NumberOfDays decimal(8,2),
	@Reason nvarchar(50) 
)  
as  
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(2000)
	set @sql=''''
	set @sql= @sql + ''UPDATE TA_Tbl_LeaveApplication SET LeaveType_id='''''' + cast(@LeaveType_id as nvarchar(20)) + '''''',Type= N'''''' 
	set @sql= @sql + @Type + '''''',Leave_FromDate= '''''' + cast(@Leave_FromDate as nvarchar(20)) + '''''',Leave_ToDate= '''''' + cast(@Leave_ToDate as nvarchar(20))
	set @sql= @sql + '''''',Leave_SessionFrom=N'''''' + @Leave_SessionFrom + '''''',Leave_SessionTo=N'''''' + @Leave_SessionTo + '''''',NumberOfDays=''''''set @sql= @sql + cast(@NumberOfDays as nvarchar(10)) + '''''',Reason=N'''''' + @Reason + '''''' WHERE LeaveApplication_Id = '' + cast(@LeaveApplication_Id  as nvarchar(10))
	exec(@sql)  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateFlagInDeviceDatabase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Updating flag in device database>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateFlagInDeviceDatabase]
	-- Add the parameters for the stored procedure here
	@TableName varchar(max),
	@FlagName varchar(50),
	@nIndex bigint
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DynamicQuery varchar(max)=''''
	set @DynamicQuery= ''UPDATE ''+convert(varchar(max),@TableName) + '' SET '' + convert(varchar(50),@FlagName) + '' = 1 WHERE nIndex='' + convert(varchar(max),@nindex)
	Execute(@DynamicQuery)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ViewLeavePolicyDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ViewLeavePolicyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
-- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: 29 June 2007  
-- Description: Leave policy - select  
-- Modified By : Kumuthini.L
-- Modified On : 06-Feb-2008
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Modified by	:	Manikandan.R
Modified on	:	15-Oct-11
Description	:	Year closure changes
-- =============================================  
*/
CREATE PROCEDURE [dbo].[Proc_TA_ViewLeavePolicyDetails]
 -- Add the parameters for the stored procedure here  
 @Type CHAR(1)='''',  
-- @Policy_Id INT=0,  
 @UserGroupName nVarchar(250),
 @EmployeeCategory NVARCHAR(50)=NULL,
 @EmployeeType NVARCHAR(50)=NULL,
 @Gender NVARCHAR(10)=NULL,
 @Religion NVARCHAR(50)=NULL  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
  DECLARE @SQL NVARCHAR(MAX)
IF (@Type=''A'')  
   BEGIN  
    IF(@UserGroupName = ''SuperAdmin'')  
       BEGIN     
		SET @SQL=''SELECT *,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
              (select Name from TA_Tbl_Religion where ID=Religion)as Religions FROM TA_Tbl_LeavePolicy 
	          WHERE IsDeleted=0 ''   
       END
    ELSE       
       BEGIN
			SET @SQL=''=SELECT *,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
              (select Name from TA_Tbl_Religion where ID=Religion)as Religions FROM TA_Tbl_LeavePolicy WHERE IsDeleted=0 ''
       END    
   END
ELSE IF (@Type=''P'')     
     BEGIN  
			IF(@UserGroupName = ''SuperAdmin'')
                BEGIN
					-- New Code on 16-Feb-08, Based on Policy Year field removed from TA_Tbl_LeavePolicy
						SET @SQL=''SELECT *, getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions  
  					FROM TA_Tbl_LeavePolicy  
        			WHERE IsDeleted=0 ''
                END
           ELSE
               BEGIN
				-- New Code 16-Feb-08,Based on Policy Year field removed from TA_Tbl_LeavePolicy
					SET @SQL=''SELECT *,getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions  
					FROM TA_Tbl_LeavePolicy  
					WHERE IsDeleted=0 ''
               END
			IF @EmployeeCategory<>'''' AND @EmployeeCategory IS NOT NULL
				BEGIN
					SET @SQL=@SQL + '' AND EmployeeCategory=''+@EmployeeCategory 
				END
			IF @EmployeeType<>'''' AND @EmployeeType IS NOT NULL 
				BEGIN
					SET @SQL=@SQL + '' AND EmployeeType=''+@EmployeeType
				END
			IF @Gender <>'''' AND @Gender IS NOT NULL
				BEGIN
					SET @SQL=@SQL + '' AND Gender=''''''+@Gender+'''''''' 
				END
			if @Religion<>'''' AND @Religion IS NOT NULL
				BEGIN
					SET @SQL=@SQL + '' AND Religion=''+@Religion 
				END
			SET @SQL=@SQL + '' ORDER BY Policy_Id''
			EXEC(@SQL)
    END  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation_Route]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_Transportation_Route]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_Update_TA_TBL_Transportation_Route]    
(  
  @LevelId INT,  
  @VehicleID INT,	
  @RouteName NVARCHAR(50),    
  @RouteDescription NVARCHAR(250),
  @EmpID  INT,  
  @RouteId INT    
)     
As    
declare @sql as nvarchar(3000)
BEGIN    
 --UPDATE TA_Tbl_RouteMaster SET Level_Id=@LevelId, VehicleID=@VehicleID, Route_Name = @RouteName, Route_Description =@RouteDescription, Emp_ID=@EmpID, Time_stamp=getdate() WHERE [Id]=@RouteId 
 set @sql = ''UPDATE TA_Tbl_RouteMaster SET Level_Id=''+cast(@LevelId as nvarchar(25))+'', VehicleID=''+cast(@VehicleID as nvarchar(25))+'', Route_Name = N''''''+@RouteName+'''''', Route_Description =N''''''+@RouteDescription+'''''', Emp_ID=''+cast(@EmpID as nvarchar(25))+'', Time_stamp=''''''+cast(getdate() as nvarchar(25))+'''''' WHERE [Id]=''+cast(@RouteId as nvarchar(25))+''''
 exec(@sql)
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationVehicle]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TransportationVehicle]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified By	:	P.Prabakaran
Modified on	:	7-Feb-08
*/
CREATE  Procedure [dbo].[Proc_Update_TA_TBL_TransportationVehicle]
(
	@VehicleNo NVARCHAR(50),
	@VehicleDescription NVARCHAR(250),
	@VehicleId int,
	@EmpID INT
) 
As
declare @sql as nvarchar(3000)
BEGIN
	--UPDATE TA_Tbl_Transportation_Vehicle SET VehicleNo = @VehicleNo,VehicleDescription =@VehicleDescription,Time_Stamp=getdate(),Emp_ID=@EmpID WHERE VehicleId=@VehicleId
    set @sql = ''UPDATE TA_Tbl_Transportation_Vehicle SET VehicleNo = N''''''+@VehicleNo+'''''',VehicleDescription =N''''''+@VehicleDescription+'''''',Time_Stamp=''''''+cast(getdate() as nvarchar(25))+'''''',Emp_ID=''+cast(@EmpID as nvarchar(25))+'' WHERE VehicleId=''+cast(@VehicleId as nvarchar(25))+''''
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[ReducePermissionHoursFromTotalHours]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReducePermissionHoursFromTotalHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ReducePermissionHoursFromTotalHours]
	@dtmPermissionFromDateTime datetime,
	@dtmPermissionToDateTime datetime,
	@dtmShiftEndTime datetime,
	@dtmFirstInDateTime datetime,
	@dtmLastOutDateTime datetime,
	@No_Of_Hours varchar(10)
AS
BEGIN
	SET NOCOUNT ON;
	if (@dtmShiftEndTime >= @dtmPermissionFromDateTime and @dtmShiftEndTime <= @dtmPermissionToDateTime)
	Begin
		if (@dtmLastOutDateTime > @dtmPermissionFromDateTime)
		Begin
			select DATEDIFF(minute,@dtmFirstInDateTime,@dtmPermissionFromDateTime)as dTotalMinsWorked
		End
		else if (@dtmLastOutDateTime >= @dtmFirstInDateTime)
		begin
			select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
		End
	End
	else if (@dtmFirstInDateTime >= @dtmPermissionFromDateTime and @dtmFirstInDateTime <= @dtmPermissionToDateTime)
	begin
		set @dtmFirstInDateTime = @dtmPermissionToDateTime
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
	end
	else if (@dtmPermissionFromDateTime >= @dtmFirstInDateTime and @dtmPermissionToDateTime <= @dtmLastOutDateTime)
	begin
		Declare @permissionMinutes int
		set @permissionMinutes=SUBSTRING(@No_Of_Hours,0,CHARINDEX('':'',@No_Of_Hours))*60+SUBSTRING(@No_Of_Hours,CHARINDEX('':'',@No_Of_Hours)+1,LEN(@No_Of_Hours))
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)-@permissionMinutes as dTotalMinsWorked
	end
    else if (@dtmLastOutDateTime >= @dtmFirstInDateTime)
    begin
		select DATEDIFF(minute,@dtmFirstInDateTime,@dtmLastOutDateTime)as dTotalMinsWorked
	end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTempShiftAlloc]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateTempShiftAlloc]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_UpdateTempShiftAlloc]
(
@EmployeeID int,
@ShiftID int,
@date int,
@month int,
@year int,
@EmpID int,
@Timestamp nvarchar,
@DateShift nvarchar
)
as
Begin
declare @query nvarchar(2000)
set @query=''Update TA_Tbl_TemporaryShiftAllocation set Day'' + cast(@date as nvarchar) +''Shift= '' + cast(@ShiftID as nvarchar) + '',[Emp_Id]='' + cast(@EmpID as nvarchar) + ''Where EmployeeId='' + cast(@EmployeeID as nvarchar)+ '' And [Year]='' + cast(@year as nvarchar) + '' And [Month]='' + cast(@month  as nvarchar)
exec (@query)
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateLeavePolicyByFilters]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateLeavePolicyByFilters]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <29-Oct-2011>
-- Description:	<To Validate the selected Leave Policy is related to selected Items>
-- =============================================
--Proc_TA_ValidateLeavePolicyByFilters 1,1,''Female'',43,97
CREATE PROCEDURE [dbo].[Proc_TA_ValidateLeavePolicyByFilters] 
	@EmployeeCategory int,
	@EmployeeType int,
	@Gender varchar(20),
	@Religion int,
	@LeavePolicyId int
AS
BEGIN
	SET NOCOUNT ON;
	declare @Query nvarchar(4000)
    set @Query=''''
    set @Query= @Query + '' select count(*) from TA_Tbl_LeavePolicy LP''
    set @Query= @Query + '' where Policy_Id=''+ cast(@LeavePolicyId  as varchar(20)) +'' ''
	if(@EmployeeCategory <> 0)
	begin
	 set @Query= @Query + '' and (LP.EmployeeCategory = '' + cast(@EmployeeCategory as varchar(20)) + '' or LP.EmployeeCategory =0)''
	end
	if(@EmployeeType <>0)
		begin
			set @Query= @Query + '' and (LP.EmployeeType = ''+ cast(@EmployeeType as varchar(20)) +'' or LP.EmployeeType =0)''
		end
	if(@Gender = ''Male'' or @Gender =''Female'')
		begin
			set @Query= @Query + '' and (LP.Gender = '''''' + @Gender + '''''' or LP.Gender =''''Both'''') ''
		end	
	if(@Religion <> 0)
		begin
			set @Query= @Query + '' and (LP.Religion = '' + cast(@Religion as varchar(20)) + '' or LP.Religion =0)''
		end	
	exec(@Query)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_userRightsInsert]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_userRightsInsert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- Create date: 11 Aug 2007
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_userRightsInsert] 
(
--[Proc_TA_userRightsInsert] ''12'',''1'','''',''1'','''',''1'',''''
	@groupId nvarchar(45),
	@pageId int,
	@pageGroupId int,
	@addPrv bit,
	@modifyPrv bit,
	@deletePrv bit,
	@viewPrv bit,
    @employeeId decimal
)
AS
declare @sql nvarchar(2000)    
set @sql=''''   
BEGIN
		declare @recordCount as int
declare @query nvarchar(1000)
set @query = (''select count(*) as recordCount from TA_Tbl_userRights where groupId= N'''''' + @groupId + '''''' and pageId='''''' + cast(@pageId as nvarchar) + '''''''')
create table #temp (reccount int)
insert into #temp exec(@query)
set @recordCount =  (select * from #temp)
		if (@recordCount=0)
			begin
				set @sql = @sql + ''insert into TA_Tbl_userRights (groupId,pageId,pageGroupId,addPrv,modifyPrv,deletePrv,viewPrv,employeeId) values ( N'''''' + @groupId + '''''', '''''' + cast(@pageId as nvarchar) + '''''','''''' + cast(@pageGroupId as nvarchar) + '''''', '''''' + cast(@addPrv as nvarchar) + '''''','''''' + cast(@modifyPrv as nvarchar) + '''''' , '''''' + cast(@deletePrv as nvarchar) + '''''','''''' + cast(@viewPrv as nvarchar) + '''''',''''''+cast(@employeeId as nvarchar)+'''''')''
exec(@sql)
			end
		else
			begin
				set @sql = @sql + ''update ta_tbl_userRights set addPrv='''''' + cast(@addPrv as nvarchar) + '''''',modifyPrv='''''' + cast(@modifyPrv as nvarchar) + '''''',deletePrv= '''''' + cast(@deletePrv as nvarchar) + '''''',viewPrv= '''''' + cast(@viewPrv as nvarchar) + '''''',employeeId=''''''+cast(@employeeId as nvarchar)+'''''' where groupId= N'''''' + @groupId + '''''' and pageId=  '''''' + cast(@pageId as nvarchar) + ''''''''
exec(@sql)				
			end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleFirst]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TitleFirst]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified By		:  Manjula.P  
Modified On		:  06-Jan-2014
Descriptions	:  Adding @LevelId param for leveldetails in designation
*/
CREATE Procedure [dbo].[Proc_Update_TA_TBL_TitleFirst]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(250),
	@LevelID INT,
	@PolicyID INT,
	@GradeID INT,
	@EmpID INT,
	@TitleId INT
) 
As
declare @sql as nvarchar(3000)
BEGIN
	set @sql = ''UPDATE TA_Tbl_Title SET TitleName=N''''''+@TitleName+'''''',TitleDescription=N''''''+@TitleDescription+'''''',LevelID=''+cast(@LevelID as nvarchar(25))+'',LeavePolicyID=''+cast(@PolicyID as nvarchar(25))+'',GradeID=''+cast(@GradeID as nvarchar(25))+'',Emp_Id=''+cast(@EmpID as nvarchar(25))+'',Time_Stamp=getdate() WHERE TitleId=''+cast(@TitleId as nvarchar(25))+''''
	--set @sql = ''UPDATE TA_Tbl_Title SET TitleName=N''''''+@TitleName+'''''',TitleDescription=N''''''+@TitleDescription+'''''',LeavePolicyID=''+cast(@PolicyID as nvarchar(25))+'',GradeID=''+cast(@GradeID as nvarchar(25))+'',Emp_Id=''+cast(@EmpID as nvarchar(25))+'',Time_Stamp=getdate() WHERE TitleId=''+cast(@TitleId as nvarchar(25))+''''
   exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftRoaster]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftRoaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftRoaster]
(@levelId int,@RoasterId int,@RoasterName nvarchar(25),@NoOfPatterns int,@Pattern1 int,@Pattern2 int,@Pattern3 int,@Pattern4 int,
 @Pattern5 int,@Pattern6 int,@Pattern7 int,@Pattern8 int,@Pattern9 int,@Pattern10 int,@Employee_Id int)
 AS
declare @sql as nvarchar(3000)
	BEGIN
--		UPDATE TA_Tbl_ShiftRoaster SET ShiftRoaster_Name=@RoasterName,NumberOfPatterns=@NoOfPatterns,Pattern1=@Pattern1,Pattern2=@Pattern2,Pattern3=@Pattern3,Pattern4=@Pattern4,			
--			   Pattern5=@Pattern5,Pattern6=@Pattern6,Pattern7=@Pattern7,Pattern8=@Pattern8,Pattern9=@Pattern9,Pattern10=@Pattern10,Emp_Id=@Employee_Id WHERE ShiftRoaster_Id=@RoasterId
       set @sql =''UPDATE TA_Tbl_ShiftRoaster SET Level_Id=''+cast(@levelId as nvarchar(25))+'',ShiftRoaster_Name=N''''''+@RoasterName+'''''',NumberOfPatterns=''+cast(@NoOfPatterns as nvarchar(25))+'',Pattern1=''+cast(@Pattern1 as nvarchar(25))+'',Pattern2=''+cast(@Pattern2 as nvarchar(25))+'',Pattern3=''+cast(@Pattern3 as nvarchar(25))+'',Pattern4=''+cast(@Pattern4 as nvarchar(25))+'',
                                                 Pattern5=''+cast(@Pattern5 as nvarchar(25))+'',Pattern6=''+cast(@Pattern6 as nvarchar(25))+'',Pattern7=''+cast(@Pattern7 as nvarchar(25))+'',Pattern8=''+cast(@Pattern8 as nvarchar(25))+'',Pattern9=''+cast(@Pattern9 as nvarchar(25))+'',Pattern10=''+cast(@Pattern10 as nvarchar(25))+'',Emp_Id=''+cast(@Employee_Id as nvarchar(25))+'' WHERE ShiftRoaster_Id=''+cast(@RoasterId as nvarchar(25))+''''
       exec(@sql)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_UpdatingData_PunchesNotAvailed 2,1,'''',''Absent'',''Absent'',''Absent'',''07:30'',''09:30 AM'',''06:00 PM'','''',1,0,'''',''240835''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingData_PunchesNotAvailed]
	-- Add the parameters for the stored procedure here		
	@intShiftId int,
	@dblTotalDays bigint,
	@strLeaveCode varchar(20),
	@gstrAttendance varchar(20),
	@strFNAttendanceCode varchar(20),
	@strANAttendanceCode varchar(20),
	@strWorkHrs varchar(10),
	@ActualShfInTime varchar(20),
	@ActualShfOutTime varchar(20),
	@HolidayDescription varchar(max),
	@intYearSettingId int,
	@Variation bigint,
	@No_Of_Hours varchar(20),
	@inProcess_Rec_ID bigint
AS
BEGIN		
	SET NOCOUNT ON;
	Declare @strSQLProcessUpdate varchar(max)
	set @strSQLProcessUpdate=''''
	set @strSQLProcessUpdate=@strSQLProcessUpdate+''
	UPDATE TA_Tbl_ProcessedData SET
				--Employee_Code_Id
				--Date
				Shift_Id = '' + convert(varchar(10),@intShiftId) + '',
				Shift_StartTime = '''''' + CONVERT(varchar(10),@ActualShfInTime) + '''''',
				Shift_EndTime = '''''' + convert(varchar(10),@ActualShfOutTime) + '''''',
				WorkHrs = ''''''+ convert(varchar(10),@strWorkHrs) + '''''',
				InTime = ''''00:00'''',
				OutTime = ''''00:00'''',
				BreakHrs = ''''00:00'''',
				LunchHrs = ''''00:00'''',
				PermissionHrs = '''''' + Convert(varchar(20),@No_Of_Hours) + '''''',
				HrsWork = ''''00:00'''',
				Attendance ='''''' + CONVERT(varchar(10),@gstrAttendance) +'''''',
				HrsOT=''''00:00'''',
				NormOT=''''00:00'''',
				OffOT=''''00:00'''',
				HolOT=''''00:00'''',
				OvertimeStatus=NULL,
				HrsLess = ''''00:00'''',
				HrsExtra=''''00:00'''',
				LateIn=''''00:00'''',
				EarlyOut=''''00:00'''',
				BreakHrsInMins = ''''0'''',
				LunchHrsInMins = ''''0'''',
				PermissionHrsInMins= '''''' + CONVERT(varchar(10),@Variation) + '''''',
				HoursWorkInMins = 0,
				----WorkHoursInMins
				----LessHoursInMins
				LateInMins=0,
				EarlyOutMins=0,
				ExtraMins=0,
				OtMins=0,
				LateExit = 0,
				EarlyEntry = 0,
				----InNotation
				----OutNotation
				TotalDays = '' + convert(varchar(10),@dblTotalDays) + '',
				LeaveCode = '''''' + convert(varchar(10),@strLeaveCode) + '''''',
				----LateEntryReason
				----EarlyOutReason
				Status = NULL,
				IsOnduty=0,
				FNAttendanceCode=''''''+ CONVERT(varchar(10),@strFNAttendanceCode) +'''''',
				ANAttendanceCode=''''''+ CONVERT(varchar(10),@strANAttendanceCode) +'''''',
				ProcessFlag = 1,				
				--LeaveStatus
				--PermissionStatus
				NormOtmins=0,
				OffOtmins=0,
				HolOtMins=0,
				----CLAvailed
				YearSettingId = '''''' + convert(varchar(10),@intYearSettingId) + '''''',
				----LeaveType_Id
				Holiday_Description='''''' + CONVERT(varchar(10),@HolidayDescription) + '''''',
				EarlyInmins=0,
				EarlyInHrs=''''00:00'''',
				lateExitMins=0,
				LateExitHours=''''00:00'''',
				ActNormOTMins=0,
				ActOffOTMins=0,
				ActHolOTMins=0,
				ActOTMins=0,
				ActHrsOT=''''00:00'''',
				ActNormOT=''''00:00'''',
				ActOffOT=''''00:00'''',
				ActHolOT=''''00:00'''',
				Inpunch=NULL,
				Outpunch=NULL,
				Indate=NULL,
				Outdate=NULL				
				WHERE Process_Rec_ID = '' + convert(varchar(10), @inProcess_Rec_ID )
	RETRY:
	BEGIN TRANSACTION
	BEGIN TRY	
		execute(@strSQLProcessUpdate)
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH	
		ROLLBACK TRANSACTION
		IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
		BEGIN
			WAITFOR DELAY ''00:00:00.05'' -- Wait for 5 ms
			GOTO RETRY -- Go to Label RETRY
		END
	END CATCH	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserAccessRights_MobileApp]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UserAccessRights_MobileApp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UserAccessRights_MobileApp]
	@userName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Declare @Defined_Users varchar(max)
	--set @Defined_Users=''581'',''2'',''7'',''12'',''787'',''758''
    -- Insert statements for procedure here
    if(@userName in(''581'',''2'',''7'',''12'',''787'',''758''))
    begin
		select 1 as eligible
    end
    else
    begin
		select 0 as eligible
    end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingSMSTemplateStaus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <27-08-2016>
-- Description:	<Activate and deactivate Templates>
-- [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]''2,3,4,5,6,7,8,9,10,11'',''Disable'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingSMSTemplateStaus]
	-- Add the parameters for the stored procedure here
	@TemplateIds varchar(max),
	@Status varchar(10),
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Declare @DynamicSQL varchar(max)
	set @DynamicSQL =''''
	set @DynamicSQL =@DynamicSQL+''update Ta_Tbl_SMSTemplates set Status=case when ''''''+CONVERT(varchar(10), @status)+''''''=''''Enable'''' then 1 else 0 end, 
	ModifiedBy=''+CONVERT(varchar(10),@EmployeeID)+'' where id in(''+CONVERT(varchar(max),@TemplateIds)+'')''
	Execute(@DynamicSQL)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManual]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupManual]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created by		:	Manjula.P
Created Date	:	05-Aug-2014
Descriptions	:	for selecting employees based on his shift date and shift name to put group manual entry
Proc_TA_SelectEmployeeForGroupManual 2014,8,6,1
*/
CREATE procedure [dbo].[Proc_TA_SelectEmployeeForGroupManual]
(
 @year VARCHAR(5),
 @month VARCHAR(5),
 @date VARCHAR(5),
 @shiftid bigint
)
as
begin
	DECLARE @query VARCHAR(2000)   
	CREATE TABLE #TempShift
	(
	Employee_Id bigint,
	Employee_Code_Id nvarchar(250),
	[Employee Name] nvarchar(500)
	)
	set @query='' SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''' '''') AS ''''Employee Name''''		from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp 
	where psa.[Year]= ''+@year+'' and psa.[Month]= ''+@month+'' and psa.EmployeeId = emp.Employee_Id and emp.Isdeleted=0 and emp.Employee_Status=1 ''
	if(@shiftid>0)
	begin
	 set @query=@query+'' and (psa.Day''+@date+''Shift)=''+cast(@shiftid as varchar(50))+''  ''
	end
	insert into #TempShift
	exec(@query)
	select * from #TempShift
	drop table #TempShift
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter] 0,2,''Both'',0  select * from ta_tbl_leavetype
CREATE Proc [dbo].[Proc_TA_SelectLeavePolicyDetailsBasedOnFilter]
(    
    @EmployeeCategory varchar(50)=null,
    @EmployeeType varchar(50)=null,
    @Gender varchar(10)=null,
    @Religion varchar(20)=null)
AS      
 DECLARE @SQL NVARCHAR(MAX)
			SET @SQL=''SELECT Policy_Id, PolicyName FROM TA_Tbl_LeavePolicy where isDeleted=0 ''
		IF @EmployeeCategory is not null
			begin
				if @EmployeeCategory=0
					begin
						set @SQL= @SQL+ '' and (EmployeeCategory in (select EmployeeCategory from TA_Tbl_LeavePolicy) or EmployeeCategory=0)''
					end
				else
					begin
						set @SQL= @SQL+ '' and (EmployeeCategory='' +CONVERT(varchar(10),@EmployeeCategory) +'' or EmployeeCategory=0)'' 
					end
			end
		IF  @EmployeeType is not null
			if @EmployeeType=0
				begin
					set @SQL= @SQL+ '' and (EmployeeType in (select EmployeeType from TA_Tbl_LeavePolicy) or EmployeeType=0)''
				end
			else			
				begin
					set @SQL= @SQL+ '' and (EmployeeType='' +CONVERT(varchar(10),@EmployeeType)+'' or EmployeeType=0)'' 
				end
		IF  @Gender is not null
			begin
				if @Gender=''Both''
					begin
						set @SQL= @SQL + '' and (Gender=''''Female'''' or Gender=''''Male'''' or Gender=''''Both'''')''
					end
				else
					begin
						set @SQL= @SQL + '' and (Gender=''''''+CONVERT(varchar(10),@gender)+'''''' or Gender=''''Both'''')''
					end
			end
		IF  @Religion is not null-- and @Religion<>0
			IF @Religion=0
				begin
					set @SQL= @SQL + '' and (Religion in(select Religion from TA_Tbl_LeavePolicy) or Religion=0)''
				end
			else
				begin
					set @SQL= @SQL + '' and (Religion=''+CONVERT(varchar(10),@Religion)+'' or Religion=0)''
				end			
			set @SQL= @SQL+ '' order by Policy_Id''
			execute(@sql)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <27-10-2011>
-- Description:	<Loading the Leave policy for selected Religion,Employee Category,Employee type and gender>
-- Proc_TA_SelectLeavePolicyforEmployeeFilters 1,1,''Male'',43
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyforEmployeeFilters] 
	-- Add the parameters for the stored procedure here
	--@EmployeeCategory  int,
	--@EmployeeType int,
	@loginEmployeeId varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @Query nvarchar(4000)
    set @Query=''''
    set @Query= @Query + ''select * from TA_Tbl_TempGroupPolicyAllocation where 1=1  and LoginEmployeeId=''+@loginEmployeeId
	exec(@Query)
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords_YearClosure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure ''1,2,3,47,113,133,134,135,137,138,140,150'',''1/1/2009'',''05/08/2009'',''''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Manjula          
-- Date    : 28-Jan-2014          
-- Update History :   [Date Updated By (Initials) Reason]   
--	Proc_TA_SelectLICPendingForwardedRecords_YearClosure 1,1       
/****************************************************************************************/ 
@OrgLevelId int=0,
@Year_SettingID int=0       
as  
	create table #tblProcessLeave(intCount bigint)
	declare @gintLeaveCount bigint
	declare @sqlQuery as varchar(8000)
	declare @Result as varchar(1000) 
	set @sqlQuery=''''  
	set @sqlQuery = ''select isnull( Count(*),0) as Count from TA_TBL_LeaveApplication ''  
	set @sqlQuery = @sqlQuery + '' Where IsDeleted=0 and Status IN (''''Forwarded'''',''''Pending'''') and companyId=''+CAST( @OrgLevelId as varchar)+'' and YearSettings_Id=''+CAST( @Year_SettingID as varchar)+'''' 
	insert into  #tblProcessLeave exec(@sqlQuery)
	set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
	set @Result=''Pending or Forwarded Records for ''
	if(@gintLeaveCount>0)
	begin	
		set @Result=@Result + '' Leave ''
	end
	set @Result=@Result + ''Exists,Close them before Save the Year Closure''
	if( @gintLeaveCount>0)
	begin
	set @Result=@Result
	end
	else
	begin
	set @Result=''''
	end
	select @Result as Result
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLICPendingForwardedRecords]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLICPendingForwardedRecords]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_SelectLICPendingForwardedRecords]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure ''1,2,3,47,113,133,134,135,137,138,140,150'',''1/1/2009'',''05/08/2009'',''''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
as  
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000)  
declare @Result as varchar(1000) 
  set @sqlQuery=''''  
  set @sqlQuery = ''select Count(*) as Count from TA_TBL_LeaveApplication ''  
  set @sqlQuery = @sqlQuery + '' Where IsDeleted=0 and Status IN (''''Forwarded'''',''''Pending'''')'' 
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
  set @sqlQuery1=''''  
  set @sqlQuery1 = ''select Count(*) as Count from TA_TBL_ManualTimeEntry ''  
  set @sqlQuery1 = @sqlQuery1 + ''where IsDeleted=0 and ManualTimeEntry_Status IN (''''Forwarded'''',''''Pending'''') '' 
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''''  
  set @sqlQuery2 = ''select Count(*) as Count from TA_TBL_ProcessedData ''  
  set @sqlQuery2 = @sqlQuery2 + '' where OvertimeStatus IN (''''Forwarded'''',''''Pending'''')'' 
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
--  set @sqlQuery3=''''  
--  set @sqlQuery3 = ''select Count(*) as Count from TA_TBL_Employee E ''  
--  set @sqlQuery3 = @sqlQuery3 + '' inner join TA_TBL_Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId ''  
--  set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
--  set @sqlQuery3 = @sqlQuery3 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
--  set @sqlQuery3 = @sqlQuery3 + '' AND E.Isdeleted=0''  
--  set @sqlQuery3 = @sqlQuery3 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
--  set @sqlQuery3 = @sqlQuery3 + '' and crd.Clk_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
--  set @sqlQuery3 = @sqlQuery3 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
--  set @sqlQuery3 = @sqlQuery3 + '' and (crd.Clk_Flag =0 or crd.Clk_Process =0)'' 
--
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery3 = @sqlQuery3 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
--
--insert into  #tblProcessRaw exec(@sqlQuery3)
--set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''''  
set @sqlQuery4 = ''select Count(*) as Count from TA_TBL_Permission ''  
set @sqlQuery4 = @sqlQuery4 + '' where IsDeleted=0 and Permission_Status IN (''''Forwarded'''',''''Pending'''')''  
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=''Pending or Forwarded Records for ''
--if(@gintRawCount>0)
--	begin
--	
--	set @Result=@Result + '' Device ''
--	
--	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + '',''
	end
set @Result=@Result + ''Over Time ''
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + '',''
			end
		set @Result=@Result + '' Leave ''
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + '',''
					end
		set @Result=@Result + '' Permission ''
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + '',''
							end
		set @Result=@Result + '' Manual Entry ''
	end
set @Result=@Result + ''Exists,Close them before updating new license''
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''''
end
select @Result as Result
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftForDate]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentShiftForDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================        
-- Author:  Prabakaran    Proc_TA_SelectPermanentShiftForDate ''01/07/2009'',''174''
-- Created  date: 
-- Description: Report Permanent Shift        
-- =============================================        
CREATE   PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftForDate]         
(        
 @fromDate datetime,
 @EmployeeId varchar(50)    
)        
AS        
BEGIN        
  declare @sqlQuery as varchar(8000)
  set @sqlQuery = ''''  
 set @sqlQuery = @sqlQuery + '' SELECT  convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId ''     
 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_PermanentShiftAllocation '' 
 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''        
exec(@sqlQuery)
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name : Proc_TA_SelectPermanentShiftAllocationForDates  ''01/01/2009'',''01/03/2009'',''3''  
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation    
Created By : Prabakaran    
Created on : 3-Aug-07      
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPermanentShiftAllocationForDates]    
 @fromDate datetime,    
 @toDate datetime,  
 @EmployeeId varchar(50)     
AS    
BEGIN    
  declare @sqlQuery as nvarchar(4000)    
  set @sqlQuery=''''    
  create table #tblTempShiftDetails (ShiftDate datetime,ShiftId int,EmployeeId int)  
while(@fromdate <= @toDate)  
begin  
 set @sqlQuery = @sqlQuery + '' SELECT  convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101)  as ShiftDate ,  dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId ''       
  set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_PermanentShiftAllocation ''   
 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''          
 set @fromdate=DateAdd(dd,1,@fromdate)  
 INSERT INTO #tblTempShiftDetails exec(@sqlQuery)  
set @sqlQuery=''''    
end  
select convert(varchar,ShiftDate,101) as ShiftDate,ShiftId ,EmployeeId from #tblTempShiftDetails  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================          
-- Author:  Prabakaran    Proc_TA_SelectTemporaryShiftForDate ''01/01/2009'',''174''  
-- Created  date:   
-- Description: Report Permanent Shift          
-- =============================================   
--Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate ''07/07/2009'',''07/07/2009'',''483''       
CREATE PROCEDURE [dbo].[Proc_TA_SelectPermanentAndTemporaryShiftFromAndToDate]           
(          
 @fromDate datetime,  
 @toDate datetime,
 @EmployeeId varchar(50)
)          
AS          
BEGIN          
	 create table #TempShiftData(P_FromShiftDate varchar(20),P_FromShiftId varchar(20),P_ToShiftDate varchar(20),P_ToShiftId varchar(20),T_FromShiftDate varchar(20),T_FromShiftId varchar(20),T_ToShiftDate varchar(20),T_ToShiftId varchar(20),EmployeeId varchar(30))
	 declare @sqlQuery as varchar(8000)  
	 set @sqlQuery = ''''    
	 set @sqlQuery = @sqlQuery + '' insert into #TempShiftData(EmployeeId) SELECT ''+ @EmployeeId +''''     
	 exec(@sqlQuery)
	  set @sqlQuery = '''' 
	 set @sqlQuery = @sqlQuery + '' update #TempShiftData set P_FromShiftDate = convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101),P_FromShiftId = dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift ''     
	 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_PermanentShiftAllocation '' 
	 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''        
	 exec(@sqlQuery)
	 set @sqlQuery = '''' 
	 set @sqlQuery = @sqlQuery + '' update #TempShiftData set P_ToShiftDate = convert(varchar,CONVERT(datetime,'''''' + cast(@toDate as nvarchar(50))  + '''''', 101),101),P_ToShiftId = dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@toDate) as nvarchar(10)) + ''Shift ''     
	 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_PermanentShiftAllocation '' 
	 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@toDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@toDate) as nvarchar(10)) + '')''        
	 exec(@sqlQuery)
	 set @sqlQuery = '''' 
	 set @sqlQuery = @sqlQuery + '' update #TempShiftData set T_FromShiftDate = convert(varchar,CONVERT(datetime,'''''' + cast(@fromDate as nvarchar(50))  + '''''', 101),101),T_FromShiftId = dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift ''     
	 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation '' 
	 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''        
	 exec(@sqlQuery)
	 set @sqlQuery = '''' 
	 set @sqlQuery = @sqlQuery + '' update #TempShiftData set T_ToShiftDate = convert(varchar,CONVERT(datetime,'''''' + cast(@toDate as nvarchar(50))  + '''''', 101),101),T_ToShiftId = dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@toDate) as nvarchar(10)) + ''Shift ''     
	 set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation '' 
	 set @sqlQuery = @sqlQuery + '' WHERE  dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId='' + @EmployeeId + '' and (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@toDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@toDate) as nvarchar(10)) + '')''        
	 exec(@sqlQuery)
	 select * from #TempShiftData
	 drop table #TempShiftData
END   
--select * from TA_Tbl_PermanentShiftAllocation
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'create PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByOverTime]
AS
Begin
declare @TableID as int
set @TableID =(select id from sysobjects where name=''TA_TBL_PayrollProcessDetails'')
	DECLARE @version as nvarchar(50)
		SET @version = ''''
		SET @version = (SELECT left(@@version,26))
		if (@version=''Microsoft SQL Server  2000'')
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4 and c.Name in (''HrsOT'',''Employee_Id'')
--			union 
--
--			select ''12345'',''OT_Type'',''OT Type''
			END
		else
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0 and c.Name in (''HrsOT'',''Employee_Id'')			
--				union 
--				select ''12345'',''OT_Type'',''OT Type''
			END		
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNamesByAttandance]
AS
Begin
declare @TableID as int
set @TableID =(select id from sysobjects where name=''TA_TBL_PayrollProcessDetails'')
	DECLARE @version as nvarchar(50)
		SET @version = ''''
		SET @version = (SELECT left(@@version,26))
		if (@version=''Microsoft SQL Server  2000'')
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4 and c.Name in (''AbsentDays'',''Employee_Id'')
--			union 
--
--			select ''12345'',''OT_Type'',''OT Type''
			END
		else
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0 and c.Name in (''AbsentDays'',''Employee_Id'')			
--				union 
--				select ''12345'',''AttendanceCode'',''Attendance Code''
			END		
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftAllocationDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftAllocationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,27-Nov-07>
-- Description:	<Description,,Select ShiftIds for the given period and selected employees>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftAllocationDetails](@Empid varchar(100),@Year varchar(100),@Month varchar(100))
AS
BEGIN
CREATE TABLE #TemShift( ShiftCount int )	
DECLARE @count int
DECLARE @sSql  nvarchar(200)
	set @sSql=''SELECT COUNT(*) FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year] IN ( '' + @Year + '') and [Month] IN ('' + @Month + '')  and EmployeeId IN ('' + @Empid + '')''
	INSERT INTO #TemShift EXEC(@sSql)	
	set @count=(SELECT ShiftCount from #TemShift)
	IF(@count<>0)
		BEGIN
			set @sSql=''SELECT * FROM TA_Tbl_TemporaryShiftAllocation WHERE [Year] IN ( '' + @Year + '') and [Month] IN ('' + @Month + '')  and EmployeeId IN ('' + @Empid + '')''
			EXEC(@sSql)
		END
	ELSE
		BEGIN
			SET @sSql=''SELECT  * FROM TA_Tbl_PermanentShiftAllocation WHERE [Year] IN ( '' + @Year + '') and [Month] IN ('' + @Month + '')  and EmployeeId IN ('' + @Empid + '')''
			EXEC(@sSql)
		END	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId_Group]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftId_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name  : Proc_TA_SelectShiftId_Group
-- Tables Used	   : TA_Tbl_TemporaryShiftAllocation,TA_Tbl_PermanentShiftAllocation,TA_Tbl_Employee
-- Purpose         : This Procedure is used to get the Shift Id for a group of employees either from Temporary or Permanent Shift Allocation   
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftId_Group] 
(
   @year VARCHAR(5),
   @month VARCHAR(5),
   @date VARCHAR(5),
   @xml xml
)  
AS
BEGIN 
	DECLARE @query VARCHAR(2000)   
	CREATE TABLE #Temp(EmployeeAutoId INT,ShiftID int)
	 Declare @Index int
	 Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into #Temp (EmployeeAutoId)
		  select xm.EmpID
		  from OpenXML(@Index, ''/NewDataSet/Table'')
		  With (EmpID Bigint ''EmpID'') as xm
	  Exec sp_xml_removedocument @Index
	SET @query = ''update #Temp set #Temp.ShiftID = (tsa.Day''+ @date + ''Shift)  from TA_Tbl_TemporaryShiftAllocation tsa inner join #Temp on #Temp.EmployeeAutoId = tsa.EmployeeId where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + ''''  
	EXEC(@query)
	SET @query = ''update #Temp set #Temp.ShiftID = (psa.Day''+ @date + ''Shift)  from TA_Tbl_PermanentShiftAllocation psa inner join #Temp on #Temp.EmployeeAutoId = psa.EmployeeId and (#Temp.ShiftId is null or #Temp.ShiftId=0) where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + ''''  
	EXEC(@query)
	update #Temp set ShiftID=0 where ShiftID is null
	select EmployeeAutoId from #Temp where ShiftID=0
	DROP TABLE #Temp
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Thilakraj>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForSelectedEmployee] ''3,6'',''2013'',''5'',''14''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForSelectedEmployee]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(max),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000) 
	declare @query1 varchar(2000)
	DECLARE @query2 VARCHAR(2000) 
	DECLARE @query3 VARCHAR(2000) 
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	SET @query = ''SELECT (tsa.Day''+ @date + ''Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation
				   tsa
				where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
				tsa.EmployeeId in ( ''+ @Employeecode +'' )'' 
	INSERT INTO #Temp 
	EXEC(@query)
	Select * from #Temp	
	Delete from #Temp	
	SET @query1 = ''SELECT (tsa.Day''+ @date + ''Shift) AS ShiftId from 
	TA_Tbl_PermanentShiftAllocation tsa
	where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
	tsa.EmployeeId  in( ''+ @Employeecode +'' )''  
	INSERT INTO #Temp
	EXEC(@query1)
	Select * from #Temp	
	Delete from #Temp
	SET @query2 = ''SELECT distinct((tsa.Day''+ @date + ''Shift)) AS ShiftId from 
	TA_Tbl_TemporaryShiftAllocation tsa
	where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
	tsa.EmployeeId  in( ''+ @Employeecode +'' )''
	INSERT INTO #Temp 
	EXEC(@query2)
	Select * from #Temp	
	Delete from #Temp
	SET @query3= ''SELECT  distinct((tsa.Day''+ @date + ''Shift)) AS ShiftId from 
	TA_Tbl_PermanentShiftAllocation tsa
	where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
	tsa.EmployeeId in( ''+ @Employeecode +'' )''
	INSERT INTO #Temp
	EXEC(@query3)
	Select * from #Temp	
	Delete from #Temp
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEditUpdated]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OrgEditUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_OrgEditUpdated]  1, ''1,2,3''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OrgEditUpdated]
(
		@lid int,
		@LevelIDs nvarchar(1000)
)
AS
BEGIN
	declare @Query as varchar(7000)
	set @Query = ''DECLARE @lelid int, @lelName varchar(30)''
	set @Query =  @Query + '' SET @lelName = (SELECT name FROM ta_tbl_levelDetails WHERE id ='' + cast(@lid as nvarchar(20))  + '' and  id in ('' + @LevelIDs + ''))''
	set @Query =  @Query + '' INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES ('' + cast(@lid as nvarchar(20)) + '',@lelName)''
	set @Query =  @Query + '' SET @lelid = (SELECT parentID FROM ta_tbl_levelDetails WHERE id = '' + cast(@lid as nvarchar(20)) + '')''
	set @Query =  @Query + '' if (@lelid >0)''
	set @Query =  @Query + '' BEGIN''
	set @Query =  @Query + '' EXEC dbo.Proc_TA_OrgEdit @lelid ,'' + @LevelIDs
	set @Query =  @Query + '' END''
exec (@Query)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NonProcessedDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_NonProcessedDataDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 09-07-2014
-- Description:	To show the unprocessed data record details
-- ==========================================================================================
--ALTER PROCEDURE [dbo].[Proc_Ta_NonProcessedDataDetails]
--	-- Add the parameters for the stored procedure here	
--AS
--BEGIN
--	-- SET NOCOUNT ON added to prevent extra result sets from
--	-- interfering with SELECT statements.
--	SET NOCOUNT ON;
--    -- Insert statements for procedure here
--    --Employee Details
--	SELECT CLK_CARDID ,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData C
--	--inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=1
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	--and E.Isdeleted=0 and (E.InActiveDate is null or E.InActiveDate<=CLK_DATE)
--	group by CLK_CARDID order by CLK_CARDID 
--	--Terminal Details
--	SELECT CLK_DEVICEID,TotalRecords=count(convert(int,CLK_DEVICEID)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=2
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_DEVICEID order by CLK_DEVICEID
--	--Shift not allocated Employee details
--	SELECT CLK_CARDID,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=3
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_CARDID order by CLK_CARDID 	
--	--Punch types not created device details
--	SELECT CLK_DEVICEID,CLK_TYPE,TotalRecords=count(convert(int,CLK_TYPE)) from TA_Tbl_Clk_RawData 
--	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=4
--	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
--	group by CLK_DEVICEID,CLK_TYPE order by CLK_DEVICEID ,CLK_TYPE
--END
CREATE PROCEDURE [dbo].[Proc_Ta_NonProcessedDataDetails]
	-- Add the parameters for the stored procedure here	
	@FROMDATE datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @FromdateString varchar(20)
	if @FROMDATE!=''''
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(varchar(20),DATEPART(month,@fromdate))+''-''+
			case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,@fromdate))
			else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
		Declare @Query1 nvarchar(4000)
		Declare @Query2 nvarchar(4000)
		Declare @Query3 nvarchar(4000)
		Declare @Query4 nvarchar(4000)
    -- Insert statements for procedure here
    --Employee Details
	set @Query1 = '' SELECT CLK_CARDID ,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData C
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=1
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) ''
	if(@fromdate!='''')
		begin
		set @Query1 =@Query1 +	'' and CLK_DATE <=  CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) ''
		end
	set @Query1 =@Query1 + '' group by CLK_CARDID order by CLK_CARDID ''
	execute (@Query1)
	--Terminal Details
	 set @Query2 = '' SELECT CLK_DEVICEID,TotalRecords=count(convert(int,CLK_DEVICEID)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=2
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) ''
	if(@fromdate!='''')
		begin
		set @Query2 =@Query2 +	'' and CLK_DATE <=  CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) ''
		end
	set @Query2 =@Query2 + '' group by CLK_DEVICEID order by CLK_DEVICEID ''
	execute (@Query2)
	--Shift not allocated Employee details
	set @Query3 = '' SELECT CLK_CARDID,TotalRecords=count(convert(int,CLK_CARDID)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=3
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) ''
	if(@fromdate!='''')
		begin
		set @Query3 =@Query3 +	'' and CLK_DATE <=  CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) ''
		end
	set @Query3 =@Query3 + '' group by CLK_CARDID order by CLK_CARDID ''
	execute (@Query3)
	--Punch types not created device details
	set @Query4 = '' SELECT CLK_DEVICEID,CLK_TYPE,TotalRecords=count(convert(int,CLK_TYPE)) from TA_Tbl_Clk_RawData 
	where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId=4
	and CLK_DATE>=(select FromDate from TA_Tbl_YearSetting where IsActive=1) ''
	if(@fromdate!='''')
		begin
		set @Query4 =@Query4 +	'' and CLK_DATE <=  CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) ''
		end
	set @Query4 =@Query4 + '' group by CLK_DEVICEID,CLK_TYPE order by CLK_DEVICEID ,CLK_TYPE ''
	execute (@Query4)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUser]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutUser] 
	-- Add the parameters for the stored procedure here
	(@ConcurrentUserId varchar(1000))
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		SET @Query=''DELETE TA_Tbl_ConcurrentUser WHERE ConcurrentUserId in ('' + @ConcurrentUserId + '')''
EXEC (@Query) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateMusterRoll]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertUpdateMusterRoll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_InsertUpdateMusterRoll ''787'',''2014-10-15'',''Present'',''Present'',10,10,10
---- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertUpdateMusterRoll]
	-- Add the parameters for the stored procedure here
	@Employeecodeid VARCHAR(50),
	@Date DATETIME,
	@FNAttendance VARCHAR(50),
	@ANAttendance VARCHAR(50),
	@LateInMins INT,
	@EarlyOutMins INT,
	@OTMins INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @SQLInsert VARCHAR(MAX)
	DECLARE @SQLUpdate VARCHAR(MAX)
	DECLARE @SQLDate VARCHAR(MAX)
	DECLARE @SQLMonth int
	DECLARE @SQLYear int
	set @SQLMonth=DATEPART(M,@Date)
	set @SQLYear=DATEPART(YEAR,@Date)	
	set @SQLDate=DATEPART(d,@Date)
	set @SQLInsert=''Insert into musterRoll(Employeecodeid,Month,Year,TotalEarlyExit,TotalLateEntry,TotalExtraHours''
	set @SQLUpdate=''Update musterRoll set ''
    -- Insert statements for procedure here
	IF EXISTS(SELECT * FROM musterRoll WHERE MONTH=@SQLMonth AND YEAR=@SQLYear AND Employeecodeid=@Employeecodeid)
		BEGIN
			set @SQLUpdate=@SQLUpdate+''FNDay''+ @SQLDate + ''=''''''+SUBSTRING(@FNAttendance,0,2)+'''''',''
			set @SQLUpdate=@SQLUpdate+''ANDay''+ @SQLDate + ''=''''''+SUBSTRING(@ANAttendance,0,2)+''''''''
			set @SQLUpdate=@SQLUpdate+'' WHERE MONTH=''''''+convert(varchar(10),@SQLMonth) +'''''' AND YEAR=''''''+convert(varchar(10),@SQLYear) +'''''' AND Employeecodeid=''''''+@Employeecodeid+''''''''
			select @SQLUpdate
			execute (@SQLUpdate)
		END
	ELSE
		BEGIN
			set @SQLInsert=@SQLInsert+'',FNDay''+ @SQLDate + '',ANDay''+ @SQLDate + '') values(''+@Employeecodeid+'',''+convert(varchar(20),@SQLMonth)+'',''+
			convert(varchar(10),@SQLYear)+'',''+
			ISNULL(convert(varchar(10),@EarlyOutMins),''0'')+'',''+ISNULL(convert(Varchar(20),@LateInMins),''0'')+'',''+convert(varchar(10),@OTMins)+'',''''''+SUBSTRING(@FNAttendance,0,2)+'''''',''''''+SUBSTRING(@ANAttendance,0,2)+'''''')''
			select @SQLInsert
			execute (@SQLInsert)
		END	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation]
(
   @EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nvarchar(15),
   @DateShift nvarchar(15)
)
 AS
BEGIN
declare @sql nvarchar(3000)
	set @sql=''INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES ('''''' + cast(@EmpId as nvarchar(25)) + '''''','''''' + cast(@Year as nvarchar(50)) + '''''','''''' + cast(@Month as nvarchar(50)) + '''''','''''' + cast(@UserId as nvarchar(50)) + '''''',N'''''' + @EntryDate + '''''',N'''''' + @DateShift + '''''')''
Exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftRoaster]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftRoaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,30-June-2007>
-- Description:	<Description,,Inserting Shift Pattern>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftRoaster]
(@companyId int,@RoasterName nvarchar(25),@NoOfPatterns int,@Pattern1 int,@Pattern2 int,@Pattern3 int,@Pattern4 int,
 @Pattern5 int,@Pattern6 int,@Pattern7 int,@Pattern8 int,@Pattern9 int,@Pattern10 int,@Employee_Id int)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
--	INSERT INTO TA_Tbl_ShiftRoaster(ShiftRoaster_Name,NumberOfPatterns,Pattern1,Pattern2,Pattern3,Pattern4,Pattern5 ,Pattern6,Pattern7,Pattern8,
--								Pattern9,Pattern10,Emp_Id,Isdeleted) VALUES (@RoasterName,
--								@NoOfPatterns,@Pattern1,@Pattern2,@Pattern3,@Pattern4,@Pattern5,@Pattern6,@Pattern7,
--								@Pattern8,@Pattern9,@Pattern10,@Employee_Id,@Isdel)
    set @sql = ''INSERT INTO TA_Tbl_ShiftRoaster(Level_Id,ShiftRoaster_Name,NumberOfPatterns,Pattern1,Pattern2,Pattern3,Pattern4,Pattern5 ,Pattern6,Pattern7,Pattern8,Pattern9,Pattern10,Emp_Id,Isdeleted) 
                VALUES(''+cast(@companyId as nvarchar(25))+'',N''''''+@RoasterName+'''''',''+cast(@NoOfPatterns as nvarchar(25))+'',''+cast(@Pattern1 as nvarchar(25))+'',''+cast(@Pattern2 as nvarchar(25))+'',''+cast(@Pattern3 as nvarchar(25))+'',
                       ''+cast(@Pattern4 as nvarchar(25))+'',''+cast(@Pattern5 as nvarchar(25))+'',''+cast(@Pattern6 as nvarchar(25))+'',''+cast(@Pattern7 as nvarchar(25))+'',''+cast(@Pattern8 as nvarchar(25))+'',
                       ''+cast(@Pattern9 as nvarchar(25))+'',''+cast(@Pattern10 as nvarchar(25))+'',''+cast(@Employee_Id as nvarchar(25))+'',''+cast(@Isdel as nvarchar(25))+'')''
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftPattern]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- ALTER  date: <Create Date,,30-June-2007>
-- Description:	<Description,,Inserting Shift Roaster>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftPattern]
(@companyId int,@PatternName nvarchar(50),@Nodays int,@Day1_ShiftId int,@Day2_ShiftId int,@Day3_ShiftId int,@Day4_ShiftId int,
 @Day5_ShiftId int,@Day6_ShiftId int,@Day7_ShiftId int,@Day8_ShiftId int,@Day9_ShiftId int,@Day10_ShiftId int,@Day11_ShiftId int,@Day12_ShiftId int,
 @Day13_ShiftId int,@Day14_ShiftId int,@Day15_ShiftId int,@Day16_ShiftId int,@Day17_ShiftId int,@Day18_ShiftId int,@Day19_ShiftId int,@Day20_ShiftId int,
 @Day21_ShiftId int,@Day22_ShiftId int,@Day23_ShiftId int,@Day24_ShiftId int,@Day25_ShiftId int,@Day26_ShiftId int,@Day27_ShiftId int,@Day28_ShiftId int,
 @Day29_ShiftId int,@Day30_ShiftId int,@Day31_ShiftId int,@Employee_Id int)
AS
DECLARE @Isdel int
declare @sql as nvarchar(3000)
SET @Isdel=0
BEGIN
--	INSERT INTO TA_Tbl_ShiftPattern(Pattern_Name,Shift_days,Day1_Shift,Day2_Shift,Day3_Shift,Day4_Shift,Day5_Shift ,Day6_Shift,Day7_Shift,Day8_Shift,
--								Day9_Shift,Day10_Shift,Day11_Shift,Day12_Shift,Day13_Shift,Day14_Shift,Day15_Shift,Day16_Shift,Day17_Shift,
--								Day18_Shift,Day19_Shift,Day20_Shift,Day21_Shift,Day22_Shift,Day23_Shift,Day24_Shift,Day25_Shift,Day26_Shift,
--								Day27_Shift,Day28_Shift,Day29_Shift,Day30_Shift,Day31_Shift,Emp_Id,Isdeleted) VALUES (@PatternName,
--								@Nodays,@Day1_ShiftId,@Day2_ShiftId,@Day3_ShiftId,@Day4_ShiftId,@Day5_ShiftId,@Day6_ShiftId,@Day7_ShiftId,
--								@Day8_ShiftId,@Day9_ShiftId,@Day10_ShiftId,@Day11_ShiftId,@Day12_ShiftId,@Day13_ShiftId,@Day14_ShiftId,	
--								@Day15_ShiftId,@Day16_ShiftId,@Day17_ShiftId,@Day18_ShiftId,@Day19_ShiftId,@Day20_ShiftId,@Day21_ShiftId,
--								@Day22_ShiftId,@Day23_ShiftId,@Day24_ShiftId,@Day25_ShiftId,@Day26_ShiftId,@Day27_ShiftId,@Day28_ShiftId,
--								@Day29_ShiftId,@Day30_ShiftId,@Day31_ShiftId,@Employee_Id,@Isdel)
set @sql = ''INSERT INTO TA_Tbl_ShiftPattern(Level_Id,Pattern_Name,Shift_days,Day1_Shift,Day2_Shift,Day3_Shift,Day4_Shift,Day5_Shift ,Day6_Shift,Day7_Shift,Day8_Shift,
                                            Day9_Shift,Day10_Shift,Day11_Shift,Day12_Shift,Day13_Shift,Day14_Shift,Day15_Shift,Day16_Shift,Day17_Shift,
                                            Day18_Shift,Day19_Shift,Day20_Shift,Day21_Shift,Day22_Shift,Day23_Shift,Day24_Shift,Day25_Shift,Day26_Shift,
                                            Day27_Shift,Day28_Shift,Day29_Shift,Day30_Shift,Day31_Shift,Emp_Id,Isdeleted)
                                            VALUES(''+cast(@companyId as nvarchar(25))+'',N''''''+@PatternName+'''''',''+cast(@Nodays as nvarchar(25))+'',''+cast(@Day1_ShiftId as nvarchar(25))+'',''+cast(@Day2_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day3_ShiftId as nvarchar(25))+'',''+cast(@Day4_ShiftId as nvarchar(25))+'',''+cast(@Day5_ShiftId as nvarchar(25))+'',''+cast(@Day6_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day7_ShiftId as nvarchar(25))+'',''+cast(@Day8_ShiftId as nvarchar(25))+'',''+cast(@Day9_ShiftId as nvarchar(25))+'',''+cast(@Day10_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day11_ShiftId as nvarchar(25))+'',''+cast(@Day12_ShiftId as nvarchar(25))+'',''+cast(@Day13_ShiftId as nvarchar(25))+'',''+cast(@Day14_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day15_ShiftId as nvarchar(25))+'',''+cast(@Day16_ShiftId as nvarchar(25))+'',''+cast(@Day17_ShiftId as nvarchar(25))+'',''+cast(@Day18_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day19_ShiftId as nvarchar(25))+'',''+cast(@Day20_ShiftId as nvarchar(25))+'',''+cast(@Day21_ShiftId as nvarchar(25))+'',''+cast(@Day22_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day23_ShiftId as nvarchar(25))+'',''+cast(@Day24_ShiftId as nvarchar(25))+'',''+cast(@Day25_ShiftId as nvarchar(25))+'',''+cast(@Day26_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day27_ShiftId as nvarchar(25))+'',''+cast(@Day28_ShiftId as nvarchar(25))+'',''+cast(@Day29_ShiftId as nvarchar(25))+'',''+cast(@Day30_ShiftId as nvarchar(25))+'',
                                            ''+cast(@Day31_ShiftId as nvarchar(25))+'',''+cast(@Employee_Id as nvarchar(25))+'',''+cast(@Isdel as nvarchar(25))+'')''
exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSpousedetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSpousedetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_InsertSpousedetails] 
(
	@EmpID INT=0,
	@spousename NVARCHAR(50),
	@spousedob NVARCHAR(15),
	@EmployeeID INT=0
)
AS
BEGIN
	declare @sql as nvarchar(3000)
	IF (@spousedob='''')
	BEGIN
		SET @spousedob=NULL
	END
	set @sql = ''INSERT INTO TA_Tbl_EmpChildrenDetails(Emp_ID,Spouse_Child,Name,DOB,Isdeleted,Employee_ID) 
	VALUES (''+cast(@EmpID as nvarchar(25))+'',''''S'''',N''''''+@spousename+'''''',N''''''+@spousedob+'''''',0,''+cast(@EmployeeID as nvarchar(25))+'')''
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompanyDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertCompanyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertCompanyDetails]
(@Type char(1),@CompanyId int=0,@CompanyName nvarchar(50),@CompanyDescription nvarchar(255),@CompanyAddress1 nvarchar(255), @CompanyAddress2 nvarchar(255),@CompanyPhone1 nvarchar(15),@CompanyPhone2 nvarchar(15),@CompanyFax1 nvarchar(15),
  @CompanyFax2 nvarchar(15),@CompanyEmail nvarchar(75),@CompanyWebaddress nvarchar(75),@Companylogo image)
as
DECLARE @Isdel int,@Count int
SET @Isdel=1
--Insert Method
if(@Type=''I'')
Begin  
   select @Count=count(*) FROM TA_Tbl_CompanyDetails WHERE Company_Name=@CompanyName  and IsDeleted=@Isdel 
  if(@Count=0)
  BEGIN
     INSERT INTO TA_Tbl_CompanyDetails(Company_Name,Company_Description,Company_Address1,Company_Address2,Company_Phone1,Company_Phone2,Company_Fax1,Company_Fax2,Company_Email,Company_WebAddress,Company_Logo,IsDeleted)
   VALUES(@CompanyName,@CompanyDescription,@CompanyAddress1, @CompanyAddress2,@CompanyPhone1,@CompanyPhone2,@CompanyFax1,@CompanyFax2,@CompanyEmail,@CompanyWebaddress,@Companylogo,@Isdel)
   END   						
end
--Update Method
if(@Type=''U'')
   BEGIN
   UPDATE TA_Tbl_CompanyDetails SET Company_Name=@CompanyName,Company_Description=@CompanyDescription,Company_Address1=@CompanyAddress1,Company_Address2=@CompanyAddress2,Company_Phone1=@CompanyPhone1,Company_Phone2=@CompanyPhone2,
   Company_Fax1=@CompanyFax1,Company_Fax2=@CompanyFax2,Company_Email=@CompanyEmail,Company_WebAddress=@CompanyWebaddress,Company_Logo=@Companylogo WHERE Company_Id=@CompanyId
   END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertChildrendetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertChildrendetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_InsertChildrendetails] 
(
@EmpID INT=0,
@childrenname NVARCHAR(50),
@childrendob NVARCHAR(15),
@EmployeeID INT=0
)
AS
BEGIN
	declare @sql as nvarchar(3000) 
	IF (@childrendob='''')
	BEGIN
		SET @childrendob=NULL
	END
	set @sql = ''INSERT INTO TA_Tbl_EmpChildrenDetails(Emp_ID,Spouse_Child,Name,DOB,Isdeleted,Employee_ID) 
	VALUES (''+cast(@EmpID as nvarchar(25))+'',''''C'''',N''''''+@childrenname+'''''',N''''''+@childrendob+'''''',0,''+cast(@EmployeeID as nvarchar(25))+'')''
    exec(@sql) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationMaster]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAllocationMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Abul:
this proc will insert the shift pattern master details in the TA_Tbl_ShiftAllocation table
*/
CREATE Proc [dbo].[Proc_TA_InsertAllocationMaster]
@ShiftPattern_Id int,
@From_Date datetime,
@To_Date datetime
As
Insert Into TA_Tbl_ShiftAllocation(ShiftPattern_Id, From_Date, To_Date) 
values(@ShiftPattern_Id, @From_Date, @To_Date);
Select @@IDENTITY as ''Identity''
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAllocationChild]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAllocationChild]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Abul:
this proc will insert the shift pattern transaction details in the TA_Tbl_ShiftAllocationDetails table
*/
Create Proc [dbo].[Proc_TA_InsertAllocationChild]
@ShiftAllocation_Id int,
@Employee_Id int,
@Starting_Day int
As
Insert Into TA_Tbl_ShiftAllocationDetails(ShiftAllocation_Id, Employee_Id, Starting_Day)
values(@ShiftAllocation_Id, @Employee_Id, @Starting_Day)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_RouteDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation_RouteDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation_RouteDetails]  
(  
	@LevelId INT,
	@VehicleID INT,
	@RouteName NVARCHAR(50),  
	@RouteDescription NVARCHAR(250),
	@EmpID INT
)  
AS  
declare @sql as nvarchar(3000)
DECLARE @Isdeleted BIT
SET @Isdeleted=0
SET NOCOUNT ON  
 BEGIN  
  --INSERT INTO TA_Tbl_RouteMaster(Level_Id,VehicleID,Route_Name,Route_Description,Emp_ID,Isdeleted)  VALUES(@LevelId,@VehicleID,@RouteName,@RouteDescription,@EmpID,@Isdeleted)  
  set @sql = ''INSERT INTO TA_Tbl_RouteMaster(Level_Id,VehicleID,Route_Name,Route_Description,Emp_ID,Isdeleted)  VALUES(''+cast(@LevelId as nvarchar(25))+'',''+cast(@VehicleID as nvarchar(25))+'',N''''''+@RouteName+'''''',N''''''+@RouteDescription+'''''',''+cast(@EmpID as nvarchar(25))+'',''+cast(@Isdeleted as nvarchar(25))+'')''
  exec(@sql)
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationVehicleDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TransportationVehicleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_TransportationVehicleDetails]
(
	@VehicleNo NVARCHAR(50),
	@VehicleDescription NVARCHAR(250),
	@EmpID INT 
)
AS
declare @sql as nvarchar(3000)
DECLARE @Isdeleted BIT
SET @Isdeleted=0
SET NOCOUNT ON
	BEGIN
		--INSERT INTO TA_Tbl_Transportation_Vehicle(VehicleNo,VehicleDescription,Emp_ID,IsDeleted) VALUES(@VehicleNo,@VehicleDescription,@EmpID,@Isdeleted)
        set @sql = ''INSERT INTO TA_Tbl_Transportation_Vehicle(VehicleNo,VehicleDescription,Emp_ID,IsDeleted) VALUES(N''''''+@VehicleNo+'''''',N''''''+@VehicleDescription+'''''',''+cast(@EmpID as nvarchar(25))+'',''+cast(@Isdeleted as nvarchar(25))+'')''
        exec(@sql)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveMasterDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveMasterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveMasterDetails]      
(        
 @CompanyId INT,         
 @RegionId INT,        
 @BranchId INT,        
 @DepartmentId INT,        
 @SectionId INT,        
 @TitleId INT,      
 @LeaveType_Id INT,      
 @LOP Varchar(20)    
)        
AS        
SET NOCOUNT ON        
 BEGIN        
  INSERT INTO TA_Tbl_LeaveMaster      
  (        
    Company_Id,Region_Id,Branch_Id,Department_Id,Section_Id,Title_Id,LeaveType_Id,LOP       
  )        
         VALUES         
  (         
   @CompanyId,@RegionId,@BranchId,@DepartmentId,@SectionId,@TitleId,@LeaveType_Id,@LOP            
 )      
 END    ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TitleFirstDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TitleFirstDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	06-Jan-2014
Descriptions	:	Adding @LevelId parameter for getting organization based designation
*/
CREATE PROCEDURE [dbo].[Proc_TA_Insert_TitleFirstDetails]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(250),
	@LevelID INT,	
	@PolicyID INT,
	@GradeID INT,
	@EmpID INT
)
AS
BEGIN
	declare @sql as nvarchar(3000)
	SET NOCOUNT ON
	--Commenting below line and adding above line for Adding @LevelId parameter for getting organization based designation
	set @sql = ''INSERT INTO TA_Tbl_Title(TitleName,TitleDescription,LevelID,LeavePolicyID,GradeID,Emp_Id,IsDeleted) VALUES(N''''''+@TitleName+'''''',N''''''+@TitleDescription+'''''',''+cast(@LevelID as nvarchar(25))+'',''+cast(@PolicyID as nvarchar(25))+'',''+cast(@GradeID as nvarchar(25))+'',''+cast(@EmpID as nvarchar(25))+'',0)''
	--set @sql = ''INSERT INTO TA_Tbl_Title(TitleName,TitleDescription,LeavePolicyID,GradeID,Emp_Id,IsDeleted) VALUES(N''''''+@TitleName+'''''',N''''''+@TitleDescription+'''''',''+cast(@PolicyID as nvarchar(25))+'',''+cast(@GradeID as nvarchar(25))+'',''+cast(@EmpID as nvarchar(25))+'',0)''
    exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_AddlWeekOffDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_AddlWeekOffDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE   PROCEDURE [dbo].[Proc_TA_Insert_AddlWeekOffDetails]  
(        
 @TYPE CHAR(1)='''',
 @AddlWeekoffID INT,
 @LevelId INT,         
 @AddlWeekoffDay NVARCHAR(50)='''',     
 @AddlWeekOffWeek NVARCHAR(50)='''',
 @auditEmpId int     
)        
AS 
declare @sql as nvarchar(3000)      
DECLARE @Isdeleted INT
SET @Isdeleted= 0
SET NOCOUNT ON        
BEGIN
IF (@TYPE=''I'')
	 BEGIN        
		 set @sql =''INSERT INTO TA_Tbl_Additional_WeeklyOff    (LevelId_Id,Addl_WeekOff_Day,Addl_WeekOff_Week,IsDeleted,Emp_Id )        
	               VALUES       ('''''' + cast(@LevelId as nvarchar(25)) + '''''',N'''''' + @AddlWeekoffDay + '''''',N'''''' + @AddlWeekOffWeek + '''''' ,'''''' + cast(@Isdeleted as nvarchar(10)) + '''''','''''' + cast(@auditEmpId as nvarchar(10)) + '''''')''
		exec(@sql) 
	 END
ELSE IF (@TYPE=''U'')
	BEGIN
		  set @sql =''UPDATE TA_Tbl_Additional_WeeklyOff   SET  LevelId_Id='''''' + cast(@LevelId as nvarchar(25))+ '''''',Addl_WeekOff_Day=N'''''' + @AddlWeekoffDay + '''''',Addl_WeekOff_Week=N'''''' + @AddlWeekOffWeek + '''''',Emp_Id='''''' + cast(@auditEmpId as nvarchar(25))+ ''''''
	               WHERE Addl_WeeklyOff_Id='''''' + cast(@AddlWeekoffID as nvarchar(25)) + '''''' ''
			exec(@sql)
	END    
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_IgnoreDuplicatePunches]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_IgnoreDuplicatePunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_Ta_IgnoreDuplicatePunches]
(
   @ClkIds AS Varchar(4000)
)
AS
BEGIN
 DECLARE @SQL AS Varchar(4000)
 SET @SQL = ''UPDATE TA_Tbl_ClockDetails SET IsVoid = 1 WHERE Clk_Id IN ('' + @ClkIds + '')''
 EXEC (@SQL)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDepartment]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDepartment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertDepartment]
(@CompanyId int,@RegionId int,@BranchId int,@DepartmentName nvarchar(50),@DepartDes nvarchar(255))
as
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	INSERT INTO TA_Tbl_Department (Company_Id,Region_Id,Branch_Id,Department_Name,Department_Description,Isdeleted) VALUES(@CompanyId,@RegionId,@BranchId,@DepartmentName,@DepartDes,@Isdel)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLookupTable]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLookupTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLookupTable]
	-- Add the parameters for the stored procedure here
@category CHAR,
@ID INT,
@Type INT,
@Title NVARCHAR(50),
@Parent INT,
@Remarks NVARCHAR(50),
@EmpID INT
AS
DECLARE @Isdeleted BIT
declare @sql as nvarchar(3000)
SET @Isdeleted=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF(@category=''I'')
  begin
	--INSERT INTO TA_Tbl_Lookup(Type,Title ,Parent,Remarks,EmpID,Isdeleted) VALUES(@Type,@Title,@Parent,@Remarks,@EmpID,@Isdeleted)
     set @sql = ''INSERT INTO TA_Tbl_Lookup(Type,Title ,Parent,Remarks,EmpID,Isdeleted) VALUES(''+cast(@Type as nvarchar(25))+'',N''''''+@Title+'''''',''+cast(@Parent as nvarchar(25))+'',N''''''+@Remarks+'''''',''+cast(@EmpID as nvarchar(25))+'',''+cast(@Isdeleted as nvarchar(25))+'')''  
	 exec(@sql)
  end
ELSE IF(@category=''U'')
   begin
	set @sql = ''UPDATE TA_Tbl_Lookup SET Title=N''''''+@Title+'''''',Parent=''+cast(@Parent as nvarchar(25))+'' WHERE ID=''+cast(@ID as nvarchar(25))+''''
	exec(@sql)
   end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGrade]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertGrade]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertGrade] 
	-- Add the parameters for the stored procedure here
	@Type CHAR(1),
	@Grade_ID INT,
	@Grade_Name NVARCHAR(50),
	@Grade_Level INT,
	@EmpID INT
AS
DECLARE @Isdeleted BIT
declare @sql as nvarchar(3000)
SET @Isdeleted=0
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF (@Type=''I'')
  begin
	--INSERT INTO TA_Tbl_Grade (Grade_Name,Grade_Level,EmpID,Isdeleted) VALUES(@Grade_Name,@Grade_Level,@EmpID,@Isdeleted)
    set @sql = ''INSERT INTO TA_Tbl_Grade (Grade_Name,Grade_Level,Emp_ID,Isdeleted) VALUES(N''''''+@Grade_Name+'''''',''+cast(@Grade_Level as nvarchar(25))+'',''+cast(@EmpID as nvarchar(25))+'',''+cast(@Isdeleted as nvarchar(25))+'')''
    exec(@sql) 
  end
ELSE IF(@Type=''U'')
  begin	
    --UPDATE TA_Tbl_Grade SET Grade_Name=@Grade_Name,Grade_Level=@Grade_Level,EmpID=@EmpID WHERE Grade_ID=@Grade_ID
    set @sql = ''UPDATE TA_Tbl_Grade SET Grade_Name=N''''''+@Grade_Name+'''''',Grade_Level=''+cast(@Grade_Level as nvarchar(25))+'',Emp_ID=''+cast(@EmpID as nvarchar(25))+'' WHERE Grade_ID=''+cast(@Grade_ID as nvarchar(25))+''''
    exec(@sql)
  end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShit]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermanentShit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- Create date: 17Aug2007
-- Description:	Report Permanent Shift
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptPermanentShit]
(
	@fromDate datetime,	
	@LevelID varchar(18) 
)
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''''
					  set @sqlQuery = @sqlQuery + '' SELECT     dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId, dbo.TA_Tbl_Shift.Shift_ShortName, dbo.TA_Tbl_Employee.Employee_FirstName + Space(1) + ''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Employee_LastName as empname, dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName''
					  set @sqlQuery = @sqlQuery + '' FROM  dbo.TA_Tbl_PermanentShiftAllocation INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = dbo.TA_Tbl_Title.TitleId''
					  set @sqlQuery = @sqlQuery + '' WHERE     (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''
if not(@LevelID='''' or @LevelID=''0'')
		begin
					set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.LevelId = '' + cast (@LevelId as nvarchar(50)) 
		end	
END
exec (@sqlQuery)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_RPTRAWDATAPUNCHES]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_RPTRAWDATAPUNCHES]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.MANIKANDAN
-- CREATE DATE: 11-11-2014
-- DESCRIPTION:	TO DISPLAY THE RAW DATA DETAILS
-- DROP PROC PROC_TA_RAWDATAPUNCHES
-- =============================================
CREATE PROCEDURE [dbo].[PROC_TA_RPTRAWDATAPUNCHES]
	-- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
	@EMPLOYEEID VARCHAR(50),
	@FROMDATE DATETIME,
	@TODATE DATETIME,	
	@PROCESSED INT,
	@TERMINALID INT,
	@PUNCHTYPES VARCHAR(20),
	@EMPLOYEENAME VARCHAR(150)
AS
BEGIN
	-- INTERFERING WITH SELECT STATEMENTS.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
    DECLARE @SQLQUERY VARCHAR(MAX)
    SET @SQLQUERY =''''
	SET @SQLQUERY =''SELECT C.* FROM TA_TBL_CLK_RAWDATA C
					INNER JOIN TA_TBL_EMPLOYEE E ON C.CLK_CARDID=E.SWIPECARDNO
					INNER JOIN TA_TBL_TERMINAL T ON T.TERMINAL_READERID=C.CLK_DEVICEID
					INNER JOIN TA_TBL_PUNCHTYPES P ON T.TERMINAL_ID=P.TERMINAL_ID
					WHERE E.ISDELETED=0''
	IF(@EMPLOYEEID!='''')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND E.EMPLOYEE_CODE_ID=''+CONVERT(VARCHAR(50),@EMPLOYEEID)
		END
	IF(@FROMDATE!='''' AND @TODATE!='''')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND (C.CLK_DATE>=''+@FROMDATE+''C.CLK_DATE<=''+@TODATE+'')''
		END
	IF(@TERMINALID!=0)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND (T.TERMINAL_ID=''+CONVERT(VARCHAR(20),@TERMINALID)+'')''
		END
	IF(@PROCESSED=1)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND (C.CLK_FLAG=1 AND C.CLK_PROCESS=1)''
		END
	IF(@PROCESSED=2)
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND (C.CLK_FLAG!=1 OR C.CLK_PROCESS!=1)''
		END
	IF(@PUNCHTYPES<>'''')
		BEGIN
			SET @SQLQUERY =@SQLQUERY+ '' AND P.PUNCHTYPE=''+CONVERT(VARCHAR(20),@PUNCHTYPES)
		END
	SET @SQLQUERY =@SQLQUERY+ '' ORDER BY C.CLK_CARDID,CLK_DATE,CLK_TIME''
	EXECUTE(@SQLQUERY)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShit]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTemporaryShit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- Create date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_RptTemporaryShit]
(
	@fromDate datetime,	
	@LevelID varchar(18) 
)
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''''
					  set @sqlQuery = @sqlQuery + '' SELECT     
dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId, dbo.TA_Tbl_Shift.Shift_ShortName, dbo.TA_Tbl_Employee.Employee_FirstName + 
Space(1) + ''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Employee_LastName as empname, 
dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName''
					  set @sqlQuery = @sqlQuery + '' FROM         dbo.TA_Tbl_TemporaryShiftAllocation 
INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast 
(day(@fromDate) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = 
dbo.TA_Tbl_Employee.Employee_Id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = 
dbo.Ta_Tbl_levelDetails.id INNER JOIN''
                      set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = 
dbo.TA_Tbl_Title.TitleId''
					  set @sqlQuery = @sqlQuery + '' WHERE     (dbo.TA_Tbl_TemporaryShiftAllocation.Year 
='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) 
as nvarchar(10)) + '')''
if not(@LevelID='''' or @LevelID=''0'')
		begin
					set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.LevelId = '' + cast (@LevelId as 
nvarchar(50)) 
		end	
END
exec (@sqlQuery)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountSummary]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOverTimewithAmountSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountSummary] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
    -- Insert statements for procedure here
	CREATE TABLE #TempDetails(SNo int,OrganizationLevel varchar(100),WeekDayOT decimal,
	WeeklyOffOT decimal,HolidayOT decimal,Amount numeric(18,2))      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)      
   VALUES(1,''EIT01'',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(2,''EIT02'',10,2,3,200.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(3,''EIT03'',10,2,3,100.00)      
  INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)         
   VALUES(4,''EIT04'',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)        
   VALUES(5,''EIT05'',10,2,3,100.00)      
   INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)     
   VALUES(6,''EIT06'',10,2,3,200.00)      
  INSERT INTO #TempDetails(SNo,OrganizationLevel,WeekDayOT,WeeklyOffOt,HolidayOT,Amount)   
   VALUES(7,''EIT07'',10,2,3,200.00)      
   --DECLARE @QUERY NVARCHAR(MAX)      
   --set @QUERY =''''      
   SELECT * FROM #TempDetails      
   --EXEC(@QUERY)      
   --  select @QUERY       
  drop  table #TempDetails 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Select](@Type char(1),@CompanyId int=0)
AS
DECLARE @Del BIT
SET @Del=1
--Select All Records 
if(@Type=''A'')
BEGIN
SELECT Company_Id,Company_Address1 FROM TA_Tbl_CompanyDetails WHERE IsDeleted=@Del
END
if(@Type=''P'')
BEGIN
SELECT * FROM TA_Tbl_CompanyDetails WHERE IsDeleted=@Del AND Company_Id=@CompanyId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SearchShiftExchange]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SearchShiftExchange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : [Proc_TA_SearchShiftExchange]   
Description : To Search the Shift Exchange Employee Details
Tables Included : TA_Tbl_Employee,Ta_Tbl_ShiftExchange,ta_tbl_shift
Created By : Sasireka  
Created On : 13-Jan-2009 
Modified By :  
Modified On :  
*/  
--exec [Proc_TA_SearchShiftExchange] '''','''','''','''','''',''SuperAdmin'',''1'','''',''''
CREATE PROCEDURE [dbo].[Proc_TA_SearchShiftExchange]
(
	@EmployeeId nvarchar(20),
	@EmployeeName nvarchar(50),
	@EmployeeType int,
	@EmployeeCategory int,
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@FromDate datetime,
	@ToDate datetime
)
AS
Declare @sql as varchar(8000)
set @sql=''''
BEGIN
set @sql = @sql + ''select ta_tbl_shiftExchange.date,e1.Employee_Code_Id + space(1) + e1.employee_Firstname as Employee1Name,''
set @sql = @sql + ''s1.shift_name,e2.Employee_Code_Id + space(1) + e2.employee_Firstname as Employee2Name,s2.Shift_Name''
set @sql = @sql + '' from ta_tbl_shiftExchange '' 
set @sql = @sql + ''inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id''
set @sql = @sql + '' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id''
set @sql = @sql + '' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift''
set @sql = @sql + '' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift''
set @sql = @sql + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
set @sql = @sql + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
set @sql = @sql + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
set @sql = @sql + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
set @sql = @sql + '' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
set @sql = @sql + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
set @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''	 
set @sql = @sql + '' where (Ta_Tbl_ShiftExchange.Date >= CONVERT(DATETIME, '''''' + cast(@fromDate as nvarchar(20)) + '''''', 102)) ''
set @sql = @sql + '' AND (dbo.Ta_Tbl_ShiftExchange.Date <= CONVERT(DATETIME,'''''' + cast(@todate as nvarchar(50))  + '''''', 102)) ''
if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end
if not(@EmployeeName='''' or @EmployeeName=''0'')
	begin
		set @sql = @sql + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
	end
	if(@employeeCategory<>0)
	begin
		set @sql = @sql +'' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sql = @sql + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='''' or @EmployeeId=''0'')
	begin
		--set @sqlQuery = @sqlQuery + '' and ta_tbl_processedData.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
			set @sql = @sql + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
	end
	if not(@LevelID='''' or @LevelID=''0'')
	begin
		set @sql = @sql + '' and TA_Tbl_EmployeeLevel.LevelId IN ('' + @LevelID  + '') '' 
	end
	exec(@sql)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllColumnNames]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllColumnNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectAllColumnNames  
Description : select congigured Field Name''s description for respective tables
Tables Included : sysobjects, sysproperties, syscolumns
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllColumnNames]
	-- Add the parameters for the stored procedure here
	@tableId decimal
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		DECLARE @version as nvarchar(50)
		SET @version = ''''
		SET @version = (SELECT left(@@version,26))
		if (@version=''Microsoft SQL Server  2000'')
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM dbo.sysobjects o 
				INNER JOIN dbo.sysproperties p
				ON o.id = p.id
				INNER JOIN dbo.syscolumns c
				ON p.smallid = c.colorder
				WHERE o.id = c.id AND o.id=@tableId
				AND p.type = 4
				ORDER BY o.id, p.smallid
			END
		else
			BEGIN
				SELECT o.id AS ''id'',
				CAST(c.Name AS varchar(75)) AS ''ColumnName'', 
				CAST(p.Value AS varchar(75)) AS ''Description'' 
				FROM sysobjects o 
				INNER JOIN sys.extended_properties p
				ON o.id = p.major_id
				INNER JOIN dbo.syscolumns c
				ON p.minor_id = c.colorder
				WHERE o.id = c.id AND o. id=@tableId
				AND p.minor_id <> 0
				ORDER BY o.id, p.minor_id
			END		
	--	SELECT DISTINCT(p.smallid), CAST(p.Value AS varchar(50)) AS ''Description'' from syscolumns c
	--	inner join sysproperties p on c.id = p.id  where c.id=@tableId AND  p.type = 4 ORDER BY p.smallid
	--SELECT * from syscolumns  where id=@tableId and autoval is null  and  name not in (''TimeStamp'',''emp_id'',''employee_id'',''employeeid'',''empid'',''Time_Stamp'',''IsDeleted'')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllTableNames]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllTableNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_SelectAllTableNames  
Description : select congigured Table Name''s description 
Tables Included : sysobjects, sysproperties
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllTableNames]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
		DECLARE @version as nvarchar(50)
		SET @version = ''''
		SET @version = (SELECT left(@@version,26))
		if (@version=''Microsoft SQL Server  2008'')
		begin
			SELECT o.id AS ''id'',
			CAST(o.Name AS varchar(75)) AS ''TableName'', 
			CAST(p.Value AS varchar(75)) AS ''Description''
			FROM sysobjects o
			INNER JOIN sysproperties p
			ON o.id = p.id
			WHERE p.type = 3
			AND p.smallid = 0 AND o.xtype<>''V''
			ORDER BY o.id, o.Name
		end
		else
		BEGIN
			SELECT o.id AS ''id'',
			CAST(o.Name AS varchar(75)) AS ''TableName'', 
			CAST(p.Value AS varchar(75)) AS ''Description''
			FROM sysobjects o
			INNER JOIN sys.extended_properties p
			ON o.id = p.major_id
			WHERE p.minor_id = 0 AND o.xtype<>''V''
			ORDER BY o.id, o.Name		
		END
	--	SELECT o.name AS name, o.id AS id, CAST(p.Value AS varchar(50)) AS ''Description'' from sysobjects o 
	--	INNER JOIN sysproperties p on o.id = p.id
	--	WHERE p.type = 3 AND p.smallid = 0 AND
	--	o.xtype=''U'' and o.name not in (''dtproperties'',''localization'',''LookupStatic'',''Old_TA_tbl_LeaveType'',''Results'',''Sheet1$'',''TA_TBL_EmailScripts'',''TA_Tbl_Page'',''TA_Tbl_ParentIDs'',''TA_Tbl_Results'',''TA_tbl_TerminalDatatype1'',''TA_Tbl_userRights'',''TA_Tbl_WindowsServiceFlag'',''Tbl_Sample'',''tblEmployee$'',''TempShift'',''tempshift2'',''test_arbic'',''testsample'',''testsample1'',''TA_Tbl_Additional_WeeklyOff'',''TA_Tbl_AuditOperation'',''Ta_Tbl_Branding'',''TA_Tbl_ChangePassword'',''TA_Tbl_ClockDetails'',''TA_Tbl_YearSetting'',''TA_Tbl_YearClosure'',''TA_Tbl_WindowsServiceFlag'',''TA_Tbl_Usergroup'',''TA_Tbl_Transportation_Mapping'',''TA_Tbl_TitleMapping'',''TA_Tbl_Title'',''TA_Tbl_TerminalMapping'',''TA_tbl_TerminalDatatype'',''TA_Tbl_TempShiftAllocation'',''TA_Tbl_TemporaryShiftAllocation'',''TA_Tbl_ShiftSettings'',''TA_Tbl_ShiftRoaster'',''TA_Tbl_ShiftPattern'',''TA_Tbl_Shift'',''TA_Tbl_RouteMaster'',''TA_Tbl_Results'',''TA_Tbl_PunchTypes'',''TA_Tbl_ProcessedData'',''TA_Tbl_Permission'',''TA_Tbl_PermanentShiftAllocation'',''TA_Tbl_PayrollProcessLeaveDetails'',''TA_Tbl_PayrollProcessDetails'',''TA_Tbl_Page'',''TA_Tbl_MultiLingual'',''TA_Tbl_MonthClosure'',''TA_Tbl_ManualTimeEntry'',''TA_Tbl_Lookup'',''TA_Tbl_Login'',''Ta_Tbl_levelDetails'',''TA_Tbl_Level'',''TA_Tbl_LeaveType'',''TA_Tbl_LeavePolicyDetails'',''TA_Tbl_LeavePolicy'',''TA_Tbl_LeaveApplication'',''TA_Tbl_HolidaySettings'',''TA_Tbl_Holiday'',''TA_Tbl_GroupDetails'',''TA_Tbl_GlobalWeekdaySettings'',''TA_Tbl_ErrLog'',''TA_Tbl_Encashment'',''TA_Tbl_EmployeeLingual'',''TA_Tbl_Employee'',''TA_Tbl_EmpChildrenDetails'',''TA_Tbl_Emp_LeavePolicyDetails'',''TA_Tbl_Emp_LeavePolicy'',''TA_TBL_EmailScripts'',''TA_Tbl_Temweekday'',''TA_Tbl_Clk_RawData'',''TA_Tbl_ConcurrentUser'',''TA_Tbl_DateandTimeFormat'',''TA_Tbl_AuditField'',''TA_Tbl_Transportation'')
	--SELECT name,id from sysobjects WHERE xtype=''U'' and name not in (''dtproperties'',''localization'',''LookupStatic'',''Old_TA_tbl_LeaveType'',''Results'',''Sheet1$'',''TA_TBL_EmailScripts'',''TA_Tbl_Page'',''TA_Tbl_ParentIDs'',''TA_Tbl_Results'',''TA_tbl_TerminalDatatype1'',''TA_Tbl_userRights'',''TA_Tbl_WindowsServiceFlag'',''Tbl_Sample'',''tblEmployee$'',''TempShift'',''tempshift2'',''test_arbic'',''testsample'',''testsample1'',''TA_Tbl_Additional_WeeklyOff'',''TA_Tbl_AuditOperation'',''Ta_Tbl_Branding'',''TA_Tbl_ChangePassword'',''TA_Tbl_ClockDetails'',''TA_Tbl_YearSetting'',''TA_Tbl_YearClosure'',''TA_Tbl_WindowsServiceFlag'',''TA_Tbl_Usergroup'',''TA_Tbl_Transportation_Mapping'',''TA_Tbl_TitleMapping'',''TA_Tbl_Title'',''TA_Tbl_TerminalMapping'',''TA_tbl_TerminalDatatype'',''TA_Tbl_TempShiftAllocation'',''TA_Tbl_TemporaryShiftAllocation'',''TA_Tbl_ShiftSettings'',''TA_Tbl_ShiftRoaster'',''TA_Tbl_ShiftPattern'',''TA_Tbl_Shift'',''TA_Tbl_RouteMaster'',''TA_Tbl_Results'',''TA_Tbl_PunchTypes'',''TA_Tbl_ProcessedData'',''TA_Tbl_Permission'',''TA_Tbl_PermanentShiftAllocation'',''TA_Tbl_PayrollProcessLeaveDetails'',''TA_Tbl_PayrollProcessDetails'',''TA_Tbl_Page'',''TA_Tbl_MultiLingual'',''TA_Tbl_MonthClosure'',''TA_Tbl_ManualTimeEntry'',''TA_Tbl_Lookup'',''TA_Tbl_Login'',''Ta_Tbl_levelDetails'',''TA_Tbl_Level'',''TA_Tbl_LeaveType'',''TA_Tbl_LeavePolicyDetails'',''TA_Tbl_LeavePolicy'',''TA_Tbl_LeaveApplication'',''TA_Tbl_HolidaySettings'',''TA_Tbl_Holiday'',''TA_Tbl_GroupDetails'',''TA_Tbl_GlobalWeekdaySettings'',''TA_Tbl_ErrLog'',''TA_Tbl_Encashment'',''TA_Tbl_EmployeeLingual'',''TA_Tbl_Employee'',''TA_Tbl_EmpChildrenDetails'',''TA_Tbl_Emp_LeavePolicyDetails'',''TA_Tbl_Emp_LeavePolicy'',''TA_TBL_EmailScripts'',''TA_Tbl_Temweekday'',''TA_Tbl_Clk_RawData'',''TA_Tbl_ConcurrentUser'',''TA_Tbl_DateandTimeFormat'',''TA_Tbl_AuditField'',''TA_Tbl_Transportation'',''TA_Tbl_AuditTable'')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectBLDetailsForService]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectBLDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_SelectBLDetailsForService 1,787,''2013-01-01'',''2014-11-11''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectBLDetailsForService]
	-- Add the parameters for the stored procedure here
	@intBonusLeaveAvailable int,
	@SwipeCardNo varchar(50),
	@FromDate datetime,
	@ToDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @sqlQuery varchar(max)
    set @sqlQuery=''SELECT TOP ''+ convert(varchar(20),@intBonusLeaveAvailable) + '' Process_Rec_Id FROM TA_Tbl_Processeddata WHERE Employee_Code_Id =''
	set @sqlQuery=@sqlQuery+''''''''+@SwipeCardNo+'''''' AND Attendance = ''''Absent'''' AND ''
	set @sqlQuery=@sqlQuery+''(Date BETWEEN ''''''+ CONVERT(varchar(20),@FromDate)+'''''' AND '''''' + convert(varchar(20),@ToDate)+'''''') ORDER BY Date ASC''
	execute(@sqlQuery)	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDeviceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDeviceDetails]
	@DeviceID as int
AS
BEGIN
		SELECT [DeviceID]
		  ,[DeviceType]
		  ,[ConnectionString]
		  ,[TableName]
		  ,[ReaderNo]
		  ,[CardNo]
		  ,[EmployeeID]
		  ,[DateField]
		  ,[DateFormat]
		  ,[TimeField]
		  ,[TimeFormat]
		  ,[DateTimeField]
		  ,[DateTimeFormat]
		  ,[DateTimeOption]
		  ,[Encrypt]
		  ,[PunchType]
		  ,[TransactionIdentFlag]
		  ,[TransactionIdentField]
		  ,[TransactionIdentValue]
		  ,[Flag]
	  FROM  [TA_Tbl_DeviceType]
			Where  [DeviceID]=@DeviceID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDevice]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDevice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDevice]
AS
BEGIN
	select DeviceID,DeviceType from ta_tbl_deviceType order by DeviceType
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateInstance]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateInstance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptLateInstance]
(@EmployeeID VarChar(50), @LevelID VarChar(50),@FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Set @EmployeeName = @EmployeeName + ''%''
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT PD.Process_Rec_ID,ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''T.TitleName AS Designation, ''
	set @SelectSQL = @SelectSQL + ''L.name AS ''''Level Name'''',''	   	
	Set @SelectSQL = @SelectSQL + ''CONVERT(varchar,Date ,106) AS Date, InTime,LateIn as LateBy,PD.Reason FROM TA_Tbl_Employee ED INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Title T ON ED.Designation_Id = T.TitleId INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''Ta_Tbl_levelDetails L ON ED.LevelId = L.Id INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_ProcessedData PD ON ED.Employee_Id = PD.Employee_Code_Id Where PD.LateIn <> ''''00:00:00'''' And PD.LateIn <> ''''00:00'''' And PD.LateIn <> ''''0'''' AND ''
	Set @SelectSQL = @SelectSQL + ''ED.IsDeleted = ''''1''''and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName like '''''' + @EmployeeName + '''''' ''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmployeeID + '''''' ''
	End
	If (@FromDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Date >= '''''' + @FromDate + '''''' ''
	End
	If (@ToDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Date <= '''''' + @ToDate + '''''' ''
	End
	if not(@LevelID='''' or @LevelID=''0'')
		Begin
			set @SelectSQL = @SelectSQL + '' and ED.LevelId = '' + cast (@LevelID as nvarchar(50)) 
		End
    exec (@SelectSQL)
	End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveDetail]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeaveDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Kannappan
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptLeaveDetail]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @LeaveType VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 FromDate varchar(50),
	 ToDate varchar(50),
	 Days varchar(50),
	 Reason varchar(255),
	 Approved varchar(255)
	)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Declare @SelFromDate as varchar(50)
	Declare @SelToDate as varchar(50)
	Declare @Days as varchar(50)
	Declare @Reason as varchar(250)
	Declare @Approved as varchar(250)
	Set @SelFromDate = ''''
	Set @SelToDate = ''''
	Set @Days = ''''
	Set @Reason = ''''
	Set @Approved = ''''
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName 
as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
    Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo,R.Region_Name AS Region, convert(varchar,LA.Leave_FromDate,106), 
convert(varchar,LA.Leave_ToDate,106), LA.NumberOfDays, LA.Reason, LA.Status FROM TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Region R ON ED.Region_Id = R.Region_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_LeaveApplication LA on ED.SwipeCardNo = LA.Employee_Id Where LA.IsDeleted = ''''1'''' ''
	Set @SelectSQL = @SelectSQL + ''And ED.IsDeleted = ''''1'''' ''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmployeeId + '''''' ''
	End
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
	If (@FromDate <> '''' and @ToDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And (( LA.Leave_FromDate  between '''''' + @FromDate + '''''' And '''''' + @ToDate + 
'''''') or (LA.Leave_ToDate between '''''' + @FromDate + '''''' And '''''' + @ToDate + ''''''))''
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  FromDate ,ToDate ,Days ,Reason , 
Approved)		
	Exec (@SelectSQL)
	Set @EmployeeName = @EmployeeName + ''%''
	Select * From #TempReportTable where EmployeeName like @EmployeeName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptEmployeeSchedule]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_rptEmployeeSchedule]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Senthil
-- ALTER  date: 06-Aug-2007
-- Description:	Reports - Employee Schedule
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_rptEmployeeSchedule]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(18) 
AS
BEGIN
		declare @sqlQuery as nvarchar(1500)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT     convert(nvarchar(20),dbo.TA_Tbl_ShiftAllocation.From_Date,101) as 
from_Date, convert(nvarchar(20),dbo.TA_Tbl_ShiftAllocation.To_Date,101) as to_date, dbo.TA_Tbl_ShiftPattern.Pattern_Name, ''
        set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + 
dbo.TA_Tbl_Employee.Employee_LastName as empName, dbo.TA_Tbl_ShiftAllocationDetails.Employee_Id, ''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Designation_Id, dbo.Ta_Tbl_levelDetails.name,  
dbo.TA_Tbl_Title.TitleName''
		set @sqlQuery = @sqlQuery + '' FROM         dbo.TA_Tbl_ShiftAllocationDetails INNER JOIN''
        set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_ShiftAllocation ON dbo.TA_Tbl_ShiftAllocationDetails.ShiftAllocation_Id = 
dbo.TA_Tbl_ShiftAllocation.ShiftAllocation_Id INNER JOIN''
        set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_ShiftPattern ON dbo.TA_Tbl_ShiftAllocation.ShiftPattern_Id = 
dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id INNER JOIN''
        set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ShiftAllocationDetails.Employee_Id = 
dbo.TA_Tbl_Employee.Employee_Id INNER JOIN''
        set @sqlQuery = @sqlQuery + '' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id 
INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = 
dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' WHERE     (dbo.TA_Tbl_Employee.Isdeleted = 1)  
(dbo.TA_Tbl_Employee.Employee_Status = 1) AND ''
		set @sqlQuery = @sqlQuery + '' (dbo.TA_Tbl_ShiftAllocation.From_Date >= CONVERT(DATETIME, ''''''+ cast( @fromDat 
as nvarchar(50))   + '''''', 101)) AND ''
        set @sqlQuery = @sqlQuery + '' (dbo.TA_Tbl_ShiftAllocation.To_Date <= CONVERT(DATETIME, '''''' + cast( @toDat as 
nvarchar(50))   +  '''''', 101))''
		if not(@EmployeeName='''' or @EmployeeName=''0'')
		begin
			set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + 
cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		end
		if not (@empId='''' or @empId=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and ta_tbl_processedData.Employee_Code_Id = '''''' + cast (@empId as 
nvarchar(50)) + '''''' ''
		end
		if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.LevelId = '' + cast (@LevelId as nvarchar(50)) 
		end	
			set @sqlQuery = @sqlQuery + '' order by ta_tbl_employee.Employee_firstName''
		exec (@sqlQuery)	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistory]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistory ''01/01/1970'',''08/20/2008'','''',0,'''','''',0,0,''Admin'',3
-- Description:	Report Employee History Details
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistory]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(3000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery = @sqlQuery + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_EmployeeLevel.EffectiveDate as LevelEffectiveDate,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_EmployeeDesignation.EffectiveDate as DesigEffectiveDate,dbo.TA_Tbl_Category.CategoryName,TA_Tbl_EmployeeCategory.EffectiveDate as CatEffectiveDate,dbo.TA_Tbl_Type.TypeName,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate,dbo.TA_Tbl_EmployeePay.BasicPay,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate ''		
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId''		
		set @sqlQuery = @sqlQuery + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		if not(@fromDat='''')		
		begin
		set @sqlQuery = @sqlQuery + '' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''		
		End
		if not (@ToDat='''')
		begin
		set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		end
		if not(@EmployeeName='''' or @EmployeeName=''0'')
		begin
			set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if not (@EmployeeId='''' or @EmployeeId=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
		end
		if not (@EmployeeCategory=0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))
		end
		if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelId +'')''
		end			
		set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_Employee.Employee_code_Id ''
		exec(@sqlQuery)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptEmployeeDetails]
	-- Add the parameters for the stored procedure here
	(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), @SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Set @EmployeeName = @EmployeeName + ''%''
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, CONVERT(Varchar, ED.DateOfJoining, 101) AS HireDate, ''
    Set @SelectSQL = @SelectSQL + ''CONVERT(Varchar, ED.DateofBirth, 101) AS DOB, ED.Nationality, ED.Employee_Status AS Status, C.Company_Logo AS Logo FROM TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON ED.Designation_Id = T.TitleId INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id Where ''
	Set @SelectSQL = @SelectSQL + ''ED.IsDeleted = ''''1'''' and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName like '''''' + @EmployeeName + '''''' ''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmployeeId + '''''' ''
	End
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
	If (@FromDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.DateOfJoining >= '''''' + @FromDate + '''''' ''
	End
	If (@ToDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.DateOfJoining <= '''''' + @ToDate + '''''' ''
	End
	Exec (@SelectSQL)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailedAttendance]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailedAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthilkumar
-- ALTER  date: 17Aug2007
-- Description:	Employee Attendance Summary
-- Proc_TA_RptDetailedAttendance ''01/01/2008'',''08/30/2008'','''','''','''',''Admin'',3
-- =============================================
CREATE       PROCEDURE [dbo].[Proc_TA_RptDetailedAttendance]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(1000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 
)
AS
BEGIN
	declare @sqlQuery as varchar(8000)
	declare @sqlQuery1 as varchar(8000)
	set @sqlQuery=''''
	set @sqlQuery1=''''	
					 set @sqlQuery = @sqlQuery + ''SELECT b.Employee_Code_Id, isnull(b.Employee_FirstName,'''''''') + SPACE(1) + isnull(b.Employee_LastName,'''''''') AS empName, SUM(a.Present) AS Present, ''
					 set @sqlQuery = @sqlQuery + '' SUM(a.cl) AS CL,  SUM(a.el) AS EL, SUM(a.sl) AS SL, SUM(a.others) AS Others,''
                     set @sqlQuery = @sqlQuery + '' SUM(a.Absent) AS Absent, SUM(a.lateDays) AS ''''TotlateDays'''', SUM(a.otDays) AS TotOtDays, SUM(a.Leaves) AS Leaves, TA_Tbl_EmployeeDesignation.DesignationId, ''
					 --set @sqlQuery = @sqlQuery + '' CAST(floor(cast(sum(a.totLate)as int) / 60) AS varchar(15)) + '''':'''' + cast((cast(sum(a.totLate)as int) % 60) as varchar(10))  as TotalLateHrs ,''	
					set @sqlQuery = @sqlQuery + '' sum(a.totLate) as TotalLateHrs ,''
					 --set @sqlQuery = @sqlQuery + '' CAST(floor(cast(sum(a.ot)as int) / 60) AS varchar(15)) + '''':'''' + cast((cast(sum(a.ot)as int) % 60) as varchar(10))  as OtHrs ,''	
					set @sqlQuery = @sqlQuery + '' sum(a.ot) as OtHrs ,''	
                     set @sqlQuery = @sqlQuery + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name''
--Number of days present					 
					 set @sqlQuery = @sqlQuery + '' FROM         (SELECT  '''''''' AS ot,'''''''' AS totLate,    Employee_Code_Id, SUM(TotalDays) AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery = @sqlQuery + '' FROM          ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE     (Attendance IN (''''Present'''', ''''Weekly Off'''', ''''Holiday'''', ''''Comp Off'''') OR LeaveCode=''''Comp Off'''')''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery = @sqlQuery + '' UNION''
--number of days absent
                     set @sqlQuery = @sqlQuery + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', SUM(TotalDays) AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery = @sqlQuery + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE    (Attendance = ''''Absent'''' OR Attendance = ''''LA'''' OR Attendance = ''''AL'''') ''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery = @sqlQuery + '' UNION''
--Late coming days count					 
                     set @sqlQuery = @sqlQuery + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', COUNT(LateInMins) AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery = @sqlQuery + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE     LateInMins <>0''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery = @sqlQuery + '' UNION''						
--late exit days count
                     set @sqlQuery = @sqlQuery + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', COUNT(ExtraMins) AS ''''otDays'''', '''''''' AS ''''Leaves''''''
                     set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
					 set @sqlQuery = @sqlQuery + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE     ExtraMins<>0 And ExtraMins IS NOT NULL And ExtraMins<>'''''''' ''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''						
					 set @sqlQuery = @sqlQuery + '' UNION''
-- sum lateIn  mins                     
                     set @sqlQuery = @sqlQuery + '' SELECT  '''''''' AS ot, sum(LateInMins) AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery = @sqlQuery + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE     lateInMins<>0''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''
					 set @sqlQuery = @sqlQuery + '' UNION''
--sum late exit mins                     
                     set @sqlQuery = @sqlQuery + '' SELECT  sum(ExtraMins) AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery = @sqlQuery + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery = @sqlQuery + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery = @sqlQuery + '' WHERE     ExtraMins<>0 And ExtraMins IS NOT NULL And ExtraMins<>'''''''' ''
					 set @sqlQuery = @sqlQuery + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery = @sqlQuery + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery = @sqlQuery + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery = @sqlQuery + '' UNION''			
--Count CL
					set @sqlQuery1 = @sqlQuery1 + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery1 = @sqlQuery1 + '' , SUM(TotalDays) AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery1 = @sqlQuery1 + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery1 = @sqlQuery1 + '' WHERE     LeaveCode=''''CL'''' ''
					 set @sqlQuery1 = @sqlQuery1 + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery1 = @sqlQuery1 + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery1 = @sqlQuery1 + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery1 = @sqlQuery1 + '' UNION''
--count EL                     
                     set @sqlQuery1 = @sqlQuery1 + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery1 = @sqlQuery1 + '' , 0.0 AS ''''cl'''' ,SUM(TotalDays) AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery1 = @sqlQuery1 + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery1 = @sqlQuery1 + '' WHERE     LeaveCode=''''EL'''' ''
					 set @sqlQuery1 = @sqlQuery1 + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery1 = @sqlQuery1 + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery1 = @sqlQuery1 + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery1 = @sqlQuery1 + '' UNION''
--count SL                     
                     set @sqlQuery1 = @sqlQuery1 + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery1 = @sqlQuery1 + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',SUM(TotalDays) AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery1 = @sqlQuery1 + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery1 = @sqlQuery1 + '' WHERE     LeaveCode=''''SL'''' ''
					 set @sqlQuery1 = @sqlQuery1 + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery1 = @sqlQuery1 + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery1 = @sqlQuery1 + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery1 = @sqlQuery1 + '' UNION''
--count Others
                     set @sqlQuery1 = @sqlQuery1 + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', '''''''' AS ''''Leaves''''''
					 set @sqlQuery1 = @sqlQuery1 + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',SUM(TotalDays) AS ''''others'''' ''
                     set @sqlQuery1 = @sqlQuery1 + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery1 = @sqlQuery1 + '' WHERE     attendance not in (''''Present'''', ''''Absent'''', ''''Weekly Off'''', ''''Holiday'''')  AND LeaveCode not in (''''Comp Off'''', ''''CL'''' ,''''EL'''' ,''''SL'''' ) ''
					 set @sqlQuery1 = @sqlQuery1 + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery1 = @sqlQuery1 + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
					 set @sqlQuery1 = @sqlQuery1 + '' GROUP BY Employee_Code_Id''
                     set @sqlQuery1 = @sqlQuery1 + '' UNION''
--number of leave days
                     set @sqlQuery1 = @sqlQuery1 + '' SELECT  '''''''' AS ot, '''''''' AS totLate,   Employee_Code_Id, 0.0 AS ''''Present'''', 0.0 AS ''''Absent'''', '''''''' AS ''''lateDays'''', '''''''' AS ''''otDays'''', COUNT(Attendance) AS ''''Leaves''''''
					 set @sqlQuery1 = @sqlQuery1 + '' , 0.0 AS ''''cl'''' ,0.0 AS ''''el'''',0.0 AS ''''sl'''',0.0 AS ''''others'''' ''
                     set @sqlQuery1 = @sqlQuery1 + '' FROM         ta_tbl_processeddata''
                     set @sqlQuery1 = @sqlQuery1 + '' WHERE     Attendance NOT IN (''''Present'''', ''''Absent'''', ''''Weekly Off'''', ''''Holiday'''') ''
					 set @sqlQuery1 = @sqlQuery1 + '' And     (date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
					 set @sqlQuery1 = @sqlQuery1 + '' AND (date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
                     set @sqlQuery1 = @sqlQuery1 + '' GROUP BY Employee_Code_Id) a INNER JOIN''
                    set @sqlQuery1 = @sqlQuery1 + '' dbo.TA_Tbl_Employee b ON a.Employee_Code_Id = b.SwipeCardNo INNER JOIN''
					set @sqlQuery1 = @sqlQuery1 + '' TA_Tbl_EmployeeLevel on b.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId INNER JOIN''
					set @sqlQuery1 = @sqlQuery1 + '' Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id INNER JOIN''
					set @sqlQuery1 = @sqlQuery1 + '' dbo.TA_Tbl_EmployeeDesignation ON b.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId INNER JOIN''
					set @sqlQuery1 = @sqlQuery1 + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId INNER JOIN''
					set @sqlQuery1 = @sqlQuery1 + '' TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
					set @sqlQuery1 = @sqlQuery1 + '' WHERE b.Isdeleted=0 and b.report_exclude=0 and b.employee_status=1''
					set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = b.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
					set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = b.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
					if(@UserGroupName<>''SuperAdmin'')
					begin
						set @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
					end
					if not(@EmployeeName='''' or @EmployeeName=''0'')
					begin
						set @sqlQuery1 = @sqlQuery1 + '' and (b.Employee_FirstName + '''''''' + isnull(b.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
					end
					if not (@empId='''' or @empId=''0'')
					begin
						set @sqlQuery1 = @sqlQuery1 + '' and b.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
					end
					if not(@LevelID='''' or @LevelID=''0'')
					begin
						set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeLevel.LevelId IN ( '' + @LevelId + '') '' 
					end	
					set   @sqlQuery1 = @sqlQuery1 + '' GROUP BY b.Employee_Code_Id, b.Employee_FirstName, b.Employee_LastName, TA_Tbl_EmployeeDesignation.DesignationId, dbo.TA_Tbl_Title.TitleName, ''
                    set   @sqlQuery1 = @sqlQuery1 + '' dbo.Ta_Tbl_levelDetails.name''
					set   @sqlQuery1 = @sqlQuery1 + '' ORDER BY b.Employee_Code_Id''
					exec(@sqlQuery + '' '' +  @sqlQuery1)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RegionNameByCid]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RegionNameByCid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_RegionNameByCid]
(@CompanyId int)
AS
DECLARE @Isdel int
SET @Isdel=1
BEGIN
SELECT Region_Id,Region_Name from TA_Tbl_Region WHERE Isdeleted=@Isdel and Company_Id=@CompanyId 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplacingSMSContent]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ReplacingSMSContent]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-01-2017 12.54>
-- Description:	<Description,,>
-- After the release of ver2.4, we got the sms gateway for testing. That time we created this procedure
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ReplacingSMSContent]
AS
BEGIN
	SET NOCOUNT ON;
	-- if any white list are used by client, we need to append those string into below service url @serviceUrl
	--select ''\nInfo:Timecheck\n-Trinetra'' as whiteList
	select '''' as whiteList
END


' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteAttandanceCode]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PermanentDeleteAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PermanentDeleteAttandanceCode]
	@AttandanceID as varchar(2000),	
	@EmpID as int
AS
BEGIN
    declare @Query varchar(2000)
	set @Query=''''	
	set @Query = @Query + ''delete from TA_Tbl_AttandanceCode where AttandanceID in ('' + @AttandanceID + '')''
	exec(@Query)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllSwipe]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAllSwipe]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_RptAllSwipe]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @TerminalID varchar(50), @EmployeeName varchar(50))
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Declare @SelectSQL As Varchar(4000)
	Set @EmployeeName = @EmployeeName + ''%''
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName 
as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
    Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo,R.Region_Name AS Region, PD.Clk_InDeviceId as ReaderID, 
PD.Clk_InDate as Date, right(PD.Clk_InTime,charindex('''' '''',PD.Clk_InTime,1)) as InTime FROM TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN ''
   	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Region R ON ED.Region_Id = R.Region_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_ClockDetails PD ON ED.SwipeCardNo = PD.Clk_EmpId Where ''
	Set @SelectSQL = @SelectSQL + ''ED.IsDeleted = ''''1'''' and ED.Employee_FirstName + case when ED.Employee_MiddleName is 
not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName like '''''' + 
@EmployeeName + '''''' ''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmployeeId + '''''' ''
	End
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
	If (@FromDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Clk_InDate >= '''''' + @FromDate + '''''' ''
	End
	If (@ToDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Clk_InDate <= '''''' + @ToDate + '''''' ''
	End
	If Not (@TerminalID = '''' Or @TerminalID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Clk_InDeviceId = '''''' + @TerminalID + '''''' ''
	End
	Set @SelectSQL = @SelectSQL + ''Order By PD.Clk_InDate Asc''
	--Exec (@SelectSQL)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLogFileSize]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLogFileSize]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_GetLogFileSize]
AS
	BEGIN
	--Get Log File Details
	DBCC SQLPERF(logspace)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekOff]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : DeleteWeekOff  
Description : delete additional week off  
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[DeleteWeekOff](@WeedayId varchar(100)) 
AS
DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SET @Query=''UPDATE TA_Tbl_Additional_WeeklyOff SET IsDeleted=0 WHERE Addl_WeeklyOff_Id in ('' + @WeedayId + '')''
EXEC (@Query) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[DeleteWeekday]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteWeekday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : DeleteWeekday  
Description : delete the weekday 
Tables Included : TA_Tbl_TemWeekday  
Created By : Janakaraj.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[DeleteWeekday](@WeedayId varchar(100)) 
AS	
BEGIN
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	SET NOCOUNT ON;
	SET @Query=''DELETE FROM TA_Tbl_TemWeekday WHERE TempWeekday_Id in ('' + @WeedayId + '')''
	EXEC (@Query) 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntryUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckManualEntryUpdate  1,''105'',''8/29/2008'',''08:37 AM'',''8/29/2008'',''04:22 PM''
Description : check manual entry while update 
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : Kumuthini.L  
Created On : 17-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntryUpdate](
@MID int,
@EmpCode varchar(10),
@ManualInDate varchar(15),
@ManualInTime varchar(25),
@ManualOutDate varchar(15),
@ManualOutTime varchar(25))
AS
BEGIN
select 0  as ManualEntry
/*
DECLARE @Isdel int
DECLARE @InDateTime VARCHAR(50)
DECLARE @OutDateTime VARCHAR(50)
SET @Isdel=0
IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')
   BEGIN
	SET @InDateTime = @ManualInDate + '' '' + @ManualInTime
	SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=@Isdel and ManualTimeEntry_Id <> @MID
   END
ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')
   BEGIN
	 SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
	SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=@Isdel and ManualTimeEntry_Id <> @MID
   END
ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')
   BEGIN
        SET @InDateTime = @ManualInDate + '' '' + @ManualInTime
        SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
        SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=@Isdel and  
		((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR 
		((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) 
		and ManualTimeEntry_Id <> @MID 
   END
   */
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[DEVICEENR_TEMP_DELETE]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DEVICEENR_TEMP_DELETE]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DEVICEENR_TEMP_DELETE]   (@EMPID  varchar(15),   @TermID           int)  AS  BEGIN   DELETE FROM TBLDEVICEENRUSERS WHERE EMPCODE=@EMPID AND STATUS=''N'' and DeviceID=@TermID     RETURN (@@ROWCOUNT)  END  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[DEVICEMASTER_INSERT]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DEVICEMASTER_INSERT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE  [dbo].[DEVICEMASTER_INSERT]   ( @v_DEVICE_ADDRESS   nvarchar(50),    @v_DEVICE_NO   nvarchar(50),    @v_DEVICE_NAME  nvarchar(50),    @v_DEVICE_GROUP  nvarchar(50),    @v_DEVICE_TYPE  nvarchar(50),    @v_DEVICE_PORT  nvarchar(50),    @v_DEVICE_NETWORKNAME nvarchar(50),    @v_DEVICE_ACTIVE   bit ,    @v_SCHEDULER_RULE nvarchar(50),   @v_remark nvarchar(30),   @v_D_INOUT nvarchar(20))  AS    Declare @idVAl  int    BEGIN      SELECT @idVAl=isnull(MAX(Device_ID + 1),1)   FROM tblDevice_Mast        INSERT INTO tblDevice_Mast  (Device_ID,Device_Group,Device_Name,Device_Address,Device_No,Device_Type,Device_Port,  Device_Networkname,Device_Active,Schedule_Rule,remark,D_INOUT    )      VALUES      (@idVAl, @v_DEVICE_GROUP,  @v_DEVICE_NAME,@v_DEVICE_ADDRESS, @v_DEVICE_NO, @v_DEVICE_TYPE,    @v_DEVICE_PORT,    @v_DEVICE_NETWORKNAME,    @v_DEVICE_ACTIVE,    @v_SCHEDULER_RULE,@v_remark,@v_D_INOUT)  RETURN (@@ROWCOUNT)     END  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Template_Read]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Read]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Template_Read]
	( @EmpID   nvarchar(10))
AS
BEGIN
SELECT Template FROM tbl_templatemaster WHERE EmpID=@EmpID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Template_Enroll]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_Enroll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Template_Enroll]
	( @EmpID   nvarchar(10),
	 @Template  	image,
	 @DeviceID 	nvarchar(20),
		@UserLevel varchar(2),
@Stemplate varchar(50),
@SHextemp varchar(50))
AS
Declare @idVAl  int
Declare @idLen  int
--Declare i  int
BEGIN
begin
set @idLen=len(@EmpID)
IF(@idLen=5)
begin
set @EmpID=''0''+@EmpID
end
IF(@idLen=4)
begin
set @EmpID=''00''+@EmpID
end
IF(@idLen=3)
begin
set @EmpID=''000''+@EmpID
end
IF(@idLen=2)
begin
set @EmpID=''0000''+@EmpID
end
IF(@idLen=1)
begin
set @EmpID=''00000''+@EmpID
end
END
set @idVAl= (SELECT count(EmpID)   FROM tbl_templatemaster where empId=@EmpID)
if( @idVAl=0)
begin
insert into tbl_templatemaster(EmpID,Template,DeviceID,CreatedDate,UserLevel, STmpData,SHextemp)values(@EmpID,@Template,@DeviceID,getdate(),@UserLevel,@Stemplate,@SHextemp)
end
else
begin
update tbl_templatemaster set ModifiedDate=getdate(),DeviceID=@DeviceID,Template=@Template, STmpData=@Stemplate,SHextemp=@SHextemp where EmpID=@EmpID
end
update tblDeviceEnrUsers set Status=''Y'' where EmpCode=@EmpID
RETURN (@@ROWCOUNT)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_LeaveType]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_LeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Select_LeaveType]
(
	@LeaveDescription nvarchar(20) OUTPUT 
)
as
SELECT @LeaveDescription = LeaveDescription from tbl_TA_LeaveType
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveTypeExist]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveTypeExist]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_LeaveTypeExist]
(
  @LeaveId BigInt,
  @LeaveType VarChar(50), 
  @LeaveDescription VarChar(10)
) 
AS
Set NoCount On
IF @LeaveId = ''Add''
	Begin
		SELECT ISNULL(COUNT(@LeaveId),0) FROM tbl_TA_LeaveType WHERE LeaveType = @LeaveType 
	End
Else If @LeaveId=''Modify''
	Begin
		SELECT ISNULL(COUNT(@LeaveId),0) FROM tbl_TA_LeaveType WHERE  LeaveType = @LeaveType  AND LeaveDescription <>@LeaveDescription
	End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveType]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveType]
(
	@LeaveId INT,
	@LeaveType VARCHAR(25) ,
	@LeaveDescription NVARCHAR(25)	
)
AS
SET NOCOUNT ON
DECLARE @CountLeaveID INT
SELECT @CountLeaveID=COUNT(@LeaveId) FROM tbl_TA_LeaveType WHERE LeaveId=@LeaveId
IF (@CountLeaveID=0) 
	BEGIN
		INSERT INTO tbl_TA_LeaveType
		(
		   LeaveId,LeaveType,LeaveDescription,IsDeleted
		)
       		VALUES 
		(	
		   @LeaveId, @LeaveType,@LeaveDescription,0
		)
	END
ELSE
	BEGIN
		UPDATE  tbl_TA_LeaveType
		SET
			  LeaveId=@LeaveId,   	
			 LeaveDescription=@LeaveDescription
  		WHERE LeaveId=@LeaveId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_Delete_LeaveType]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_Delete_LeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : proc_TA_Delete_LeaveType  
Description : delete leave type  
Tables Included : tbl_TA_LeaveType  
Created By : Arun Vinoth
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[proc_TA_Delete_LeaveType]
(@LeaveId int)
AS
begin
set NOCOUNT ON;
Delete From tbl_TA_LeaveType Where LeaveId=@LeaveId
end
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[udf_CompleteWeekRange]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_CompleteWeekRange]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE Function [dbo].[udf_CompleteWeekRange] (
    @StartDate Datetime
   ,@EndDate Datetime
   ,@DayNumber1 int
   )
-- CompleteWeekRange(StartDate,EndDate,DayNumber1,DayNumber2) 
--             1=Sun,2=Mon,3=Tue,4=Wed,5=Thu,6=Fri,7=Sat
Returns Int
As Begin 
   Declare @nCnt Money
   Set @nCnt=0
   While @StartDate <= @EndDate
   Begin
      Set @nCnt=@nCnt 
            + case when datepart(dw,@StartDate)=@DayNumber1
                                 then 1 else 0 end
      Set @StartDate=@StartDate+1
   End
   Return Floor(@nCnt)
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonthYear]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDateMonthYear]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--GetDateMonthYear''2015-04-01'',''2015-05-01''
-- =============================================
Create PROCEDURE [dbo].[GetDateMonthYear] 
	-- Add the parameters for the stored procedure here
	@From varchar(20),
	@To varchar(20)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @year varchar(20)
	declare @Date varchar(20)
	declare @MOnth varchar(20)
	declare @year1 varchar(20)
	declare @Date1 varchar(20)
	declare @MOnth1 varchar(20)
    -- Insert statements for procedure here
    set @year=DATEPART(year,CONVERT(datetime,@From))
    set @Date=DATEPART(DAY,CONVERT(datetime,@From))
    set @MOnth=DATEPART(MONTH,CONVERT(datetime,@From))
    set @year1=DATEPART(year,CONVERT(datetime,@To))
    set @Date1=DATEPART(DAY,CONVERT(datetime,@To))
    set @MOnth1=DATEPART(MONTH,CONVERT(datetime,@To))
    select @year as Year,@MOnth as Month,@Date as Date union all select @year1 as Year,@MOnth1 as Month,@Date1 as Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectFTPConfiguration]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectFTPConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 17-Aug-2011
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectFTPConfiguration] 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    select * from TA_Tbl_FTPConfiguration
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateFTPConfiguration]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateFTPConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 17-Aug-2011
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertUpdateFTPConfiguration] 
(
 @Address varchar(250),
 @UserName varchar(100),
 @Password varchar(100),
 @Port varchar(15)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
   if((select count(*) from TA_Tbl_FTPConfiguration) = 0)
   Begin
      insert into TA_Tbl_FTPConfiguration (Address,UserName,Password,Port) values (@Address,@UserName,@Password,@Port)
   End
   else
   Begin
      update TA_Tbl_FTPConfiguration set Address = @Address,UserName = @UserName,Password = @Password,Port = @Port
   End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetDateMonth]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDateMonth]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.r,,Name>
-- Create date: <06-05-2015,,>
-- Description:	<Get date month year using for the EmailSchedular,,>
-- GetDateMonth ''2014-05-01'',''2014-05-31''
-- =============================================
Create PROCEDURE [dbo].[GetDateMonth]
	-- Add the parameters for the stored procedure here
	@FromDate varchar(25),
	@ToDate varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @Month varchar(10)
    declare @Year varchar(10)
    declare @TS varchar(10)
    declare @frmDate varchar(20)
    declare @frmDate1 varchar(20)
    --set @Month=(MONTH(convert(datetime,@FromDate)))
    set @Month=RIGHT(''0''+CAST(MONTH(convert(datetime,@FromDate)) AS varchar(2)),2)
    set @Year=(year(convert(datetime,@FromDate)))
    set @frmDate = @FromDate
    set @TS=(DATEDIFF(day,@FromDate,@ToDate) + 1)
    DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
		if(@TS > 31)
			begin
				set @frmDate1=DATEADD(day,@TS - 31,@FromDate)
			end
		IF(@date=''dd/MM/yyyy'')
			BEGIN
				SET @frmDate1 = CONVERT(varchar, @frmDate, 103)
			END
		ELSE IF(@date=''MM/dd/yyyy'')
			BEGIN
				SET @frmDate1 = CONVERT(VARCHAR, @frmDate, 101)
			END
		ELSE
			BEGIN
				SET @frmDate1 = CONVERT(VARCHAR, @frmDate, 106)
			END
    select @Month as Month,@Year as Year,@TS as TS,@frmDate1 as Fromdate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFormatForExportData]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCustomFormatForExportData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name : GetCustomFormatForExportData  
Description : Gets the custom formats based on the option type.  
Tables Included : TA_ExportData_CustomFormat  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[GetCustomFormatForExportData]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int	
)
AS
	BEGIN
	if(@OptionType = ''All'')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType=''All'' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = ''OT'')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType=''OT'' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = ''Attendance'')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType=''Attendance'' and DataType=@DataType and CompanyID=@CompanyID
		END
	else if(@OptionType = ''Leave'')
		BEGIN
		  select * from  TA_ExportData_CustomFormat where OptionType=''Leave'' and DataType=@DataType and CompanyID=@CompanyID
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetCustomFieldNameForExportData]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCustomFieldNameForExportData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name : GetCustomFieldNameForExportData  
Description : Gets the custom field name based on the option type.  
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 04-Apr-2011
*/  
CREATE PROCEDURE [dbo].[GetCustomFieldNameForExportData]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int		
)
AS
	BEGIN
	if(@OptionType = ''All'')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name from  TA_ExportData_FieldData where OptionType=''All'' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = ''OT'')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name from  TA_ExportData_FieldData where OptionType=''OT'' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = ''Attendance'')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name from  TA_ExportData_FieldData where OptionType=''Attendance'' and DataType=@DataType and CompanyId=@CompanyID
		END
	else if(@OptionType = ''Leave'')
		BEGIN
		  select FieldName,UserDefinedFieldName,FieldType,FieldName+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name from  TA_ExportData_FieldData where OptionType=''Leave'' and DataType=@DataType and CompanyId=@CompanyID
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetActiveLanguage]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetActiveLanguage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetActiveLanguage]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Language_Name from TA_Tbl_MultiLingual where IsActive=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMaxLevel]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMaxLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_Ta_GetMaxLevel]
AS
BEGIN	
	select max(levelID) as maxId from ta_tbl_level where isdeleted=0
END
' 
END
GO
/****** Object:  View [dbo].[VW_FetchDataFromProcessedData]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[VW_FetchDataFromProcessedData]'))
EXEC dbo.sp_executesql @statement = N'






CREATE  VIEW [dbo].[VW_FetchDataFromProcessedData]
AS
SELECT		P.[Date], P.Shift_Id, P.InTime, P.OutTime, P.Employee_Code_Id, 
			P.Process_Rec_ID, P.HrsWork, P.HrsOT, P.NormOT, P.OffOT, 
			P.HolOT, P.EarlyOut, P.LateIn, P.WorkHrs, P.Attendance, 
			P.HrsLess, P.HrsExtra, P.LateInMins, P.EarlyOutMins, P.ExtraMins, 
			P.OtMins, P.OvertimeStatus, P.TotalDays, P.LeaveCode, P.LateEntryReason, 
			P.EarlyOutReason, P.BreakOut, P.BreakIn, P.BreakHours, P.BreakLateMins, 
			P.BreakLate, P.TotalLate, P.TotalLateMins, P.ProcessFlag, P.Status, 
			P.FNAttendanceCode, P.ANAttendanceCode, P.LateExit, P.EarlyEntry, P.BreakHrs, 
			P.LunchHrs, P.BreakHrsInMins, P.InNotation, P.LunchHrsInMins, P.OutNotation, 
			P.Shift_EndTime, P.Inpunch, P.Outpunch, TA_Tbl_Shift.Shift_StartTime, 
			TA_Tbl_Shift.Shift_SecondHalf_StartTime,ActOTMins,ActNormOT,
			p.SPEC_NormOT1,
			p.SPEC_NormOTMins1,
			P.SPEC_NormOT2,
			P.SPEC_NormOTMins2,
			P.SPEC_OffOT1,
			P.SPEC_OffOTMins1,
			P.SPEC_OffOT2,
			P.SPEC_OffOTMins2,
			P.SPEC_HOLOT1,
			P.SPEC_HOLOTMins1,
			P.SPEC_HOLOT2,
			P.SPEC_HOLOTMins2,
			p.ActHolOTMins,
			p.ActOffOTMins,
			p.ActHolOT,
			p.ActOffOT,p.PermissionHrs,P.PermissionHrsInMins,P.PermissionStatus,
			InLocation ,
			OutLocation,
			'''' In_Latitude,
			'''' In_Longitude,
			'''' Out_Latitude,
			'''' Out_Longitude
			
FROM TA_TBL_PROCESSEDDATA P LEFT OUTER JOIN TA_Tbl_Shift ON P.Shift_Id = TA_Tbl_Shift.Shift_Id







'
GO
/****** Object:  StoredProcedure [dbo].[VerifyWarningAlertMsgTriggerredAlready]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VerifyWarningAlertMsgTriggerredAlready]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-Nov-2019 05:30 PM>
-- Description:	<Verifying already alert message sent or not to current employee on this month>
-- VerifyWarningAlertMsgTriggerredAlready  787,1
-- =============================================
CREATE PROCEDURE [dbo].[VerifyWarningAlertMsgTriggerredAlready] 
	@EmployeeID VARCHAR(50),
	@scheduleID BIGINT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @FromDate DATETIME
	DECLARE @Todate DATETIME
	DECLARE @isCross INT
	--Which is used to define cross month need to check or straight case
	--1 means cross month. 0 means straight case.
	SET @isCross=0
	DECLARE @ScheduleName VARCHAR(50)
	SET @ScheduleName=''''
	--Get Current Schedule Name
	SELECT @ScheduleName=ScheduleName FROM TA_Tbl_EmailSchedule WHERE ScheduleId=@scheduleID AND IsDeleted=0
	--Get current Date here
	Declare @CurrentDate DATETIME
	SET @CurrentDate=CONVERT(VARCHAR(11),DATEADD(d,0,GETDATE()))
	IF(@isCross=0)
	BEGIN
		SELECT @FromDate=DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate),0)
	END
	ELSE
	BEGIN
		DECLARE @currentDay INT
		SET @currentDay=DATEPART(d,@CurrentDate)
		--from 1 to 15 it will check the previous month 16 to till date. after that it will check the current month 16 to current date 
		IF(@currentDay>=1 and @currentDay<=15)
		BEGIN
			SELECT @FromDate=DATEADD(d,15,DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate)-1,0))
		END
		ELSE
		BEGIN
			SELECT @FromDate=DATEADD(d,15,DATEADD(MONTH,DATEDIFF(MONTH,0,@CurrentDate),0))
		END			
	END
	SET @Todate=@CurrentDate
	--SELECT @FromDate,@Todate
	IF(@ScheduleName=''Warning Message - Late Entry'' OR @ScheduleName=''Warning Message - Early Exit'')
	BEGIN
		IF EXISTS(SELECT ESS.Status FROM TA_Tbl_EmailSchedule ES
		INNER JOIN TA_tbl_EmailScheduleStatus ESS on ES.ScheduleId=ESS.ScheduleId
		INNER JOIN TA_Tbl_EmailScheduled_Employees ESE on ESS.ScheduleId=ESE.ScheduleId
		WHERE ESS.ScheduleId=@scheduleID and ESE.Employee_id=@EmployeeID and ESS.Status=1
		and (ESS.DurationFrom between @FromDate and @Todate))
		BEGIN
			SELECT 1 ''Sent''
		END
		ELSE
		BEGIN
			SELECT 0 ''Sent''
		END
	END
	ELSE
	BEGIN
		SELECT 0 ''Sent''
	END	
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMinTime]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMinTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckMinTime  
Description : check minimum time entry  
Tables Included : TA_Tbl_Clk_RawData,  
Created By : Kumuthini.L  
Created On : 17-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMinTime]
	-- Add the parameters for the stored procedure here
	(@EmployeeID VarChar(50))
AS
BEGIN
	Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 ClkID VarChar(255),	
	 MinTime Varchar(225),
	 MaxTime Varchar(225),
	 ADate varchar(50)
	)
	Declare @TestDate as Varchar(50)
	Declare @MinTime as Varchar(50)
	Declare @MaxTime as Varchar(50)
	Declare @Noon as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select distinct CLK_DATE From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID
	OPEN c 
	FETCH NEXT FROM c INTO @TestDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Select @MinTime = Min(CONVERT(DateTime, CLK_TIME, 118)) From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID And CLK_DATE = @TestDate
	Select @MaxTime = Max(CONVERT(DateTime, CLK_TIME, 118)) From TA_Tbl_Clk_RawData Where CLK_CARDID = @EmployeeID And CLK_DATE = @TestDate
	Select @MinTime =
	(Case len (datepart(hh, @MinTime))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(datepart(hh, @MinTime)) + '':'' +
	Case len (datepart(mi, @MinTime))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(datepart(mi, @MinTime))), 
	@MaxTime =
	(Case len (datepart(hh, @MaxTime))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(datepart(hh, @MaxTime)) + '':'' +
	Case len (datepart(mi, @MaxTime))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(datepart(mi, @MaxTime)))  
	Insert InTo #TempReportTable (ClkID, MinTime, MaxTime, ADate) values (@EmployeeID, @MinTime, @MaxTime, @TestDate)
	FETCH NEXT FROM c INTO @TestDate
	END 
	Select ClkID, MinTime, MaxTime, ADate From #TempReportTable
	CLOSE c 
	DEALLOCATE c
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMaxHoliday]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMaxHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckMaxHoliday    
Description : check maximun holidays  
Tables Included : TA_Tbl_HolidaySettings, TA_tbl_YearSetting    
Created By : Janakaraj.P   
Created On : 20-Aug-2007  
Modified By :    
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMaxHoliday]
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM TA_Tbl_HolidaySettings hs 
	inner join TA_tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId where ys.IsActive=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntryUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_CheckManualODEntryUpdate]  19,''a006'',''02/Oct/2012'',''10:47:28 AM'','''',''''
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntryUpdate]
(
	@MID int,
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)
	DECLARE @OutDateTime VARCHAR(50)
	 IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')
	   BEGIN
			SET @InDateTime = @ManualInDate + '' '' + @ManualInTime
			SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
			if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status in (''Forwarded'',''Pending'') and  
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
		  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status = ''Approved''  and 
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Id <> @MID and ManualTimeEntry_Status = ''Approved'' and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ '' '' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + '' '' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ '' '' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + '' '' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		  End 
		  else
		  Begin
		   select 0 as ManualEntry
		  End
	   END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntryForODUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntryForODUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_CheckManualODEntryForODUpdate]  3,''100'',''2016-03-15'',''09:00:00 AM'',''2016-03-15'',''06:00:00 PM''
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntryForODUpdate]
(
	@OD int,
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)
	DECLARE @OutDateTime VARCHAR(50)
	IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')
	   BEGIN
			SET @InDateTime = @ManualInDate + '' '' + @ManualInTime
			SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
			if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and  
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
		  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and 
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and OnDuty_ID <> @OD and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ '' '' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + '' '' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ '' '' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + '' '' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		  End 
		  else
			  Begin
			   select 0 as ManualEntry
			  End
	   END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualODEntry]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualODEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_CheckManualODEntry ''609620'',''02/05/2014'',''11:30 PM'',''02/06/2014'',''12:30 AM''
--Modified by A.Amsaveni on 07/10/2013 to allow to save continous days of night shift 
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualODEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35)
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	 IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
	 BEGIN  
		SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
		SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  	
		if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status in (''Forwarded'',''Pending'',''Approved'') and  
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
		  BEGIN
			 select 1 as ManualEntry
		  END
	  else if((SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status = ''Approved''  and 
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)))) )>0)
	  Begin
		   create table #TempManualEntries(ManualTimeEntry_InDate varchar(40),ManualTimeEntry_InTime varchar(40),ManualTimeEntry_OutDate varchar(40),ManualTimeEntry_OutTime varchar(40))
		   insert into #TempManualEntries 
		   select ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime
		   from TA_tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and IsOnDuty=1 and ManualTimeEntry_Status = ''Approved'' and   
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		 OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))
		   create table #TempClockDetailsEntries(InDate varchar(40),InTime varchar(40),OutDate varchar(40),OutTime varchar(40))
		   insert into #TempClockDetailsEntries
		   select Clk_InDate,Clk_Intime,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails CD
		   inner join TA_Tbl_Employee E on E.Employee_Code_Id = @EmpCode
		   where E.IsDeleted=0 and E.Employee_Status=1 and CD.IsVoid =0 and CD.Clk_EmpId = E.SwipeCardNo
		   and ((Clk_InDate+ '' '' + convert(varchar(15),Clk_Intime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_InDate,103) + '' '' + ManualTimeEntry_InTime as datetime) from #TempManualEntries)
		   or (Clk_OutDate+ '' '' + convert(varchar(15),Clk_OutTime,108)) in (select cast(CONVERT(varchar(11),ManualTimeEntry_OutDate,103) + '' '' + ManualTimeEntry_OutTime as datetime) from #TempManualEntries))
		   select count(*) as ManualEntry from #TempClockDetailsEntries
		End 
	  else
		  Begin
		   select 0 as ManualEntry
		  End
	  END  
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveWithPermission]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveWithPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_CheckLeaveWithPermission ''02/19/2008'',''02/20/2014'',29
Description		:	Check Permission Count for Leave Dates
Tables Included		:	TA_Tbl_Permision
Created By		:	Prabakaran
Created On		:	15-Mar-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveWithPermission] 
@LeaveFromDate datetime,
@LeaveToDate datetime,
@EmployeeId int
as
BEGIN
	SET NOCOUNT ON;
	select count(Permission_Id) as PermissionCount from TA_Tbl_Permission where (Permission_Date between @LeaveFromDate and @LeaveToDate) 
	and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getmastersSubMenu]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getmastersSubMenu]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getmastersSubMenu]
@ReportsMenu int	
AS
BEGIN	
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from TA_Tbl_Page where ParentIdForSubMenu=@ReportsMenu 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelName_FromLevelID]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLevelName_FromLevelID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Arun vinoth
-- Create date: 14 July 2007
-- Description:	Get Level name from LevelID
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLevelName_FromLevelID]
	-- Add the parameters for the stored procedure here
@LevelID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;
    -- Insert statements for procedure here
SELECT levelName FROM TA_Tbl_Level WHERE levelID = @LevelID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMailConfiguration]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMailConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetMailConfiguration]
AS
BEGIN
     select * from TA_Tbl_MailConfiguration
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntryForImport]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntryForImport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckManualEntry  ''120'',''2010/03/31'',''04:06:37 PM'','' '','' '','' ''  
Description : check manual entry for import perpose   
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Karthikeyan.R
Created On : 09-Apr-2015
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntryForImport](
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35),
	@PunchType varchar(50))  
AS  
BEGIN
SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')  
	   BEGIN  
	 SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
	 SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0 and ManualTimeEntry_InPunchType=@PunchType
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')  
	   BEGIN  
	  SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
	 SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0 and ManualTimeEntry_OutPunchType=@PunchType
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
	   BEGIN  
			SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
			SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and    
	  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime) and ManualTimeEntry_InPunchType=@PunchType) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime) and ManualTimeEntry_InPunchType=@PunchType))
	 OR   
	  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) and ManualTimeEntry_InPunchType=@PunchType) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) and ManualTimeEntry_InPunchType=@PunchType)))   
	   END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry_Group]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntry_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckManualEntry_Group
Description : check manual entry    
Tables Included : TA_Tbl_ManualTimeEntry    
Created By : Sashma   
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntry_Group]
(
@ManualInDate varchar(15),
@ManualInTime varchar(35),
@ManualOutDate varchar(15),
@ManualOutTime varchar(35),
@xml xml
)  
AS  
BEGIN
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	Declare @Index int
	Set @Index = 0;
	IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')  
	   BEGIN  
		 SET @InDateTime = @ManualInDate + '' '' + @ManualInTime 
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
		 SELECT xm.EmpID as EmployeeAutoId  FROM TA_Tbl_ManualTimeEntry
		 INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId varchar(50) ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
		 WHERE (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0  
		  Exec sp_xml_removedocument @Index
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')  
	   BEGIN  
	  SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
	   SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_ManualTimeEntry 
	   INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId varchar(50) ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
	   WHERE (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0  
	   Exec sp_xml_removedocument @Index
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
	   BEGIN  
	   SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
	   SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml 
		   SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_ManualTimeEntry 
		   INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId varchar(50) ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmployeeId = ManualTimeEntry_Employee_Id  
		   WHERE Isdeleted=0 and    
		  ((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		  OR   
		  ((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))   
	  Exec sp_xml_removedocument @Index
	   END 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckManualEntry  ''105'',''2009/04/02'',''04:06:37 PM'','' '','' ''  
Description : check manual entry    
Tables Included : TA_Tbl_ManualTimeEntry    
Created By : Kumuthini.L    
Created On : 17-Aug-2007  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckManualEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(35),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(35)
)
AS  
BEGIN
	Set NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(30)  
	DECLARE @OutDateTime VARCHAR(30)  
	IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')  
  BEGIN  
		SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
		SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@InDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@InDateTime as DateTime)) or ((ManualTimeEntry_InDate+ManualTimeEntry_InTime) = Cast(@InDateTime as DateTime))) and Isdeleted=0  
	END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')  
  BEGIN  
		SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
		SELECT COUNT(*) as ManualEntry  FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and (((ManualTimeEntry_InDate+ManualTimeEntry_InTime) <= Cast(@OutDateTime as DateTime) and (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) >= Cast(@OutDateTime as DateTime)) or ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) = Cast(@OutDateTime as DateTime))) and Isdeleted=0  
	END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
  BEGIN  
		SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
    SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
    SELECT COUNT(*) as ManualEntry FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id=@EmpCode and Isdeleted=0 and    
		((((ManualTimeEntry_InDate+ManualTimeEntry_InTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((ManualTimeEntry_OutDate+ManualTimeEntry_OutTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)))
		OR   
		((Cast(@InDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (ManualTimeEntry_InDate+ManualTimeEntry_InTime) AND (ManualTimeEntry_OutDate+ManualTimeEntry_OutTime))))   
	END   
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPageStandard]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMandatoryPageStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
 -- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMandatoryPageStandard]  
AS  
BEGIN  
 select MandatoryChecking from TA_Tbl_PageMandatoryFlagStandard  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMandatoryPage]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMandatoryPage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckMandatoryPage]
AS
BEGIN
	select MandatoryChecking from TA_Tbl_PageMandatoryFlag
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[DeleteCustomDataBasedOnOptionType]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DeleteCustomDataBasedOnOptionType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name : DeleteCustomDataBasedOnOptionType  
Description : delete custom datas based on the option type.  
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[DeleteCustomDataBasedOnOptionType]
(
 @OptionType varchar(50),
 @DataType varchar(50),
 @CompanyID int	
)
AS
BEGIN
  delete from TA_ExportData_FieldData where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeaveAvailed]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeaveAvailed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_EmpLeaveAvailed ''94''
-- select * from ta_tbl_leaveApplication where employee_id=32 and yearSettings_Id=3 and type=''Leave''
--update ta_tbl_leaveApplication set numberofDays=4.0 where CheckedIDs=49 LeaveApplication_Id=512
-- =============================================
-- Author:		<Angeswaran.S>
-- Create date: <06-Apr-2012>
-- Description:	<Pop up window for Employee Leave availed>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLeaveAvailed]
	-- Add the parameters for the stored procedure here
	@Employee_code_Id varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	Declare @EmployeeId int	
	Declare @StartMonth int
	Declare @RemainingMonth int
	Declare @Startyear int
	Declare @EndYear int
	--Declare @RemainingMonthUpdate int
	select @EmployeeId=Employee_Id from TA_Tbl_Employee where Employee_Code_Id= @Employee_code_Id
	select @StartMonth=DATEPART(MONTH ,FromDate),@Startyear=StartYear,@EndYear=EndYear from TA_Tbl_YearSetting where IsActive=1 
	--set @RemainingMonthUpdate=@StartMonth
	select DATENAME(month,LA.Leave_FromDate)  as month,sum(LA.NumberOfDays) as NumberofDays,
	case 				
		when DATENAME(month,LA.Leave_FromDate)=''January'' then 1
		when DATENAME(month,LA.Leave_FromDate)=''February'' then 2
		when DATENAME(month,LA.Leave_FromDate)=''March'' then 3
		when DATENAME(month,LA.Leave_FromDate)=''April'' then 4	
		when DATENAME(month,LA.Leave_FromDate)=''May'' then 5    
		when DATENAME(month,LA.Leave_FromDate)=''June'' then 6
		when DATENAME(month,LA.Leave_FromDate)=''July'' then 7      
		when DATENAME(month,LA.Leave_FromDate)=''August'' then 8      
		when DATENAME(month,LA.Leave_FromDate)=''September'' then 9 
		when DATENAME(month,LA.Leave_FromDate)=''October'' then 10
		when DATENAME(month,LA.Leave_FromDate)=''November'' then 11 
		when DATENAME(month,LA.Leave_FromDate)=''December'' then 12 
    end ''OrderBy'' into #FinalLeaveApplicationData
	from TA_Tbl_LeaveApplication LA 
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id where LA.Employee_Id=@EmployeeId and YS.IsActive=1 and 
	LA.Type <> ''Comp Off'' and LA.IsDeleted=0 and LA.Status=''Approved'' group by DATENAME(month,LA.Leave_FromDate)	
	Update #FinalLeaveApplicationData set MONTH=MONTH +'' - '' +CONVERT(varchar(20), @Startyear) where OrderBy >=@StartMonth
	Update #FinalLeaveApplicationData set MONTH=MONTH +'' - '' +CONVERT(varchar(20),@EndYear) where OrderBy<@StartMonth
	Select MONTH,NumberofDays from #FinalLeaveApplicationData Order by OrderBy
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTStatus]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffOTStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	: Proc_TA_EmployeeOTStatus  
Description		: To Update the OverTime Status in ta_tbl_processedData  table
Tables Included : ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		: A.K.T.MOORTHI
Created On		: 22-July-2013
Modified By :  
Modified On :  
	EXEC [Proc_TA_EmployeeCompOffOTStatus]	''<NewDataSet>
  <Status>
    <Process_Rec_ID>1944</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>04/02/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>06:00</HrsExtra>
    <ExtraMins>360</ExtraMins>
    <OverTimeStatus>Approved</OverTimeStatus>
    <CompOffEligible>1</CompOffEligible>
    <OTEligible>1</OTEligible>
    <Status>Pending</Status>
  </Status>
  <Status>
    <Process_Rec_ID>1945</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>04/06/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>06:00</HrsExtra>
    <ExtraMins>360</ExtraMins>
    <OverTimeStatus>Approved</OverTimeStatus>
    <CompOffEligible>1</CompOffEligible>
    <OTEligible>1</OTEligible>
    <Status>Pending</Status>
  </Status>
  <Status>
    <Process_Rec_ID>2065</Process_Rec_ID>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>Emp5</Employee_Code_Id>
    <Date>05/01/2012</Date>
    <Employee_FirstName>Employee FIve LastNAme</Employee_FirstName>
    <Level_x0020_Name>Auto ID System</Level_x0020_Name>
    <HrsExtra>01:00</HrsExtra>
    <ExtraMins>60</ExtraMins>
    <OverTimeStatus>Pending</OverTimeStatus>
    <CompOffEligible>0</CompOffEligible>
    <OTEligible>0</OTEligible>
    <Status>Pending</Status>
  </Status>
</NewDataSet>''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTStatus]
	@Xml XML
As
BEGIN 
	DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,[Date] DATETIME, HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT)
	DECLARE @Index INT
	SET @Index = 0
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	INSERT INTO @TblRecords
		SELECT * FROM OPENXML(@Index, ''/NewDataSet/ColumnValues'')
		WITH(
			Process_Rec_ID BIGINT ''Process_Rec_ID'',
			Employee_Id INT ''Employee_Id'',
			[Date] DATETIME ''Date'',
			HrsExtra VARCHAR(5) ''HrsExtra'',
			ExtraMins INT ''ExtraMins'',
			[Status] VARCHAR(50) ''Status'',
			CompOffEligible BIT ''CompOffEligible'',
			OTEligible BIT ''OTEligible''
		   ) AS OT 
	UPDATE TA_Tbl_ProcessedData SET OvertimeStatus = OT.OverTimeStatus FROM TA_Tbl_ProcessedData PD 	
	INNER JOIN @TblRecords OT ON OT.Process_RecID = PD.Process_Rec_ID
	EXEC sp_xml_removedocument @Index
	INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible)
		SELECT * FROM @TblRecords WHERE Process_RecID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus)
	UPDATE TA_Tbl_OverTimeStatus SET 
		Process_RecID = TR.Process_RecID,
		Employee_Id = TR.Employee_Id,
		[Date] = TR.[Date],
		HrsExtra = TR.HrsExtra,
		ExtraMins = TR.ExtraMins,
		OverTimeStatus = TR.OverTimeStatus,
		CompOffEligible = TR.CompOffEligible,
		OTEligible = TR.OTEligible
	FROM TA_Tbl_OverTimeStatus OTS
	INNER JOIN @TblRecords TR ON TR.Process_RecID = OTS.Process_RecID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[EmpProcessStatus]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpProcessStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[EmpProcessStatus] 
as
declare @Process_Rec_ID varchar(20)
declare @Employee_Code varchar(20)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @HrsWork varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @eHours int
update dbo.TA_Tbl_ProcessedData set processflag=0  where left(HrsWork,2) >12
declare emp_ReProcess cursor for 
select  Process_Rec_ID,Employee_Code_Id,Date,Shift_Id,HrsWork,NormOT,OffOT,HolOT  from dbo.TA_Tbl_ProcessedData WHERE
      Attendance=''Present''and FNAttendanceCode=''Absent'' and InTime is not null and OutTime is not null and left(HrsWork,2)<24 and date >dateadd(d,-60,getdate())  order by Process_Rec_ID
open emp_ReProcess
fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@HrsWork,@NormOT,@OffOT,@HolOT
while (@@fetch_status = 0 )
begin
		update dbo.TA_Tbl_ProcessedData set FNAttendanceCode=''Present'',ANAttendanceCode=''Present'' where Process_Rec_ID=@Process_Rec_ID 
--set @eHours =datediff(hour,''00:00'',@HrsWork)
--if @eHours>7
--begin
		--update dbo.TA_Tbl_ProcessedData set ANAttendanceCode=''Present'' where Process_Rec_ID=@Process_Rec_ID
--end
  fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@HrsWork,@NormOT,@OffOT,@HolOT
end   
deallocate emp_ReProcess
' 
END
GO
/****** Object:  StoredProcedure [dbo].[EmpOUTReEntry]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpOUTReEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[EmpOUTReEntry] 
as
declare @timeVal int
declare @CLK_ID int
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
set @timeVal=15
declare emp_OuTReEntry cursor for 
select Clk_Id,Clk_EmpId,Clk_outDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails WHERE
      Clk_inTime IS NULL AND Clk_outTime IS NOT NULL and clk_outdate< dateadd(d,-1,getdate()) and isvoid=0 and clk_outdate> dateadd(m,-2,getdate()) 
order by clk_empid,clk_outdate,clk_outtime
open emp_OuTReEntry
fetch emp_OuTReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
--set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and clk_indate=@CLK_DATE and clk_inTime>dateadd(mi,-5,@CLK_TIME) and clk_inTime<dateadd(mi,5,@CLK_TIME) )
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and Clk_OutDate=@CLK_DATE and Clk_OutTime>=dateadd(mi,- @timeVal,@CLK_TIME) and isvoid=0 and Clk_OutTime<=dateadd(mi,@timeVal,@CLK_TIME))
if @eCount>0
	begin 
--		delete from  dbo.TA_Tbl_ClockDetails where  CLK_ID=@CLK_ID
update dbo.TA_Tbl_ClockDetails set isvoid=''1'' where  CLK_ID=@CLK_ID
--  and clk_EmpID=@CLK_CARDID and Clk_OutDate=@CLK_DATE
	end
--else
--begin
--end
  fetch emp_OuTReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_OuTReEntry' 
END
GO
/****** Object:  StoredProcedure [dbo].[EmpINReEntry]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpINReEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[EmpINReEntry] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
set @timeVal=15
declare emp_ReEntry cursor for 
--select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime from TA_Tbl_ClockDetails WHERE
  --    Clk_outTime IS NULL AND Clk_inTime IS NOT NULL and clk_indate< dateadd(d,-1,getdate())
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime from TA_Tbl_ClockDetails WHERE
Clk_outTime IS NULL AND isvoid=0 and Clk_inTime IS NOT NULL and 
clk_indate< dateadd(d,-1,getdate()) and clk_indate> dateadd(m,-2,getdate())  order by clk_empid,clk_indate,clk_intime desc
open emp_ReEntry
fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
--set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and clk_indate=@CLK_DATE and clk_inTime>dateadd(mi,-5,@CLK_TIME) and clk_inTime<dateadd(mi,5,@CLK_TIME) )
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_DATE  AND clk_inTime>=dateadd(mi,- @timeVal,@CLK_TIME) and isvoid=0 and clk_inTime<=dateadd(mi,@timeVal,@CLK_TIME) )
if (@eCount>0)
	begin 
--		delete from  dbo.TA_Tbl_ClockDetails where  CLK_ID=@CLK_ID
update dbo.TA_Tbl_ClockDetails set isvoid=1 where  CLK_ID=@CLK_ID
	end
--else
--begin
--end
  fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_ReEntry' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayroll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForPayroll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_EmployeeDetailsForPayroll  
Description : Select all Active Employee Details for Payroll
Tables Included : TA_Tbl_Employee, TA_Tbl_EmployeePay  
Created By : Kumuthini.L
Created On : 19-Apr-2008
Modified By :  Kumuthini.L
Modified On :  21-Apr-2008
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayroll]
(
    @Type CHAR(1),
    @EndDate NVARCHAR(10),
    @SwipeCardNo NVARCHAR(10)
)
AS
IF(@Type = ''A'') -- Selecting all Active Employees for Payroll
	BEGIN				
		SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,EP.BasicPay
		FROM TA_Tbl_Employee E
		INNER JOIN TA_Tbl_EmployeePay EP ON EP.EmployeeId = E.Employee_Id 
		--INNER JOIN TA_Tbl_YearSetting Y ON Y.YearSettings_Id = EP.YearSettingID
		WHERE Employee_Firstname <> ''Administrator'' AND  E.IsDeleted = 0 AND E.Employee_Status = 1 AND
                           EP.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeePay WHERE EffectiveDate <= @EndDate AND EmployeeId = E.Employee_Id) 
	END
ELSE IF(@Type = ''P'') -- Getting the Details for a particular Swipe Card No
	BEGIN				
		SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,EP.BasicPay
		FROM TA_Tbl_Employee E
		INNER JOIN TA_Tbl_EmployeePay EP ON EP.EmployeeId = E.Employee_Id 
		--INNER JOIN TA_Tbl_YearSetting Y ON Y.YearSettings_Id = EP.YearSettingID
		WHERE Employee_Firstname <> ''Administrator'' AND E.SwipeCardNo = @SwipeCardNo AND E.IsDeleted = 0 AND E.Employee_Status = 1 AND
                           EP.EffectiveDate = (SELECT MAX(EffectiveDate) FROM TA_Tbl_EmployeePay WHERE EffectiveDate <= @EndDate AND EmployeeId = E.Employee_Id) 
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLocationDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLocationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLocationDetails]
	@landMarkID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * from Ta_tbl_LandMarks where (@landMarkID=0 or id=@landMarkID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeavesUnplanned]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeavesUnplanned]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		
-- ALTER  date:
-- Description:	
-- Modified By : 
-- Modified On : 
-- Description :
-- [Proc_TA_RptDailyLeavesUnplanned] ''02/09/2010'',''1,2,3,4,5,6,7'',''P''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeavesUnplanned]
	@fromDat datetime,
	@LevelID varchar(8000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''		
		set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, ''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name''
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' where dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlQuery = @sqlQuery + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102)))''
		if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
		end	
		declare @IntimationType as varchar(1)
		set @IntimationType=''U''
		if (@IntimationType=''P'') --planned leave
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.IntimationType=''''P'''' ''
		end		
		if (@IntimationType=''U'') -- unplanned leave
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.IntimationType <> ''''P'''' ''
		end
create table #EmpLeave(Employee_Id varchar(15),
applicationDate datetime,
fromDate datetime,
todate datetime,
NumberOfDays decimal(18,1),
leavetype varchar(100),
Leave_SessionFrom varchar(100),
Leave_SessionTo varchar(100),
Reason varchar(1050),
status varchar(50),
Remarks varchar(1050),
TitleName varchar(500),
empname varchar(500),
[name] varchar(500),
)
insert into #EmpLeave exec(@sqlQuery)
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
select empname as ''Executive Name'',name as Department,fromDate as ''FromDate'',toDate as ToDate from #EmpLeave order by fromDate,Employee_Id asc
--select * from #EmpLeave order by Employee_Id,fromDate asc
drop table #EmpLeave
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic1]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamic1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--select * from ta_tbl_processeddata where date between ''2009/10/01'' and ''2009/10/30'' and employee_code_id=''501'' order by date
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
--drop procedure Proc_TA_RptDetailAttendanceDynamic
--Proc_TA_RptDetailAttendanceDynamic ''2010/01/01'',''2010/01/31'','''','''',''115'',''SuperAdmin'',''0'',''''
create     PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic1] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
set @fromDat=''2010/01/01''
set @ToDat=''2010/01/31''
set @empId=''''
set @EmployeeName=''''
set @LevelID=''110''
set @UserGroupName=''SuperAdmin''
set @GradeLevel=''0''
set @EmpSwipeCard=''''
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
-------Start
		declare @query as varchar(8000)
		set @query=''''
		set @query = ''select isnull(Employee_FirstName,'''''''') + SPACE(1) + isnull(Employee_MiddleName,'''''''')+ SPACE(1) + isnull(Employee_LastName,'''''''')  + ''''$'''' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],''
	    	set @query = @query + '' ''''Present'''' = sum( CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END When ''''|'''' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		set @query = @query + '' ''''Absent'''' = sum( CASE FNAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		--angler Specific
		set @query = @query + '' ''''Weekly Off'''' = sum( CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		set @query = @query + '' ''''Holiday'''' = sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		set @query = @query + '' ''''CompOff'''' = sum( CASE FNAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		set @query = @query + '' ''''LOP'''' = sum( CASE FNAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
		-------
		set @query = @query + '' ''''Total Late Days'''' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , ''
		set @query = @query + '' ''''Total Late Hours'''' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), ''
		--angler Specific
		set @query = @query + '' ''''Total Early Out Days'''' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , ''
		set @query = @query + '' ''''Total Early Out Hours'''' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), ''
		set @query = @query + '' ''''Total OT Days'''' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , ''
		set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE otmins WHEN otmins THEN  otmins END), ''
		set @query = @query + '' ''''Norm OT Hrs''''=sum(CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''WeekOff OT Hrs''''=sum(CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''Holiday OT Hrs''''=sum(CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''
--For approved only
		--set @query = @query + '' ''''Total OT Days'''' =  count(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END) , ''
		--set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END), ''
		--set @query = @query + '' replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as Level,''
		--set @query = @query + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,''
		DECLARE @sql varchar(8000)
		DECLARE @sumfunc varchar(2000)
		set @sumfunc = ''sum(Totaldays)''
		DECLARE @sumfunc1 varchar(1000)
		declare @pivot varchar(1000)
		declare @pivot1 varchar(1000)
		--set @pivot =''LeaveCode''
		set @pivot =''FNAttendanceCode''
		set @pivot1 =''ANAttendanceCode''
---- get the leave type details and form query
		EXEC (''SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2'')
CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
(
	[pivot] ASC
) ON [PRIMARY]
		exec (''INSERT INTO ##pivot select top 5 LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
		SELECT @sql='''',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, '' END)'' )
		declare @delim  varchar(1)
		SELECT  @delim=CASE Sign( CharIndex(''char'', data_type)+CharIndex(''date'', data_type) ) 
		WHEN 0 THEN '''' ELSE '''''''' END 
		FROM tempdb.information_schema.columns 
		WHERE table_name=''##pivot'' AND column_name=''pivot''
		select @sql=''''
		SELECT @sql=@sql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
		+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
--		+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN '' ) + '', '' 
		+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
		+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
		FROM ##pivot order by [pivot]
		if len(@sql)>0
			SELECT @sql=left(@sql, len(@sql)-1)
-- end of leave type
---- other leave type
		declare @SelectedLeaveType as varchar(500)
		set @SelectedLeaveType =''''
		SELECT @SelectedLeaveType=@SelectedLeaveType + '''''''' + convert(varchar(100), [pivot]) + '''''' , '' 
		FROM ##pivot
delete  from ##pivot
		if len(@SelectedLeaveType)>0
			begin
				SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
				exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0 and leavetype not in ('' + @SelectedLeaveType + '' )  order by leavetype'')
			end
		else
			begin
				exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
			end
		--delete  from ##pivot
		declare @othSql as varchar(5000)
		select @othSql=''''
		--SELECT @othSql=@othSql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
		SELECT @othSql=@othSql + '' '' 
		+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
		+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
		+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
		FROM ##pivot order by [pivot]
		if (len(@othSql)>0) 
			begin
				SELECT @othSql=left(@othSql, len(@othSql)-1) + ''+''
			end
			set @query = @query + '' ''''Others'''' =  '' + @othSql + '' sum( CASE FNAttendanceCode WHEN ''''RH'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)''
			set @query = @query + '' + sum( CASE ANAttendanceCode WHEN ''''RH'''' THEN Case TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END),''
--end of other leave type
if(len(@sql)=0)
begin	
SET @query=left(@query, len(@query)-1)
end
		set @query  = @query + @sql
		declare @query1 as varchar(8000) 
		set @query1=''''
		set @query1 = @query1 + '' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo''
		set @query1 = @query1 + '' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @query1 = @query1 + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id ''
		set @query1 = @query1 + '' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId''
		set @query1 = @query1 + '' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID ''
		end
		set @query1 = @query1 + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @query1 = @query1 + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @query1 = @query1 + '' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1''
		set @query1 = @query1 + '' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
		set @query1 = @query1 + '' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		if not(@EmployeeName='''')
		begin
			set @query1 = @query1 + '' and ta_tbl_employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		end
		If Not (@EmpSwipeCard = '''')  
			 Begin  
			  Set @query1 = @query1 + ''And ta_tbl_employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			 End
		if not (@empId='''')
		begin
			set @query1 = @query1 + '' and ta_tbl_employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
		if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @query1 = @query1 + '' and #EmpLevel.LevelId IN ( '' + @LevelId + '') '' 
		end	
		set @query1 = @query1 + '' group by ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname''
		DROP TABLE ##pivot
		exec  (@query + '' '' + @query1)
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
/*
select ''a$EIT'' as [Employee Name],''1'' as [Employee Id],''20'' as Present,''2'' as Absent,''4'' as [Weekly Off],''1'' as Holiday,''0'' as CompOff
,''0'' as LOP
,''0'' as [Total Late Days]
,''0'' as [Total Late Hours]
,''0'' as [Total Early Out Days]
,''0'' as [Total Early Out Hours]
,''0'' as [Total OT Days]
,''0'' as [Total Ot Hours]
,''0'' as [Norm Ot Hrs]
,''0'' as [WeekOff OT Hrs]
,''0'' as [Holiday OT Hrs]
,''0'' as Others
,''0'' as CL
,''0'' as ML
*/
END
' 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenuForExpress]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReportsSubMenuForExpress]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
/*
--	Create By		:	Thilakraj.C
--	Create On		:	26-Nov-2013
--  Reson : For Express edition creation
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ReportsSubMenuForExpress] 
	-- Add the parameters for the stored procedure here
	@ReportsMenu varchar(50),
	@groupId int,
 @strType varchar(20)   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
  if(@strType=''Standard'')
  begin  
    if(@ReportsMenu = ''ReportsMenu'')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1)
			and ur.groupId=@groupId and P.pageId not in 			
			(20,24,25,69,96,97,98,110,133,93,116,127,130,118,174) 
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			and P.pageId not in (20,24,25,69,96,97,98,110,133,93,116,127,130,118,174) 
			order by P.pageId
		end
	End
	else if(@strType=''Express'')
	begin  
    if(@ReportsMenu = ''ReportsMenu'')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) 
			and ur.groupId=@groupId and P.pageId not in (20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,76,60,116,118,127,130,117,174,175) 
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			and P.pageId not in (20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,76,60,116,118,127,130,117,174,175) 
			order by P.pageId
		end
	End
else
begin
if(@ReportsMenu = ''ReportsMenu'')
		begin
			select distinct ParentIdForSubMenu from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId 
			where P.ParentIdForSubMenu is not null and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			order by P.orderBy
		end
End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReportsSubMenu]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReportsSubMenu]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_ReportsSubMenu] 149,7
--	Modified By		:	Manjula.P
--	Modified On		:	04-Oct-2013
--	Descriptions	:	Adding order by P.pageId for displaying menu order correctly. : Mantis : 0019213
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ReportsSubMenu] 
	-- Add the parameters for the stored procedure here
	@ReportsMenu varchar(50),
	@groupId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if(@ReportsMenu = ''ReportsMenu'')
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId
			where (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
		end
	else 
		begin
			select * from TA_Tbl_Page P inner join ta_tbl_userRights UR on P.pageId=UR.pageId where P.ParentIdForSubMenu=@ReportsMenu
			and (ur.addPrv=1 or ur.modifyPrv=1 or ur.deletePrv=1 or ur.viewPrv=1) and ur.groupId=@groupId
			--Added by Manjula.P on 04-Oct-2013 for getting Employee order wise Mantis : 0019213 
			order by P.pageId
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptAttendanceDetails]
(@EmployeeID VarChar(50), @LevelID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Designation VarChar(255),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @AbsentDays as varchar(50)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)	
	Declare @PresentDays As Varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Set @AbsentDays = ''0''
	Set @TotalLeaves = ''0''
	Set @ESILeaves = ''0''
	Set @PresentDays = ''0''
	Set @LateComingDays = ''0''
	Set @TotalLateEntryHrs = ''00:00''
	Set @LateExitDays = ''0''
	Set @TotalLateExitHrs = ''00:00''
	Declare @TestEmployeeId as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Select @AbsentDays = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else ''0'' end From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND Attendance=''Absent''
	Select @TotalLeaves = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else ''0'' end From TA_Tbl_ProcessedData PD  where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND (PD.Attendance = ''CL'' or PD.Attendance = ''EL'' or PD.Attendance = ''SL'')
    Select @ESILeaves = case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else ''0'' end From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId and PD.Attendance = ''ESI'' And Date >= @FromDate and Date <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 as varchar)
	Select @LateComingDays= case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else ''0'' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND LateIn <> ''00:00:00'' AND LateIn <> ''0'' AND LateIn is not null
	--Select 	@TotalLateEntryHrs=case when sum(PD.HrsLess) is not null then sum(PD.HrsLess) else ''0'' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND LateIn <> ''00:00:00'' AND LateIn <> ''0'' AND LateIn is not null
	Select @LateExitDays= case when sum(PD.Process_Rec_ID) is not null then sum(PD.Process_Rec_ID) else ''0'' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND HrsOT <> ''0'' AND HrsOT is not null
	--Select 	@TotalLateExitHrs=case when sum(PD.HrsOT) is not null then sum(PD.HrsOT) else ''0'' end  From TA_Tbl_ProcessedData PD where PD.Employee_Code_Id = @TestEmployeeId  And Date >= @FromDate and Date <= @ToDate AND HrsOT <> ''0'' AND HrsOT is not null
	Set @SelectSQL = '' '' 
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + '' T.TitleName AS Designation, ''
    Set @SelectSQL = @SelectSQL + '''''''' + @PresentDays + '''''','''''' + @AbsentDays + '''''', '''''' + @LateComingDays + '''''','''''' + @TotalLateEntryHrs + '''''', '''''' + @LateExitDays + '''''', '''''' + @TotalLateExitHrs + '''''', '''''' + @TotalLeaves + '''''', '''''' + @ESILeaves + '''''' FROM TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + '' TA_Tbl_Title T ON ED.Designation_Id = T.TitleId  ''
    Set @SelectSQL = @SelectSQL + ''Where ED.IsDeleted = ''''1'''' ''
	Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @TestEmployeeId + '''''' ''
	If Not (@LevelID = '''' Or @LevelID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Level_Id = '''''' + @LevelID + '''''' ''
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName,  Designation, PresentDays, AbsentDays, LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
--	Set @EmployeeName = @EmployeeName + ''%''
--	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'') 
--	Begin
--	Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName  
--	End
--	Else 
--	Begin
--	Select * From #TempReportTable where EmployeeName like @EmployeeName 
--	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetailold]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetailold]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptAttendanceDetailold]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @PresentDays As Varchar(50)
	Declare @AbsentDays as varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)
	Declare @TestInDate as Varchar(50)
	Declare @TestOutDate as Varchar(50)
	Declare @TestEmployeeId as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Set @PresentDays = ''0''
	Set @AbsentDays = ''0''
	Set @LateComingDays = ''0''
	Set @TotalLateEntryHrs = ''00:00''
	Set @LateExitDays = ''0''
	Set @TotalLateExitHrs = ''00:00''
	Set @TotalLeaves = ''0''
	Set @ESILeaves = ''0''
	Select @AbsentDays = case when sum(NumberOfDays) is not null then sum(NumberOfDays) else ''0'' end From 
TA_Tbl_LeaveApplication where Employee_Id = @TestEmployeeId and IsDeleted = 1 And Leave_FromDate >= @FromDate and 
Leave_ToDate <= @ToDate
	Select @TotalLeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else ''0'' end From 
TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = 
@TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate 
and (LT.LeaveType = ''CL'' or LT.LeaveType = ''EL'' or LT.LeaveType = ''SL'')
	Select @ESILeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else ''0'' end From 
TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = 
@TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 and LT.LeaveType = ''ESI'' And LA.Leave_FromDate >= @FromDate and 
LA.Leave_ToDate <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 as varchar)
	DECLARE d CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct Clk_InDate, Clk_OutDate from TA_Tbl_ClockDetails where (Clk_InDate >= @FromDate and Clk_InDate <= 
@ToDate) or (Clk_OutDate >= @FromDate and Clk_OutDate <= @ToDate) and Clk_EmpId = @TestEmployeeId
	OPEN d 
	FETCH NEXT FROM d INTO @TestInDate,@TestOutDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @LateBy as Varchar(50)
	Declare @LateByTime as varchar(50)
	Declare @ActIn as varchar(50)
	Declare @Grace as varchar(50)
	Declare @EarlyBy as Varchar(50)
	Declare @EarlyByTime as varchar(50)
	Declare @ActOut as varchar(50)
	Declare @GraceOut as varchar(50)	
	Select @ActIn = Shift_StartTime , @Grace = Case len(Shift_GraceInTime) when 1 then ''00:0'' when 2 then ''00:'' End + 
Shift_GraceInTime, @ActOut = Shift_EndTime , @GraceOut = Case len(Shift_GraceOutTime) when 1 then ''00:0'' when 2 then ''00:'' 
End + Shift_GraceOutTime From TA_Tbl_Shift where Shift_Id = 1
	SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101) - convert(datetime,@Grace,101) 
FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = 
@TestEmployeeId
	if (convert(varchar,@LateBy,101) > convert(datetime,''Dec 30 1899 12:00AM'',101))
	Begin
	Set @LateByTime = left(right(convert(datetime,@LateBy,101) + convert(datetime,@Grace,101),7),5)
	if (left(@LateByTime,2)=''12'')
	Begin
		Set @LateByTime = ''00:'' + right(@LateByTime,2)
	end
	if (left(@LateByTime,1)='''')
	Begin
		Set @LateByTime = ''0'' + right(@LateByTime,4)
	end
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1) as int) + 
cast(left(@LateByTime,charindex('':'',@LateByTime,1)-1) as int) as varchar) + '':'' + 
cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)) as int) + 
cast(right(@LateByTime,charindex('':'',@LateByTime,1)-1) as int) as varchar)
	Set @LateComingDays = @LateComingDays + 1
	End
	SELECT @EarlyBy = max(convert(datetime,Clk_OutTime,101)) - convert(datetime,@ActOut,101) FROM TA_Tbl_ClockDetails 
Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestOutDate,101) and Clk_EmpId = @TestEmployeeId
	if (convert(varchar,@EarlyBy,101) > convert(datetime,''Dec 30 1899 12:00AM'',101))
	Begin
	Set @EarlyByTime = left(right(convert(datetime,@EarlyBy,101),7),5)
	if (left(@EarlyByTime,2)=''12'')
	Begin
		Set @EarlyByTime = ''00:'' + right(@EarlyByTime,2)
	end
	if (left(@EarlyByTime,1)='''')
	Begin
		Set @EarlyByTime = ''0'' + right(@EarlyByTime,4)
	end
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1) as int) + 
cast(left(@EarlyByTime,charindex('':'',@EarlyByTime,1)-1) as int) as varchar) + '':'' + 
cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)) as int) + 
cast(right(@EarlyByTime,charindex('':'',@EarlyByTime,1)-1) as int) as varchar)
	Set @LateExitDays = @LateExitDays + 1
	End
	FETCH NEXT FROM d INTO @TestInDate,@TestOutDate
	END 
	CLOSE d 
	DEALLOCATE d
	Declare @Test as int
	Set @Test = cast((right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)))/60 as int)
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1) as int) + @Test as 
varchar) + '':'' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)) as int) - 
(@Test * 60) as varchar)
	Select @TotalLateEntryHrs =
	(Case len (left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1)) + '':'' +
	Case len (right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1))))	
	Set @Test = cast((right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)))/60 as int)
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1) as int) + @Test as 
varchar) + '':'' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)) as int) - 
(@Test * 60) as varchar)
	Select @TotalLateExitHrs =
	(Case len (left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1)) + '':'' +
	Case len (right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1))))	
	Set @SelectSQL = '' '' 
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName 
as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
    Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo,R.Region_Name AS Region, '''''' + @PresentDays + '''''','''''' + @AbsentDays 
+ '''''', '''''' + @LateComingDays + '''''','''''' + @TotalLateEntryHrs + '''''', '''''' + @LateExitDays + '''''', '''''' + @TotalLateExitHrs + '''''', 
'''''' + @TotalLeaves + '''''', '''''' + @ESILeaves + '''''' FROM TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Region R ON ED.Region_Id = R.Region_Id ''
    Set @SelectSQL = @SelectSQL + ''Where ED.IsDeleted = ''''1'''' ''
	Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @TestEmployeeId + '''''' ''
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  PresentDays, AbsentDays, 
LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
	Set @EmployeeName = @EmployeeName + ''%''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'') 
	Begin
	Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName  
	End
	Else 
	Begin
	Select * From #TempReportTable where EmployeeName like @EmployeeName 
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAttendanceDetail]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAttendanceDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_RptAttendanceDetail]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), @SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 PresentDays varchar(50),
	 AbsentDays varchar(50),
	 LateComingDays varchar(50),
	 TotalLateEntryHrs varchar(255),
	 LateExitDays varchar(255),
	 TotalLateExitHrs varchar(255),
	 TotalLeaves varchar(255),
	 ESILeaves varchar(255)
	)
BEGIN
	Declare @SelectSQL As Varchar(4000)
	Declare @PresentDays As Varchar(50)
	Declare @AbsentDays as varchar(50)
	Declare @LateComingDays as varchar(50)
	Declare @TotalLateEntryHrs as varchar(50)
	Declare @LateExitDays as varchar(250)
	Declare @TotalLateExitHrs as varchar(250)
	Declare @TotalLeaves as varchar(250)
	Declare @ESILeaves as varchar(250)
	Declare @In_Out_Sql as varchar(4000)
	Declare @TestInDate as Varchar(50)
	Declare @TestOutDate as Varchar(50)
	Declare @TestEmployeeId as Varchar(50)
	Declare @WeekOff as int
	Set @WeekOff = 0
	select @WeekOff = dbo.udf_CompleteWeekRange(convert(varchar, @FromDate, 101), convert(varchar, @ToDate, 101), 1)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct SwipeCardNo from TA_Tbl_Employee 
	OPEN c 
	FETCH NEXT FROM c INTO @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Set @PresentDays = ''0''
	Set @AbsentDays = ''0''
	Set @LateComingDays = ''0''
	Set @TotalLateEntryHrs = ''00:00''
	Set @LateExitDays = ''0''
	Set @TotalLateExitHrs = ''00:00''
	Set @TotalLeaves = ''0''
	Set @ESILeaves = ''0''
	Select @AbsentDays = case when sum(NumberOfDays) is not null then sum(NumberOfDays) else ''0'' end From TA_Tbl_LeaveApplication where Employee_Id = @TestEmployeeId and IsDeleted = 1 And (( Leave_FromDate  between @FromDate  And @ToDate ) or (Leave_ToDate between @FromDate  And @ToDate  ))
	Select @TotalLeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else ''0'' end From TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = @TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate and (LT.LeaveType = ''CL'' or LT.LeaveType = ''EL'' or LT.LeaveType = ''SL'')
	Select @ESILeaves = case when sum(LA.NumberOfDays) is not null then sum(LA.NumberOfDays) else ''0'' end From TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveType LT on LA.LeaveType_Id = LT.LeaveType_Id where LA.Employee_Id = @TestEmployeeId and LT.IsDeleted = 1 and LA.IsDeleted = 1 and LT.LeaveType = ''ESI'' And LA.Leave_FromDate >= @FromDate and LA.Leave_ToDate <= @ToDate
	Set @PresentDays = cast(cast(Datediff(dd,@FromDate,@ToDate)as int) - cast(@AbsentDays as float) + 1 - @WeekOff as varchar)
	if (@FromDate = NULL and  @ToDate = NULL)
	Begin
		DECLARE d CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_InDate, Clk_OutDate from TA_Tbl_ClockDetails where Clk_EmpId = @TestEmployeeId
	End
	Else
	Begin
		DECLARE d CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_InDate from TA_Tbl_ClockDetails where ((Clk_InDate >= @FromDate and Clk_InDate <= @ToDate)) and Clk_EmpId = @TestEmployeeId
	End	
	OPEN d 
	FETCH NEXT FROM d INTO @TestInDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @LateBy as Varchar(50)
	Declare @LateByTime as varchar(50)
	Declare @ActIn as varchar(50)
	Declare @Grace as varchar(50)
	Declare @CheckSunday as int
	Set @CheckSunday = 0
	select @CheckSunday = dbo.udf_CompleteWeekRange(convert(varchar, @TestInDate, 101), convert(varchar, @TestInDate, 101), 1)
	Select @ActIn = Shift_StartTime , @Grace = Case len(Shift_GraceInTime) when 1 then ''00:0'' when 2 then ''00:'' End + Shift_GraceInTime From TA_Tbl_Shift where Shift_Id = 1
	--SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101) - convert(datetime,@Grace,101) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = @TestEmployeeId
	SELECT @LateBy = min(convert(datetime,Clk_InTime,101)) - convert(datetime,@ActIn,101)  FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_InDate,101) = convert(datetime,@TestInDate,101) and Clk_EmpId = @TestEmployeeId
	--if (convert(varchar,@LateBy,101) > convert(datetime,''Dec 30 1899 12:00AM'',101))
	if (convert(varchar,@LateBy,101) > convert(datetime,@Grace,101))
	Begin
	--Set @LateByTime = left(right(convert(datetime,@LateBy,101) + convert(datetime,@Grace,101),7),5)
	Set @LateByTime = left(right(convert(datetime,@LateBy,101) ,7),5)
	if (left(@LateByTime,2)=''12'')
	Begin
		Set @LateByTime = ''00:'' + right(@LateByTime,2)
	end
	if (left(@LateByTime,1)='''')
	Begin
		Set @LateByTime = ''0'' + right(@LateByTime,4)
	end
	if(@CheckSunday <> 1)
	Begin
		Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1) as int) + cast(left(@LateByTime,charindex('':'',@LateByTime,1)-1) as int) as varchar) + '':'' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)) as int) + cast(right(@LateByTime,charindex('':'',@LateByTime,1)-1) as int) as varchar)
		Set @LateComingDays = @LateComingDays + 1
	End
	End
	FETCH NEXT FROM d INTO @TestInDate
	END 
	CLOSE d 
	DEALLOCATE d
	DECLARE e CURSOR 
		    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
			Select Distinct Clk_OutDate from TA_Tbl_ClockDetails where ((Clk_OutDate >= @FromDate and Clk_OutDate <= @ToDate)) and Clk_EmpId = @TestEmployeeId
	OPEN e
	FETCH NEXT FROM e INTO @TestOutDate
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN
	Declare @EarlyBy as Varchar(50)
	Declare @EarlyByTime as varchar(50)
	Declare @ActOut as varchar(50)
	Declare @GraceOut as varchar(50)	
	Set @CheckSunday = 0
	select @CheckSunday = dbo.udf_CompleteWeekRange(convert(varchar, @TestOutDate, 101), convert(varchar, @TestOutDate, 101), 1)
	Select  @ActOut = Shift_EndTime , @GraceOut = Case len(Shift_GraceOutTime) when 1 then ''00:0'' when 2 then ''00:'' End + Shift_GraceOutTime From TA_Tbl_Shift where Shift_Id = 1	
	SELECT @EarlyBy = max(convert(datetime,Clk_OutTime,101)) - convert(datetime,@ActOut,101) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestOutDate,101) and Clk_EmpId = @TestEmployeeId
	--if (convert(varchar,@EarlyBy,101) > convert(datetime,''Dec 30 1899 12:00AM'',101))
	if (convert(varchar,@EarlyBy,101) > convert(datetime,@GraceOut,101))
	Begin
	Set @EarlyByTime = left(right(convert(datetime,@EarlyBy,101),7),5)
	if (left(@EarlyByTime,2)=''12'')
	Begin
		Set @EarlyByTime = ''00:'' + right(@EarlyByTime,2)
	end
	if (left(@EarlyByTime,1)='''')
	Begin
		Set @EarlyByTime = ''0'' + right(@EarlyByTime,4)
	end
	if(@CheckSunday <> 1)
	Begin
		Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1) as int) + cast(left(@EarlyByTime,charindex('':'',@EarlyByTime,1)-1) as int) as varchar) + '':'' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)) as int) + cast(right(@EarlyByTime,charindex('':'',@EarlyByTime,1)-1) as int) as varchar)
		Set @LateExitDays = @LateExitDays + 1
	End
	End
	FETCH NEXT FROM e INTO @TestOutDate
	END 
	CLOSE e
	DEALLOCATE e
	Declare @Test as int
	Set @Test = cast((right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)))/60 as int)
	Set @TotalLateEntryHrs = cast(cast(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1) as int) + @Test as varchar) + '':'' + cast(cast(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)) as int) - (@Test * 60) as varchar)
	Select @TotalLateEntryHrs =
	(Case len (left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(left(@TotalLateEntryHrs,charindex('':'',@TotalLateEntryHrs,1)-1)) + '':'' +
	Case len (right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1)))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(right(@TotalLateEntryHrs,len(@TotalLateEntryHrs) - charindex('':'',@TotalLateEntryHrs,1))))	
	Set @Test = cast((right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)))/60 as int)
	Set @TotalLateExitHrs = cast(cast(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1) as int) + @Test as varchar) + '':'' + cast(cast(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)) as int) - (@Test * 60) as varchar)
	Select @TotalLateExitHrs =
	(Case len (left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1))
	when 1 then ''0''
	when 2 then ''''
	End + 
	rtrim(left(@TotalLateExitHrs,charindex('':'',@TotalLateExitHrs,1)-1)) + '':'' +
	Case len (right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1)))
	when 1 then ''0''
	when 2 then ''''
	End +
	rtrim(right(@TotalLateExitHrs,len(@TotalLateExitHrs) - charindex('':'',@TotalLateExitHrs,1))))	
	Set @SelectSQL = '' '' 
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    	Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
    	Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo,R.Region_Name AS Region, '''''' + @PresentDays + '''''','''''' + @AbsentDays + '''''', '''''' + @LateComingDays + '''''','''''' + @TotalLateEntryHrs + '''''', '''''' + @LateExitDays + '''''', '''''' + @TotalLateExitHrs + '''''', '''''' + @TotalLeaves + '''''', '''''' + @ESILeaves + '''''' FROM TA_Tbl_Employee ED LEFT OUTER JOIN ''
    	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id LEFT OUTER JOIN TA_Tbl_Title T ON ED.Designation_Id = T.TitleId LEFT OUTER JOIN ''
    	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id LEFT OUTER JOIN ''
    	Set @SelectSQL = @SelectSQL + ''TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id LEFT OUTER JOIN ''
    	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Region R ON ED.Region_Id = R.Region_Id ''
    	Set @SelectSQL = @SelectSQL + ''Where ED.IsDeleted = ''''1'''' ''
	Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @TestEmployeeId + '''''' ''
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region,  PresentDays, AbsentDays, LateComingDays, TotalLateEntryHrs,	 LateExitDays, TotalLateExitHrs, TotalLeaves, ESILeaves)		
	Exec (@SelectSQL)
	FETCH NEXT FROM c INTO @TestEmployeeId
	END 
	CLOSE c 
	DEALLOCATE c
	Set @EmployeeName = @EmployeeName + ''%''
	--If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')  
	If (@EmployeeId = '''' Or @EmployeeId = ''0'') 
	Begin
		Select * From #TempReportTable where EmployeeName like @EmployeeName
	End
	Else
	Begin		Select * From #TempReportTable where CardNo = @EmployeeId and EmployeeName like @EmployeeName
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectDuplicate]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProjectDuplicate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ProjectDuplicate]
	-- Add the parameters for the stored procedure here
	@Project_Name varchar(250)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select count(*) from TA_Tbl_Project where Project_Name=@Project_Name and IsDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProInsertShiftLocation]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProInsertShiftLocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_ProInsertShiftLocation ''2020-01-02 00:00:00.000'',1,19

CREATE PROCEDURE [dbo].[Proc_TA_ProInsertShiftLocation]
@Shiftdate datetime,
@UserId int,
@LocationId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

IF EXISTS (select EmployeeId from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId )
BEGIN
		IF NOT EXISTS (select Shift_Lcoation_Id from TA_tbl_ShiftAdd_Location where ShiftDate= @Shiftdate 
		and EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId   ))
			BEGIN
			Insert into TA_tbl_ShiftAdd_Location(EmployeeId, LocationId,ShiftDate,CreatedBy)
			select EmpID, @LocationId, @Shiftdate, @UserId
			from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId
			END

		ELSE
			BEGIN
			UPDATE TA_tbl_ShiftAdd_Location
			set LocationId = @LocationId, ModifiedBy = @UserId, ModifiedOn=getdate()
			where ShiftDate= @Shiftdate and EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where LoginEmployeeId= @UserId)
			END
		END

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Preferences]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Preferences]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 22-09-2017
-- =============================================
create PROCEDURE [dbo].[Proc_TA_Preferences]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	select isDomain,DomainName,DomainAdminUserName,DomainAdminPassword from TA_Tbl_Preferences
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PolicyName]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PolicyName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_PolicyName]  (@PolicyId int,@PolicyName varchar(50))
as
SELECT COUNT(*) FROM TA_Tbl_LeavePolicy WHERE PolicyName=@PolicyName and IsDeleted=0 and Policy_Id <>@PolicyId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PermanentDeleteOtType]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PermanentDeleteOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_PermanentDeleteOtType] 
	@OtTypeID as int,	
	@EmpId as int
AS
BEGIN	
update  TA_Tbl_OtType set EmpID=@EmpID where OtTypeID=@OtTypeID
	delete from TA_Tbl_OtType where OtTypeID=@OtTypeID	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReplaceReportingPerson]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReplaceReportingPerson]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_ReplaceReportingPerson]
(
@OldManagerEmployeeCode varchar(15),
@NewManagerEmployeeCode varchar(15)
)
AS
BEGIN
	DECLARE @OldManagerEmployeeId as bigint
	DECLARE @NewManagerEmployeeId as bigint
	SET @OldManagerEmployeeId=(SELECT Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@OldManagerEmployeeCode)
	SET @NewManagerEmployeeId=(SELECT Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@NewManagerEmployeeCode)
	UPDATE TA_Tbl_Employee SET Reporting_To=@NewManagerEmployeeId WHERE Reporting_To=@OldManagerEmployeeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ReplaceInDetailsForService]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ReplaceInDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Check whether the InTime lies inbetween any InTime and OutTime in the Clock Details Table for particular Employee
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ReplaceInDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@Type char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if @Type=''I''
	begin
		Select Clk_Id,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_OutDeviceId IN (@strOutDeviceId) AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <@strInDateTime ) 
		AND (CAST(Clk_OutDate+Clk_OutTime AS DateTime) > @strInDateTime) AND IsVoid=0
	end
	if @Type=''O''
	begin
		Select Clk_Id,Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_InDeviceId IN (@strOutDeviceId) 
		AND (CAST(Clk_InDate+Clk_InTime AS DateTime) < @strInDateTime) 
		AND (CAST(Clk_OutDate+Clk_OutTime AS DateTime) > @strInDateTime) AND IsVoid=0
	end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RemoveImportMasterErrData]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RemoveImportMasterErrData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <17-11-2018 01.27 PM>
-- Description:	<To remove import master Error Data from database>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_RemoveImportMasterErrData]
AS
BEGIN
	SET NOCOUNT ON;
	Delete from TA_Tbl_ImportMasterError
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-02-2013
-- Description:	Removing the EmailReportNotSendedDetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_RemoveEmailReportNotSendedDetails]
	-- Add the parameters for the stored procedure here
	@ReScheduleid bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM Ta_tbl_EmailReportNotSendedDetails where ReScheduleid=@ReScheduleid
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ParentIDs]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ParentIDs]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- Create date: 16 July 2007
-- Modified by : R.Manikandan
-- Modified on : 19-Apr-2019 11:51 AM
-- Description:	Get Parent Level IDs
-- We got some wrong data binding in iffco. They are created the level details tables as per their requirement.
-- i.e they were created the parent id after the child data creation. Due to this level dropdowns are not loaded
-- properly in employee master modify page. Due to this, we bring row_number.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ParentIDs]
AS	
BEGIN
	SET NOCOUNT ON;
	select LevelID,LevelName,pid from
	(
		SELECT *,ROW_NUMBER()over(order by (select 100))as slno FROM TA_Tbl_ParentIDs 
	)as a order by slno desc
	DELETE FROM TA_Tbl_ParentIDs
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OverTimeRoundOff]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OverTimeRoundOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OverTimeRoundOff]
	-- Add the parameters for the stored procedure here
	@inShiftSettingId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT StartMins,EndMins,RoundedAs FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId =  @inShiftSettingId 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RecursionLeaveDays]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RecursionLeaveDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Proc_TA_RecursionLeaveDays 7,''04/02/2015 12:00:00 AM'',''04/04/2016 12:00:00 AM''
Created By		:	Manjula.P
Created Date	:	25-May-2013
Descriptions	:	To restrict the Continued leave as per the new leave policy
*/
CREATE proc [dbo].[Proc_TA_RecursionLeaveDays]
(
@Employee_Id int,
@LeavePrevious datetime,
@LeaveNext datetime
)
as begin
create table #TempRecursion
(
	LeaveApplicationId int,
	LeaveType varchar(50),
	LeaveFromDAte datetime,
	LeaveToDate datetime,
	EmpId int,
	Type varchar(50),
	NoOfDays decimal(18,1)
)
BEGIN
	SET NOCOUNT ON;
	declare @Count int;
	declare @DateDiff int;
	declare @FirstRowToDate datetime;
	set @Count=(select COUNT( LA.LeaveApplication_Id) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
	where (LA.Employee_Id=@Employee_Id) 
	and
	(
	(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
	or
	(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
	or           
	(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
	)
	and LA.IsDeleted=0 and LA.Status<>''Rejected'')
	set @DateDiff=1;
	while (@Count>0 and (@DateDiff=1 or @DateDiff=-1) )
		begin
			insert into #TempRecursion
			select LA.LeaveApplication_Id, LT.LeaveType,LA.Leave_FromDate,LA.Leave_ToDate,Employee_Id,LA.Type, LA.NumberOfDays from TA_Tbl_LeaveApplication LA
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			where (LA.Employee_Id=@Employee_Id) 
			and
			(
			(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
			or
			(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
			or           
			(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
			)
			and LA.IsDeleted=0 and LA.Status<>''Rejected''
			set @FirstRowToDate=@LeaveNext;
			set @LeavePrevious=DATEADD(DAY,-1, @LeavePrevious)
			set @LeaveNext=DATEADD(DAY,1, @LeaveNext)
			--set @DateDiff=DATEDIFF(day,@LeavePrevious,@FirstRowToDate);
			set @Count= (select COUNT( LA.LeaveApplication_Id) from TA_Tbl_LeaveApplication LA
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			where (LA.Employee_Id=@Employee_Id) 
			and
			(
			(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
			or
			(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
			or           
			(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
			)
			and LA.IsDeleted=0 and LA.Status<>''Rejected''  and LA.LeaveApplication_Id not in (select #TempRecursion.LeaveApplicationId from #TempRecursion))
		end
	select * from #TempRecursion 
	group by LeaveApplicationId,EmpId,LeaveFromDAte,LeaveToDate,LeaveType,NoOfDays,Type
	drop table #TempRecursion
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyExit]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEarlyExit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptEarlyExit]
(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), @SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @EmployeeName varchar(50))
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	Create Table #TempReportTable
	(
	 CardNo VarChar(255),	
	 [Employee Name] Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Logo image,
	 Region Varchar(250),
	 Date DateTime,
	 OutTime varchar(50),
	 EarlyBy varchar(50)
	)
	Declare @TestDate as Varchar(50)
	Declare @TestEmployeeId as Varchar(50)
	DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
	Select Distinct Clk_OutDate, Clk_EmpId from TA_Tbl_ClockDetails where Clk_OutDate >= @FromDate and Clk_OutDate <= @ToDate
	OPEN c 
	FETCH NEXT FROM c INTO @TestDate, @TestEmployeeId
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
	Declare @InTime as Varchar(50)
	Declare @LateBy as Varchar(50)
	Declare @LateByTime as varchar(50)
	Declare @ActIn as varchar(50)
	Declare @Grace as varchar(50)	
	Select @ActIn = Shift_EndTime , @Grace = Case len(Shift_GraceOutTime) when 1 then ''00:0'' when 2 then ''00:'' End + Shift_GraceInTime From TA_Tbl_Shift where Shift_Id = 1
	SELECT @InTime = max(convert(datetime,Clk_OutTime,101)) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestDate,101) and Clk_EmpId = @TestEmployeeId
	SELECT @LateBy = convert(datetime,@ActIn,101) - max(convert(datetime,Clk_OutTime,101)) - convert(datetime,@Grace,101) FROM TA_Tbl_ClockDetails Where Convert (varchar,Clk_OutDate,101) = convert(datetime,@TestDate,101) and Clk_EmpId = @TestEmployeeId
	if (convert(varchar,@LateBy,101) > convert(datetime,''Jan 03 1900 12:00AM'',101))
	Begin
	set  @InTime = right(@InTime,7)
	Set @LateByTime = left(right(convert(datetime,@LateBy,101) + convert(datetime,@Grace,101),7),5)
	if (left(@LateByTime,2)=''12'')
	Begin
		Set @LateByTime = ''00:'' + right(@LateByTime,2)
	end
	if (left(@LateByTime,1)='''')
	Begin
		Set @LateByTime = ''0'' + right(@LateByTime,4)
	end
	Declare @SelectSQL As Varchar(4000)
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
   	Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo,R.Region_Name AS Region, '''''' +  @TestDate + '''''' as Date, '''''' +  @InTime + '''''' as InTime, '''''' +  @LateByTime + '''''' as LateBy FROM TA_Tbl_Employee ED INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON ED.Designation_Id = T.TitleId INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_CompanyDetails C ON ED.Company_Id = C.Company_Id INNER JOIN ''
	Set @SelectSQL = @SelectSQL + ''TA_Tbl_Region R ON ED.Region_Id = R.Region_Id Where ''
	--Set @SelectSQL = @SelectSQL + ''TA_Tbl_ProcessedData PD ON ED.Employee_Id = PD.Employee_Code_Id Where PD.LateIn <> ''''00:00'''' And PD.LateIn <> ''''0''''''
	Set @SelectSQL = @SelectSQL + ''ED.IsDeleted = ''''1''''''
	--If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	--Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @TestEmployeeId + '''''' ''
	--End
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
--	If (@FromDate <> '''')
--	Begin
--		Set @SelectSQL = @SelectSQL + ''And PD.Date >= '''''' + @FromDate + '''''' ''
--	End
--
--	If (@ToDate <> '''')
--	Begin
--		Set @SelectSQL = @SelectSQL + ''And PD.Date <= '''''' + @ToDate + '''''' ''
--	End
	Insert InTo #TempReportTable (CardNo, [Employee Name], Department, Designation, Section, Logo, Region, Date, OutTime, EarlyBy) 
	exec (@SelectSQL)
	End
	FETCH NEXT FROM c INTO @TestDate, @TestEmployeeId
	END 
	Set @EmployeeName = @EmployeeName + ''%''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
	Select * From #TempReportTable where CardNo = @EmployeeId and [Employee Name] like @EmployeeName
	End
	Else 
	Begin
	Select * From #TempReportTable where [Employee Name] like @EmployeeName
	End
	CLOSE c 
	DEALLOCATE c
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_RptEmployeeInOutSelectEmployee] ''4'',''2009'','''','''',''0,1,2,3,5,9,10,11,12,13,14,15,16'',''0'',''0''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSelectEmployee]
	 @SelectedMonth nvarchar(20),  
	 @SelectedYear nvarchar(20),  
	 @EmployeeId varchar(50),
	 @EmployeeName varchar(50),  
	 @LevelID varchar(1000), 	 
	 @employeeCategory nvarchar(50),
	 @employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
@EmpSwipeCard varchar(20)
AS
BEGIN
	declare @FromDate as nvarchar(15)
	declare @ToDate as nvarchar(15)
	set @FromDate = cast(@SelectedMonth as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
--	set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
if (@SelectedMonth=12)
	Begin
		set @ToDate =  ''01/'' + ''01/'' + cast(@SelectedYear+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
	End
declare @fromDat as datetime
declare @todat as datetime
set @fromdat=@FromDate
set @ToDat = @ToDate
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpGrade(Grade_Id int)
--Employee Grade Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
(
	[Grade_Id] ASC
) ON [PRIMARY]
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		--select  distinct employee_code_id from ta_tbl_processedData order by employee_code_id
	declare @sqlQuery as varchar(8000)
	set @sqlQuery =''select distinct TA_Tbl_ProcessedData.employee_code_id''  
	set @sqlQuery = @sqlQuery + '' FROM  dbo.TA_Tbl_ProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.SwipeCardNo=dbo.TA_Tbl_ProcessedData.Employee_Code_Id ''  	
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
    set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
   	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
   	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' where 1=1 And (TA_Tbl_Employee.Employee_Status=1 and ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )''  
	set @sqlQuery = @sqlQuery + '' AND (month(TA_Tbl_ProcessedData.Date) = '''''' + cast(@SelectedMonth as nvarchar(50))  + '''''') ''   
	set @sqlQuery = @sqlQuery + '' AND (year(TA_Tbl_ProcessedData.Date) = '''''' + cast(@SelectedYear as nvarchar(50))  + '''''') ''   
	if(@UserGroupName<>''SuperAdmin'')
	begin
		--SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		SET @sqlQuery = @sqlQuery + ''	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)''
	end
	if not(@EmployeeName='''' or @EmployeeName=''0'')  
	begin  
		--set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''  
		set @sqlQuery = @sqlQuery + ''and (TA_Tbl_Employee.Employee_FirstName + isnull(TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end  
	If Not (@EmpSwipeCard = '''')  
    Begin  
		  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End 
	if not (@EmployeeId='''' or @EmployeeId=''0'')  
	begin  
		set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''  
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
	end	
	if not(@LevelID='''' or @LevelID=''0'')  
	begin  
		set @sqlQuery = @sqlQuery + '' And (#EmpLevel.levelId IN ('' + @LevelID  + ''))''
	end  
	set @sqlQuery = @sqlQuery + '' order by TA_Tbl_ProcessedData.Employee_code_id''  
	Exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--EXEC [Proc_TA_RptDetails] ''2012-05-01'',''Emp1''
CREATE PROCEDURE [dbo].[Proc_TA_RptDetails]
 @fromDate datetime,
 @Id VARCHAR(100)
AS  
BEGIN  
	SELECT 
		''InTime['' + PD.InTime + ''], OutTime['' + PD.OutTime + ''], BreakOut['' + PD.BreakOut	+ ''], BreakIn['' + PD.BreakIn + '']'' FROM TA_Tbl_ProcessedData PD
	WHERE PD.[Date] = CONVERT(DATETIME, CAST(@fromDate AS NVARCHAR(50)), 102) AND PD.Employee_Code_Id = @Id
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetailsGroupPolicy]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDetailsGroupPolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/****************************************************************************************/            
-- Name    : Proc_TA_SelectDetailsGroupPolicy           
-- Desc    : To select the enties from TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : P.Santhosh Raj            
-- Date    : 25-Mar-2009            
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectDetailsGroupPolicy]
@loginEmployeeId int       
AS      
BEGIN
	SET NOCOUNT ON;      
	SELECT EmpID,EmployeeId, EmployeeName,LoginEmployeeId,convert(nvarchar(20),DateOfJoining,101) as DateOfJoining,LevelID     
	FROM TA_Tbl_TempGroupPolicyAllocation Where LoginEmployeeId = @loginEmployeeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
/* Proc_TA_SelectDetails  1 */
CREATE PROCEDURE [dbo].[Proc_TA_SelectDetails]
	@loginEmployeeId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @loginEmployeeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDashBoardRightsDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDashBoardRightsDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-10-2016>
-- Description:	<Select Board Rights Details>
-- [Proc_TA_SelectDashBoardRightsDetails]''5''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDashBoardRightsDetails]
	@UsergroupId int
AS
BEGIN
	SET NOCOUNT ON;
	if exists(select BoardId from ta_tbl_DashboardUserrights where Usergroupid=@UsergroupId)
    begin
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0)ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId		
		where Usergroupid=@UsergroupId and BoardParentName=''AttendanceData''
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0) ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId
		where Usergroupid=@UsergroupId and BoardParentName=''ApprovalData''
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,isnull(ViewPrev,0)ViewPrev
		from ta_tbl_DashboardData DD inner join ta_tbl_DashboardUserrights DUR on DUR.Boardid=DD.DataId
		where Usergroupid=@UsergroupId and BoardParentName=''ExceptionData''	
		select top 1 Dashboard,Gridview,Chart from ta_tbl_DashboardUserrights DUR
		where Usergroupid=@Usergroupid 
		select groupName from ta_tbl_usergroup where groupid=@UsergroupId
	end
	else
	begin
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName=''AttendanceData''
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName=''ApprovalData''
		SELECT DD.DataId,dd.BoardChildName as BoardChildName,0 ViewPrev
		from ta_tbl_DashboardData DD where BoardParentName=''ExceptionData''
		select top 1 Dashboard,Gridview,Chart from ta_tbl_DashboardUserrights DUR		
		where Usergroupid=@Usergroupid
		select groupName from ta_tbl_usergroup where groupid=@UsergroupId
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectApprovalSettings]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectApprovalSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_SelectApprovalSettings
Description			:	select the companies
Tables Included		:	TA_Tbl_ApprovalSettings
Created By			:	Prabakaran.P
Created On			:	11-Sep-09
Modified By	:
Modified On	:
Proc_TA_SelectApprovalSettings 1
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectApprovalSettings]
-- Add the parameters for the stored procedure here
@intCompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry, Approval, 
	webClockInOut=isnull(webClockInOut,0) from TA_Tbl_ApprovalSettings where CompanyId=@intCompanyId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllYearSetting]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllYearSetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectAllYearSetting]  
AS  
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + '' - '' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting ,* 
from Ta_Tbl_Yearsetting  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllType]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllType]
	@UserType as nvarchar(100)		
AS
BEGIN
	Create table #TempType(TypeName nvarchar(100),TypeId bigint,isdeleted nvarchar(10),IsFlexible bit,flag int)
	if (@UserType=''SuperAdmin'')
		Begin
			insert into #TempType
			select TypeName,TypeId,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted,IsFlexible,0 From Ta_tbl_Type order by TypeName	
		End
	Else
		Begin
			insert into #TempType
			select TypeName,TypeId,case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted,IsFlexible,0 From Ta_tbl_Type where isdeleted=0 order by TypeName	
		End
	Update #TempType set flag=1 from #TempType TT inner join ta_tbl_employeeType ET on TT.TypeId=ET.TypeId 
	select * from #TempType
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllNews]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllNews]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllNews] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_NewsEvents order by newsEvent_Id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_UserGroupName]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_UserGroupName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Senthil
-- ALTER  date: 15-May-08
-- Description:	Select usergroup name by id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Select_UserGroupName]
	@GroupID as int
AS
BEGIN
	select groupName,hasSpecialRights,isnull(ReportsBasedOn,0)ReportsBasedOn,IndividualUsers from Ta_tbl_usergroup where groupId=@GroupID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Select_TerminalforView]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Select_TerminalforView]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 July 2007
-- Description:	Select Terminal details for view
-- Modified By : Kumuthini.L
-- Modifi
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Select_TerminalforView] 
(
-- Add the parameters for the stored procedure here
  @TerminalID INT
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
             -- Insert statements for procedure here
	SELECT T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,T.IsDeleted
	FROM TA_Tbl_Terminal T
	INNER JOIN TA_tbl_TerminalDatatype TD
	ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
	WHERE T.Terminal_Id=@TerminalID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RstoreOtType]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RstoreOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
create PROCEDURE [dbo].[Proc_TA_RstoreOtType]   
 @OtTypeID as int,   
 @EmpId as int  
AS  
BEGIN   
 update  TA_Tbl_OtType set   
   IsDeleted=0,     
   EmpID=@EmpID  
  where OtTypeID=@OtTypeID  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditTableNames]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllAuditTableNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllAuditTableNames] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_AuditTable WHERE Status = 1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicy]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author				:	Arun vinoth
-- ALTER  date		:	28 June 2007
-- Description		:	Leave policy - Insert
--Modified By		:	Manikandan.R
--Modified Date		:	15-10-2011
--Modified By		:	A.K.T.MOORTHI
--Modified Date		:	31-Dec-2013
-- Description		:	Add the Halfdaycompoff, VaildDays Column for insert and update query.
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_TA_InsertLeavePolicy] 
	@Type CHAR(1)='''',
	@Policy_Id INT=0,
	@PolicyName NVARCHAR(50)='''',
	@Permission_MaxHrs_Month NVARCHAR(5)='''',
	@Permission_MaxInstances_Month INT=0,
	@Permission_MaxHrs_Instance NVARCHAR(5)='''',
	@Employee_Id INT,
	@PermissionBeforeLeave INT, 
	@PermissionAfterLeave INT,
	@OtHourWise INT,
 	@OtDayWise INT,
	@OtMinHrs VARCHAR(20),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@Gender VARCHAR(10),
	@Religion INT,
	@HalfDayCompOff VARCHAR(5),
	@VaildDays INT,
	@companyID int
AS
	DECLARE @IsDeleted BIT
	SET @IsDeleted=0
BEGIN
	SET NOCOUNT ON;
	IF (@Type=''I'')
	BEGIN 
		INSERT INTO TA_Tbl_LeavePolicy (PolicyName, Permission_MaxHrs_Month, Permission_MaxInstances_Month, Permission_MaxHrs_Instance, IsDeleted, Emp_Id, PermissionBeforeLeave, PermissionAfterLeave, OtHourWise, OtDayWise, OtMinHrs, EmployeeCategory, EmployeeType, Gender, Religion, FullDayOTMinHrs, CompOffValidDays,companyID)
			VALUES (@PolicyName, @Permission_MaxHrs_Month, @Permission_MaxInstances_Month, @Permission_MaxHrs_Instance, @IsDeleted, @Employee_Id, @PermissionBeforeLeave, @PermissionAfterLeave, @OtHourWise, @OtDayWise, @HalfDayCompOff, @EmployeeCategory, @EmployeeType, @Gender, @Religion, @OtMinHrs, @VaildDays,@companyID)
	END
	ELSE IF (@Type=''U'')
	BEGIN
		UPDATE TA_Tbl_LeavePolicy SET 
			PolicyName = @PolicyName,
			Permission_MaxHrs_Month = @Permission_MaxHrs_Month,
			Permission_MaxInstances_Month = @Permission_MaxInstances_Month,
			Permission_MaxHrs_Instance = @Permission_MaxHrs_Instance,
			IsDeleted=@IsDeleted,
			Emp_Id=@Employee_Id,
			Time_Stamp=getdate(),
			PermissionBeforeLeave = @PermissionBeforeLeave,
			PermissionAfterLeave = @PermissionAfterLeave,
			OtHourWise = @OtHourWise,
			OtDayWise = @OtDayWise,
			OtMinHrs = @HalfDayCompOff,
			EmployeeCategory = @EmployeeCategory,
			EmployeeType = @EmployeeType,
			Gender = @Gender,
			Religion = @Religion,
			FullDayOTMinHrs = @OtMinHrs,
			CompOffValidDays = @VaildDays,
			companyID=@companyID
		WHERE  Policy_Id = @Policy_Id
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationMaster]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_InsertLeaveApplicationMaster  ''5'',''03/17/2008'',''52'',''Leave'',''03/17/2008'',''03/17/2008'',''First Session'',''Second Session'',1.0,''TEst Reason'',0,6,''''
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationMaster]  
(
@EmployeeID int,
@Leave_ApplicationDate datetime,
@Reason nvarchar(1050),
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@LeaveAvailedYear decimal(18,1),
@LeaveAvailedMonth decimal(18,1)
)  
as  
BEGIN
SET NOCOUNT ON;
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @CountRecord as int  
set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID)  
declare @sql nvarchar(3000)
set @sql=''''
begin
		if(@LeaveStatus='''' and @CountRecord>0)
			BEGIN
			set @LeaveStatus=''Forwarded''
			END
		else if (@LeaveStatus='''' and @CountRecord=0)
			BEGIN
			set @LeaveStatus=''Pending''
			END
--Insert Method  
	begin  
		set @sql= @sql + ''INSERT INTO TA_Tbl_LeaveApplicationMaster(Employee_Id,Leave_ApplicationDate,Reason,Status,IsDeleted,Emp_Id,YearSettings_Id,IntimationType,CCMail,LeaveAvailedYear,LeaveAvailedMonth)''
		set @sql= @sql + ''VALUES('''''' + cast(@EmployeeID as nvarchar(20)) + '''''','''''' + cast(@Leave_ApplicationDate as nvarchar(20)) + '''''',''''''
		set @sql= @sql + @Reason + '''''',N'''''' + @LeaveStatus + '''''','''''' + cast(@Isdeleted as nvarchar(10)) +  '''''',N'''''' + @auEmpId + '''''',N'''''' + @YearSettings_Id + '''''',N'''''' + @intimationType + '''''','''''' + @CCMail + '''''','''''' + cast(@LeaveAvailedYear as nvarchar(20)) + '''''','''''' + cast(@LeaveAvailedMonth as nvarchar(20)) +'''''')''
		exec(@sql)
      SELECT @@IDENTITY AS LeaveApplication_Id
	end
end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.MANIKANDAN
-- Create date: 04-02-2013
-- Description:	Inserting the Leave and Permission details to emailTriggering Table
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationDetailsInEmailTrigger]
	-- Add the parameters for the stored procedure here
	@LeaveApplicationId bigint,
	@FromEmailID nvarchar(max),
	@ToEmailId nvarchar(max),
	@CCEmailid nvarchar(max),
	@Subjects nvarchar(max),
	@BodyContent nvarchar(max),
	@Attachment nvarchar(max),
	@AraisedFrom nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO Ta_tbl_EmailReportNotSendedDetails values(@LeaveApplicationId,@FromEmailID,@ToEmailId,@CCEmailid,@Subjects,@BodyContent,@Attachment,@AraisedFrom)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertGeofenceDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertGeofenceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_InsertGeofenceDetails ''addr'',''Manikandan'',10,''Manikandan'',''Manikandan'',''Manikandan'',''Manikandan'',''Manikandan'','''',''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertGeofenceDetails]
	@Options nvarchar(max), 
	@LocationName nvarchar(500),
	@Radius int,
	@Description nvarchar(1000), 
	@Address nvarchar(500),
	@City nvarchar(500),
	@State nvarchar(500),
	@Country nvarchar(500),
	@latitude varchar(30),
	@longitude varchar(30),
	@CreatedBy int,
	@insertflag char(1),
	@geoID bigint
AS
BEGIN	
	SET NOCOUNT ON;
	IF(@insertflag=''I'')
	BEGIN
		INSERT INTO Ta_tbl_LandMarks
		(
			Options ,
			LocationName ,
			Radius ,
			Description, 
			Address,
			City,
			State,
			Country,
			CreatedBy,
			CreatedDate,
			latitude,
			longitude
		) 
		VALUES
		(
			@Options,
			@LocationName,
			@Radius,
			@Description,
			@Address,
			@City,
			@State,
			@Country,
			@CreatedBy,
			GETDATE(),
			@latitude,
			@longitude
		)
	END
	ELSE
	BEGIN
		UPDATE Ta_tbl_LandMarks SET Options=@Options,
									LocationName=@LocationName,
									Radius=@Radius,
									Description=@Description,
									Address=@Address,
									City=@City,
									State=@State,
									Country=@Country,
									ModifiedBy=@CreatedBy,
									ModifiedDate=GETDATE(),
									latitude=@latitude,
									longitude=@longitude
		WHERE id=@geoID
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogo]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLogo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj>
-- Create date: <Create Date,,26-Nov-07>
-- Description:	<Description,,Inserting CustomerLogo>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLogo](@logo image)
AS
DECLARE @Count as int
BEGIN
		set @count=(select count(*) from Ta_Tbl_Branding)
		if(@count=0)
		begin
		INSERT INTO Ta_Tbl_Branding(Cus_Image)values(@logo)	
		end
		else
		begin
		UPDATE Ta_Tbl_Branding SET Cus_Image=@logo
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLogDownloaded]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLogDownloaded]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		: Manjula.P
Created Date	: 21-May-2013
Descriptions	: For creating log downloaded details as per the given requirements by sathish sir 
*/
CREATE proc [dbo].[Proc_TA_InsertLogDownloaded]
(
@LoggedEmployeeId int 
)
as begin
insert into ta_tbl_LogDownloaded(LoggedEmployeeId,LoggedDate) values(@LoggedEmployeeId,GETDATE())
select * from ta_tbl_LogDownloaded where LoggedId=(select @@IDENTITY as LoggedId)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLevelWiseRights]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLevelWiseRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- Create date: 23-Aug-08
-- Description:	Insert/update levelwise rights
--Proc_TA_InsertLevelWiseRights 8,''47,3,2,1,113,3,2,1''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLevelWiseRights]
	@GroupId as int,
	@LevelID as nvarchar(3000),
	@empid as nvarchar(30)
AS
BEGIN
	declare @Query as varchar(7000)
	declare @RecCount as int
	set @RecCount = (select count(*) from TA_Tbl_LevelRights where groupID = @GroupID)
	if (@RecCount>0)
		Begin
				set @Query = ''update TA_TBL_LevelRights set LevelID='''''' + @LevelID + '''''', emp_id = '''''' + @empid + '''''' where GroupID= '' + cast (@GroupID as nvarchar(100))
		End
	Else
		Begin
				set @Query = ''insert into TA_Tbl_LevelRights (GroupID, LevelID,emp_id) values ('' + cast (@GroupID as nvarchar(100)) + '','''''' + @LevelID + '''''','''''' + @empid  + '''''')''
		End
	exec (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShift]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE   procedure [dbo].[Proc_TA_InsertShift]  
(
	@levelId int,
	@ShiftId int,
	@ShiftName nvarchar(50),  
	@ShiftShortName nvarchar(50),  
	@ShiftDescription nvarchar(255),  
	@ShiftStartTime nvarchar(10),  
	@ShiftEndTime nvarchar(10),  
	@Shift_FirstHalfStartTime nvarchar(10),  
	@Shift_FirstHalfEndTime nvarchar(10),  
	@Shift_SecondHalfStartTime nvarchar(10),  
	@Shift_SecondHalfEndTime nvarchar(10),  
	@ShiftGraceInTime nvarchar(10),  
	@ShiftGraceOutTime nvarchar(10),  
	@ShiftBreakStartTime1 nvarchar(10),  
	@ShiftBreakEndTime1 nvarchar(10),  
	@ShiftBreakStartTime2 nvarchar(10),  
	@ShiftBreakEndTime2 nvarchar(10),  
	@ShiftBreakStartTime3 nvarchar(10),  
	@ShiftBreakEndTime3 nvarchar(10),  
	@ShiftMinTimeOT nvarchar(50),  
	@ShiftMaxTimeOT nvarchar(50),  
	@ShiftWorkingDayOverTime float,  
	@ShiftTotalWorkingHours nvarchar(50),  
	@Shift_FirstHalfWorkingHours nvarchar(10),    
	@Shift_SecondHalfWorkingHours nvarchar(10),    
	@Emp_ID nvarchar(50),
	@DefaultShift int,  
	@ShiftType bit,
	@24HrsShift bit,
	@isStraightShift bit,
	@StraightPresentTime nvarchar(10),
	@BreakHours nvarchar(5),
	@empCategory int=1,
	@specialOvertime_start1 varchar(10),	
	@specialOvertime_start2 varchar(10),
	@MaxShiftWorkHours varchar(10)
)
AS  
BEGIN  
	Declare @DefShift int
	if(@specialOvertime_start1='''')
	begin
		set @specialOvertime_start1=0
	end
	if(@specialOvertime_start2='''')
	begin
		set @specialOvertime_start2=0
	end
	if exists(select DefaultShift from TA_Tbl_Shift where Level_Id=@levelId and DefaultShift=1)
		begin	
			if(@DefaultShift=1)
				begin
					update ta_tbl_shift set DefaultShift=0 where Level_Id =@levelId 
				end
		end
	if(@ShiftId=0)
	begin
		INSERT INTO TA_Tbl_Shift (Level_Id, Shift_Name, Shift_ShortName, Shift_Description,Shift_StartTime,Shift_EndTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_GraceInTime,
		Shift_GraceOutTime,Shift_BreakStartTime1,Shift_BreakEndTime1,Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_BreakStartTime3,Shift_BreakEndTime3,Shift_MinTimeOT,Shift_MaxTimeOT,Shift_WorkingDay_OverTime,Shift_TotalWorkingHours,Shift_FirstHalfWorkingHours,
		Shift_SecondHalfWorkingHours,Isdeleted,Emp_ID,DefaultShift,ShiftType,[24HrsShift],CreatedDate,isStraightShift,StraightPresentTime,BreakHours,empCategory,specialOvertime_start1,specialOvertime_start2,MaxShiftWorkHours )
		VALUES(cast(@levelId as nvarchar(25)),@ShiftName,@ShiftShortName,@ShiftDescription,@ShiftStartTime,@ShiftEndTime,@Shift_FirstHalfStartTime,
		@Shift_FirstHalfEndTime,@Shift_SecondHalfStartTime,@Shift_SecondHalfEndTime,@ShiftGraceInTime,@ShiftGraceOutTime,@ShiftBreakStartTime1,
		@ShiftBreakEndTime1,@ShiftBreakStartTime2,@ShiftBreakEndTime2,@ShiftBreakStartTime3,  
		@ShiftBreakEndTime3,@ShiftMinTimeOT ,@ShiftMaxTimeOT ,cast(@ShiftWorkingDayOverTime as nvarchar(25)),@ShiftTotalWorkingHours,
		@Shift_FirstHalfWorkingHours , @Shift_SecondHalfWorkingHours ,0,@Emp_ID,cast(@DefaultShift as nvarchar(25)),cast(@ShiftType as nvarchar(1)),cast(@24HrsShift as nvarchar(1)),cast(GETDATE()as nvarchar(25)),cast(@isStraightShift as nvarchar(1)),@StraightPresentTime,@BreakHours,@empCategory,@specialOvertime_start1,@specialOvertime_start2, @MaxShiftWorkHours)
	END
	ELSE
	BEGIN
		Declare @OldGraceShiftIn nvarchar(6)
		Declare @OldGraceShiftOut nvarchar(6)
		Declare @Shift_BreakStartTime1	nvarchar(10)
		Declare @Shift_BreakEndTime1	nvarchar(10)
		Declare @Shift_BreakStartTime2	nvarchar(10)
		Declare @Shift_BreakEndTime2	nvarchar(10)
		Declare @Shift_BreakStartTime3	nvarchar(10)
		Declare @Shift_BreakEndTime3	nvarchar(10)
		select @OldGraceShiftIn=Shift_GraceInTime,@OldGraceShiftOut=Shift_GraceOutTime,@Shift_BreakStartTime1=Shift_BreakStartTime1,
		@Shift_BreakEndTime1=Shift_BreakEndTime1, @Shift_BreakStartTime2=Shift_BreakStartTime2, @Shift_BreakEndTime2=Shift_BreakEndTime2,
		@Shift_BreakStartTime3=Shift_BreakStartTime3, @Shift_BreakEndTime3=Shift_BreakEndTime3 from TA_Tbl_Shift where Shift_Id=@ShiftId
		insert into ta_tbl_GraceDetails values(@ShiftId,@OldGraceShiftIn,@OldGraceShiftOut,  @Shift_BreakStartTime1,
		@Shift_BreakEndTime1,	@Shift_BreakStartTime2,	@Shift_BreakEndTime2,	@Shift_BreakStartTime3,	@Shift_BreakEndTime3,   GETDATE())	
		
		UPDATE TA_Tbl_Shift  SET Level_Id=cast(@levelId as nvarchar(25)), Shift_Name=@ShiftName, Shift_ShortName = @ShiftShortName, Shift_Description=@ShiftDescription,Shift_StartTime=@ShiftStartTime,
		Shift_EndTime=@ShiftEndTime,Shift_FirstHalf_StartTime=@Shift_FirstHalfStartTime,Shift_FirstHalf_EndTime=@Shift_FirstHalfEndTime,Shift_SecondHalf_StartTime=@Shift_SecondHalfStartTime,Shift_SecondHalf_EndTime=
		@Shift_SecondHalfEndTime,Shift_GraceInTime=@ShiftGraceInTime,Shift_GraceOutTime=@ShiftGraceOutTime,Shift_BreakStartTime1=@ShiftBreakStartTime1,Shift_BreakEndTime1=@ShiftBreakEndTime1,Shift_BreakStartTime2=
		@ShiftBreakStartTime2,Shift_BreakEndTime2=@ShiftBreakEndTime2,Shift_BreakStartTime3 =@ShiftBreakStartTime3,Shift_BreakEndTime3=@ShiftBreakEndTime3 ,Shift_MinTimeOT=  @ShiftMinTimeOT , Shift_MaxTimeOT= @ShiftMaxTimeOT ,
		Shift_WorkingDay_OverTime=cast(@ShiftWorkingDayOverTime as nvarchar(25)),Shift_TotalWorkingHours=@ShiftTotalWorkingHours,Shift_FirstHalfWorkingHours=@Shift_FirstHalfWorkingHours,Shift_SecondHalfWorkingHours=
		@Shift_SecondHalfWorkingHours,Emp_ID= @Emp_ID,DefaultShift=cast(@DefaultShift as nvarchar(25)),ShiftType= cast(@ShiftType as nvarchar(1)) ,ModifiedDate= cast(GETDATE() as nvarchar(25))  ,isStraightShift=cast(@isStraightShift as nvarchar(25)),StraightPresentTime=@StraightPresentTime,
		BreakHours=@BreakHours,empCategory=@empCategory ,
		specialOvertime_start1=@specialOvertime_start1,		
		specialOvertime_start2=@specialOvertime_start2,
		MaxShiftWorkHours = @MaxShiftWorkHours
		,[24HrsShift] = cast(@24HrsShift as nvarchar(1)) -- aded by velumani observed on ADNIP support on 31-jan-2020
		WHERE Shift_Id=cast(@ShiftId as nvarchar(25))	   
	END
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertRawDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertRawDataDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Insert employees raw data details into raw data table with reason>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertRawDataDetails]
	@CLK_CARDID nvarchar(20),	
	@CLK_DEVICEID nvarchar(20),
	@CLK_DATE datetime,
	@CLK_TIME nvarchar(20),
	@CLK_TYPE nvarchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	IF(@CLK_DATE<=dbo.DateOnly(GETDATE()))
	BEGIN
		DECLARE @ReasonId int
		DECLARE @CLK_FLAG int
		DECLARE @CLK_PROCESS int
		SET @ReasonId=0
		SET @CLK_FLAG=0
		SET @CLK_PROCESS=0
		IF NOT EXISTS(SELECT SwipeCardNo from TA_Tbl_Employee where SwipeCardNo =@CLK_CARDID and Isdeleted=0)
		BEGIN
			SELECT @ReasonId=1,@CLK_FLAG=1,@CLK_PROCESS=0
		END
		if not exists(select * from TA_Tbl_Clk_RawData where CLK_CARDID=@CLK_CARDID and CLK_DEVICEID=@CLK_DEVICEID
		and CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=@CLK_TYPE)
		BEGIN
			INSERT INTO TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS,ReasonId,TimecheckDateTime) VALUES
			(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,@CLK_TYPE,@CLK_FLAG,@CLK_PROCESS,@ReasonId,GETDATE())
		END
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpNameGroupPolicy]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpNameGroupPolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpNameGroupPolicy]         
/****************************************************************************************/            
-- Name    : [Proc_TA_InsertEmpNameGroupPolicy] 223,''1231235676'',''ewqqwe wqeq'',6,''2009/01/01'',1           
-- Desc    : To add the enties in TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : P.Santhosh Raj            
-- Date    : 25-Mar-2009            
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/       
(    
@EmpID INT,    
@EmployeeId nvarchar(20),    
@EmpName nvarchar(50),     
@loginEmployeeId INT,    
@DateOfJoining varchar(30),  
@LevelID int  
)          
AS          
BEGIN          
 SET NOCOUNT ON;          
declare @recCount int          
declare @sql nvarchar(2000)        
set @sql = ''''        
 set @recCount = (select count(*) from TA_Tbl_TempGroupPolicyAllocation where EmpID=@EmpID and LoginEmployeeId=@loginEmployeeId)          
 if (@recCount=0)          
 begin          
set @sql = @sql + ''INSERT INTO TA_Tbl_TempGroupPolicyAllocation VALUES('' + cast(@EmpID as nvarchar) + '',N'''''' + @EmployeeId + '''''',N'''''' + @EmpName + '''''',''+cast(@loginEmployeeId as nvarchar)+'',''''''+@DateOfJoining + '''''',''+cast(@LevelID as nvarchar)+'')'' ;      
exec(@sql)        
 end          
END          
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpName]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpName] 
--[Proc_TA_InsertEmpName] ''1'',''2'',''3''
(@EmpID INT,@EmployeeId nvarchar(20),@EmpName nvarchar(50), @loginEmployeeId INT)  
AS  
BEGIN  
 SET NOCOUNT ON;  
 declare @recCount int  
declare @sql nvarchar(2000)
set @sql = ''''
 set @recCount = (select count(*) from ta_tbl_TempShiftAllocation where EmpID=@EmpID and LoginEmployeeId=@loginEmployeeId)  
 if (@recCount=0)  
 begin  
set @sql = @sql + ''INSERT INTO TA_Tbl_TempShiftAllocation VALUES('' + cast(@EmpID as nvarchar) + '',N'''''' + @EmployeeId + '''''',N'''''' + @EmpName + '''''',''+cast(@loginEmployeeId as nvarchar)+'')'' ;
exec(@sql)
 end  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails_Angler]
	@EmployeeCodeId NVARCHAR(50),
	@deviceId NVARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT Employee_Code_Id FROM TA_Tbl_EmployeeEntrance WHERE Employee_Code_Id=@EmployeeCodeId)
	BEGIN
		UPDATE TA_Tbl_EmployeeEntrance set Device_Id=@deviceId WHERE Employee_Code_Id=@EmployeeCodeId
	END
	ELSE
	BEGIN
		INSERT INTO TA_Tbl_EmployeeEntrance (Employee_Code_Id,Device_Id) VALUES(@EmployeeCodeId,@deviceId);
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeEntranceDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeEntranceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmployeeEntranceDetails]
@EmployeeCodeId nvarchar(50),
@deviceId nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	if exists(Select Employee_Code_Id from TA_Tbl_EmployeeEntrance where Employee_Code_Id=@EmployeeCodeId)
	begin
			Update TA_Tbl_EmployeeEntrance set Device_Id=@deviceId Where Employee_Code_Id=@EmployeeCodeId
	End
	Else
	begin
		Insert into TA_Tbl_EmployeeEntrance (Employee_Code_Id,Device_Id) values(@EmployeeCodeId,@deviceId);
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmployeeDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified by : Prabakaran.P
Modified on : 25-June-08
Modified By			:	A.K.T.MOORTHI
Date Of Modified		:	07-Apr-2014
Description			:	Update IsDeleted = 1, InActiveDate = DateOfJoinDate, Employee_Status = 0, Report_Exclude = 1 When Employee Count Greater Then 5, Bze User Can Able To Create N Number Of User.
								But They Can Access Only 5 Employee For Hole Application.
*/
CREATE  PROCEDURE  [dbo].[Proc_TA_InsertEmployeeDetails]   
(  
	@type CHAR(1),
	@EmployeeId INT=0,
	@LevelId INT=0,
	@UserGroupId NVARCHAR(50)='''',  
	@DesignationId INT=0,
	@BusRouteId INT=0,
	@EmpFirstName NVARCHAR(50)='''',
	@EmpMiddleName NVARCHAR(50)='''',  
	@EmpLastName NVARCHAR(50)='''',
	@EmpFatherName NVARCHAR(50)='''',
	@EmpMotherName NVARCHAR(50)='''',
	@dob NVARCHAR(15)=null,  
	@dobrecord NVARCHAR(15)=null,
	@BloodGroup NVARCHAR(10)='''',
	@EmailId NVARCHAR(100)='''',
	@ContactAddress NVARCHAR(255)='''',  
	@PermanentAddress NVARCHAR(255)='''',
	@PhoneNo NVARCHAR(20)='''',
	@MobileNo NVARCHAR(20)='''',
	@Gender NVARCHAR(10)='''',  
	@MaritalStatus NVARCHAR(10)='''',
	@Nationality NVARCHAR(50)='''',
	@Religion INT,  
	@Photo IMAGE,  
	@PersonalEmailId NVARCHAR(100)='''',
	@PassportNo NVARCHAR(50)='''',
	@PExpiry NVARCHAR(15)=null,
	@VisaNo NVARCHAR(50)='''',  
	@VExpiry NVARCHAR(15)=null,
	@VehicleType NVARCHAR(20)='''',
	@VehicleNo NVARCHAR(50)='''',  
	@AnniversaryDate NVARCHAR(15)=null,  
	@NativePlace INT=0,  
	@District NVARCHAR(50)='''',  
	@State INT=0,  
	@Country INT=0,  
	@SpouseNo INT=0,  
	@ChildrenNo INT=0,  
	@EmpCode NVARCHAR(15)='''',  	
	@DateOfJoin NVARCHAR(15)=null,  
	@ReportingTo INT=0,   
	@LeaveSancAuthority INT=0,  	  
	@PrevExperience FLOAT=0,  
	@BasicSalary FLOAT,  
	@HostelWorker BIT=0, 
	@Username NVARCHAR(15)='''',  
	@Password NVARCHAR(50)='''',  
	@Qual_Join NVARCHAR(50)=null,
	@Qual_Employment NVARCHAR(50)=null,  
	@OutDoorJob BIT=0,  
	@CompOffEligible BIT=0,  
	@OTEligible BIT=0,  
	@ESIeligible BIT=0, 
	@PFeligible BIT=0,
	@ReportExclude BIT=0,  
	@EmpStatus BIT=0,  
	@SwipeCardNo NVARCHAR(20),
	@intEmpCategory NVARCHAR(15),
	@intEmpType NVARCHAR(15),  
	@EmpID INT=0,
	@strBasicSalEffDate NVARCHAR(20)=null,
	@strDesigEffDate NVARCHAR(20)=null,
	@intYearSettingsId INT,
	@strLevelEffDate NVARCHAR(20)=null, 
	@strEmpCatEffDate NVARCHAR(20)=null, 
	@strEmpTypeEffDate NVARCHAR(20)=null,
	@intFlexibleTimings int,
	@InActiveDate NVARCHAR(15)=null,	
	@CustomField1 nvarchar(max)=null,
	@CustomField2 nvarchar(max)=null,
	@CustomField3 nvarchar(max)=null,
	@CustomField4 nvarchar(max)=null,
	@CustomField5 nvarchar(max)=null,
	@ApplnMode BIT,
	@penalty bit,
	@MobileClockInOUt bit,
	@SMS bit
) 
AS  
	set nocount on 
	DECLARE @Isdeleted INT 
	SET @Isdeleted=0  
	DECLARE @countBasicPay INT
	DECLARE @countDesignation INT  
	DECLARE @countLevel INT
	DECLARE @countCategory INT
	DECLARE @countType INT
	DECLARE @Inactive_Status BIT
	Declare @Deleted int
	SET @countBasicPay=0  
	SET @countDesignation=0
	SET @countLevel=0
	SET @countCategory=0
	SET @countType=0
	SET @Inactive_Status = (CASE WHEN ISNULL(@EmpStatus, 0) = 0 or @EmpStatus='''' THEN 1 ELSE 0 END)
	if(@Religion=0)
	begin
		select top 1 @Religion=ID from TA_Tbl_Religion where Name=''All'' and IsDeleted=0
		set @Religion=ISNULL(@Religion,0)
	end
	-- insert  
	IF (@type=''I'')  
	BEGIN
		if (@Password is null or @Password='''') 
		begin
			set @Password=''QL5OWbmiorXf+5GMDoaz1w==''
		end
		INSERT INTO TA_Tbl_Employee 
		(
			UserGroup_Id,
			Bus_Id,
			Employee_FirstName,
			Employee_MiddleName,
			Employee_LastName,  
			Father_name,
			Mother_name,
			DateofBirth,
			DateofBirth_Record,
			Blood_Group,
			EmailId,
			Contact_Address,
			Permanent_Address,
			Phone_Number,
			Mobile_Number,
			Gender,
			Marital_status,
			Nationality,
			Religion,
			Personal_mailid,
			Passport_No,  
			Passport_expirydate,
			Visa_No,
			Visa_expirydate,
			Vehicle_Type,
			Vehicle_No,
			Anniversary_Date,
			Native_Place,
			District,
			State,
			Country,
			Spouse_No,
			Children_No,
			Employee_Code_Id,
			DateOfJoining,
			Reporting_To,  
			Leave_Sanc_Authority,
			Prev_Experience,
			Hostel,
			UserName,
			Emp_password,
			Qual_JoiningTime,
			Qual_Employment,
			OutDoorJob,
			CompOff_Eligible,
			OT_Eligible,
			ESI_Eligible,
			PF_Eligible,
			Report_Exclude,
			Employee_Status,
			SwipeCardNo,
			Emp_ID,
			Isdeleted,
			IsFlexible,
			InActiveDate,
			InActive_Status,
			CustomField1,
			CustomField2,
			CustomField3,
			CustomField4,
			CustomField5,
			penalty,
			MobileClockInOUt,
			SMSEnabled,
			Basic_Salary
		)
		VALUES 
		(
			@UserGroupId,
			cast(@BusRouteId as nvarchar(25)),
			@EmpFirstName,
			@EmpMiddleName,
			@EmpLastName,
			@EmpFatherName,
			@EmpMotherName,
			case when isnull(@dob,'''')='''' then null else @dob end,
			case when isnull(@dobrecord,'''')='''' then null else @dobrecord end,
			@BloodGroup,
			@EmailId,
			@ContactAddress,
			@PermanentAddress,
			@PhoneNo,
			@MobileNo,
			@Gender,
			@MaritalStatus,
			@Nationality,
			convert(varchar(10),@Religion) ,
			@PersonalEmailId,
			@PassportNo,
			case when isnull(@PExpiry,'''')='''' then null else @PExpiry end,  
			@VisaNo,
			case when isnull(@VExpiry,'''')='''' then null else @VExpiry end,
			@VehicleType,
			@VehicleNo,
			case when isnull(@AnniversaryDate,'''')='''' then null else @AnniversaryDate end,
			cast(@NativePlace as nvarchar(25)),
			@District,
			cast(@State as nvarchar(25)),
			cast(@Country as nvarchar(25)),
			cast(@SpouseNo as nvarchar(25)),
			cast(@ChildrenNo as nvarchar(25)),
			@EmpCode,			
			case when isnull(@DateOfJoin,'''')='''' then null else @DateOfJoin end,
			cast(@ReportingTo as nvarchar(25)),
			cast(@LeaveSancAuthority as nvarchar(25)),     
			cast(@PrevExperience as nvarchar(25)),
			cast(@HostelWorker as nvarchar(25)),
			@Username,
			@Password,
			@Qual_Join,
			@Qual_Employment,
			cast(@OutDoorJob as nvarchar(25)),
			cast(@CompOffEligible as nvarchar(25)),
			cast(@OTEligible as nvarchar(25)),
			cast(@ESIeligible as nvarchar(25)),
			cast(@PFeligible as nvarchar(25)),
			cast(@ReportExclude as nvarchar(25)),
			cast(@EmpStatus as nvarchar(25)),
			@SwipeCardNo,
			cast(@EmpID as nvarchar(25)),
			cast(@Isdeleted as nvarchar(25)),
			cast(@intFlexibleTimings as nvarchar(25)),
			case when isnull(@InActiveDate,'''')='''' then null else @InActiveDate end ,
			CAST(@Inactive_Status AS VARCHAR(10)),
			cast(@CustomField1 as nvarchar(1000)),
			cast(@CustomField2 as nvarchar(1000)),
			cast(@CustomField3 as nvarchar(1000)),
			cast(@CustomField4 as nvarchar(1000)),
			cast(@CustomField5 as nvarchar(1000)),
			@penalty,
			@MobileClockInOUt,
			@SMS,
			@BasicSalary
		)
		--exec(@sql)  
		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[UpdateTrigTA_Tbl_Employee]''))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
		declare @nextId as int    		
		select @nextId =max(employee_id) from ta_tbl_employee	
		INSERT INTO TA_Tbl_EmployeePay (EmployeeId,BasicPay,EffectiveDate,EmpID) VALUES(@nextId,@BasicSalary,@strBasicSalEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeDesignation (EmployeeId,DesignationID,EffectiveDate,EmpID) VALUES(@nextId,@DesignationId,@strDesigEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId,LevelId,EffectiveDate,EmpID) VALUES(@nextId,@LevelId,@strLevelEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeCategory (EmployeeId,CategoryId,EffectiveDate,EmpId)VALUES(@nextId,@intEmpCategory,@strEmpCatEffDate,@EmpID)
		INSERT INTO TA_Tbl_EmployeeType (EmployeeId,TypeId,EffectiveDate,EmpId)VALUES(@nextId,@intEmpType,@strEmpTypeEffDate,@EmpID)
		-- Type Details Insert Ends here
		if @Deleted=1
		begin
			Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
		end
	END
	---update  
	ELSE IF (@type=''U'')  
	BEGIN  
		IF (@Password is null or @Password='''')  
		BEGIN  
			SELECT @Password = Emp_password FROM TA_Tbl_Employee WHERE Employee_Id =@EmployeeId  
			if (@Password is null or @Password='''') 
			begin
				set @Password=''QL5OWbmiorXf+5GMDoaz1w==''
			end
		END
		--Manual Entry Employee Code Update, while changing the Employee Code Id
		DECLARE @EmployeeCodeId as varchar(15)
		SELECT @EmployeeCodeId=Employee_Code_Id FROM TA_Tbl_Employee WHERE Employee_Id =@EmployeeId
		if(@EmployeeCodeId<>@EmpCode)
		BEGIN
			update TA_Tbl_ManualTimeEntry set ManualTimeEntry_Employee_Id=@EmpCode where ManualTimeEntry_Employee_Id=@EmployeeCodeId
		END
		IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[UpdateTrigTA_Tbl_Employee]''))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
		UPDATE TA_Tbl_Employee SET
		MobileClockInOUt = @MobileClockInOUt,
		SMSEnabled=@SMS,
		penalty=@penalty,	
		UserGroup_Id=@UserGroupId,  
		Bus_Id=cast(@BusRouteId as nvarchar(25)),Employee_FirstName=@EmpFirstName,Employee_MiddleName=@EmpMiddleName,Employee_LastName=@EmpLastName,Father_name=@EmpFatherName,Mother_name=@EmpMotherName, 
		Blood_Group=@BloodGroup,EmailId=@EmailId,Contact_Address=@ContactAddress,Permanent_Address=@PermanentAddress,Phone_Number=@PhoneNo,Mobile_Number=@MobileNo,Gender=@Gender,Marital_status=@MaritalStatus,  
		Nationality=@Nationality,Religion=convert(varchar(10),@Religion),Personal_mailid=@PersonalEmailId,Passport_No=@PassportNo,Visa_No=@VisaNo,Vehicle_Type=@VehicleType,  
		Vehicle_No=@VehicleNo,Native_Place=cast(@NativePlace as nvarchar(25)),District=@District,State=cast(@State as nvarchar(25)),Country=cast(@Country as nvarchar(25)),Spouse_No=cast(@SpouseNo as nvarchar(25)),Children_No=cast(@ChildrenNo as nvarchar(25)),Employee_Code_Id=@EmpCode,  
		Reporting_To=cast(@ReportingTo as nvarchar(25)),Leave_Sanc_Authority=cast(@LeaveSancAuthority as nvarchar(25)),Prev_Experience=cast(@PrevExperience as nvarchar(25)),Hostel=cast(@HostelWorker as nvarchar(25)),UserName=@Username,Emp_password=@Password,Qual_JoiningTime=@Qual_Join,  
		Qual_Employment=@Qual_Employment,OutDoorJob=cast(@OutDoorJob as nvarchar(25)),CompOff_Eligible=cast(@CompOffEligible as nvarchar(25)),OT_Eligible=cast(@OTEligible as nvarchar(25)),ESI_Eligible=cast(@ESIeligible as nvarchar(25)),PF_Eligible=cast(@PFeligible as nvarchar(25)),
		Report_Exclude=cast(@ReportExclude as nvarchar(25)),
		Employee_Status=cast(@EmpStatus as nvarchar(25)),
		SwipeCardNo=@SwipeCardNo,
		modify_by=cast(@EmpID as nvarchar(25)),
		modify_date=cast(getdate() as nvarchar(25)),
		IsFlexible=cast(@intFlexibleTimings as nvarchar(25)),
		CustomField1  =cast(@CustomField1 as nvarchar(1000)),
		CustomField2  =cast(@CustomField2 as nvarchar(1000)),
		CustomField3  =cast(@CustomField3 as nvarchar(1000)),
		CustomField4  =cast(@CustomField4 as nvarchar(1000)),
		CustomField5  =cast(@CustomField5 as nvarchar(1000)),
		InActiveDate= case @InActiveDate when '''' then null else @InActiveDate end,
		InActive_Status = CAST(@Inactive_Status AS VARCHAR(10)),
		Basic_Salary=@BasicSalary,
		DateofBirth_Record=	case when isnull(@dobrecord,'''')=''''	then null else @dobrecord end,
		Passport_expirydate=case when isnull(@PExpiry,'''')=''''	then null else @PExpiry end,
		Visa_expirydate=	case when isnull(@VExpiry,'''')=''''	then null else @VExpiry end,
		Anniversary_Date=	case when isnull(@AnniversaryDate,'''')='''' then null else @AnniversaryDate end,
		DateOfJoining=		case when isnull(@DateOfJoin,'''')='''' then null else @DateOfJoin end,
		DateofBirth=		case when isnull(@dob,'''')=''''		then null else @dob end,
		Photo=case when (@Photo is null)then null else @Photo end								   
		where Employee_Id = @EmployeeId		
				
		if @Deleted=1
			begin
				Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			end			
		-- UPDATE/Insert Employee Basic Pay Details
		BEGIN
			select @countBasicPay=count(EmployeeId) from TA_Tbl_EmployeePay where EffectiveDate=@strBasicSalEffDate and EmployeeId = @EmployeeId
			if(@countBasicPay=0)
			begin
				--Adding Timestamp to getdate() for null insert value error while modifyinh the employee by MAnjula.P on 09-Oct-2013
				INSERT INTO TA_Tbl_EmployeePay (EmployeeId,BasicPay,EffectiveDate,EmpID,Timestamp)VALUES(@EmployeeId,@BasicSalary,@strBasicSalEffDate,@EmpID,GETDATE())
			end
			else
			begin
				UPDATE TA_Tbl_EmployeePay SET BasicPay=@BasicSalary,EmpID=@EmpID where EmployeeId = @EmployeeId  and EffectiveDate=@strBasicSalEffDate
			end
		END
		-- Employee Pay Details UPDATE ends here
		-- Insert/Update Employee Designation Details
		BEGIN
			Select @countDesignation=count(EmployeeId) from TA_Tbl_EmployeeDesignation where EffectiveDate=@strDesigEffDate and EmployeeId = @EmployeeId
			if(@countDesignation=0)
				begin
					INSERT INTO TA_Tbl_EmployeeDesignation (EmployeeId,DesignationID,EffectiveDate,EmpID) VALUES(@EmployeeId,@DesignationId,@strDesigEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeDesignation SET DesignationID=@DesignationId,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strDesigEffDate  
				end
		END
		-- Designation Details Insert Ends here
		-- Insert/Update Employee Level Details
		BEGIN
			Select @countLevel=count(EmployeeId) from TA_Tbl_EmployeeLevel where EffectiveDate=@strLevelEffDate and EmployeeId = @EmployeeId
			if(@countLevel=0)
				begin
					INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId,LevelID,EffectiveDate,EmpID) VALUES(@EmployeeId,@LevelId,@strLevelEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeLevel SET LevelId=@LevelId,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strLevelEffDate  
				end
		END
		-- Level Details Insert/Update Ends here
		-- Insert/Update Employee Category Details
		BEGIN
			Select @countCategory=count(EmployeeId) from TA_Tbl_EmployeeCategory where EffectiveDate=@strEmpCatEffDate and EmployeeId = @EmployeeId
			if(@countCategory=0)
				begin				
					INSERT INTO TA_Tbl_EmployeeCategory (EmployeeId,CategoryId,EffectiveDate,EmpID) VALUES(@EmployeeId,@intEmpCategory,@strEmpCatEffDate,@EmpID)
				end
			else
				begin				
					UPDATE TA_Tbl_EmployeeCategory SET CategoryId=@intEmpCategory,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strEmpCatEffDate  
				end
		END
		-- Category Details Insert/Update Ends here
		-- Insert/Update Employee Type Details
		BEGIN
			Select @countType=count(EmployeeId) from TA_Tbl_EmployeeType where EffectiveDate=@strEmpTypeEffDate and EmployeeId = @EmployeeId
			if(@countType=0)
				begin
					INSERT INTO TA_Tbl_EmployeeType (EmployeeId,TypeId,EffectiveDate,EmpID) VALUES(@EmployeeId,@intEmpType,@strEmpTypeEffDate,@EmpID)
				end
			else
				begin
					UPDATE TA_Tbl_EmployeeType SET TypeId=@intEmpType,EmpID=@EmpID where EmployeeId = @EmployeeId and EffectiveDate=@strEmpTypeEffDate  
				end
		END
		IF(@ApplnMode = 0)
		BEGIN		
			IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[UpdateTrigTA_Tbl_Employee]''))
			begin
				--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
				DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
				set @Deleted=1
			end	
			/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
			UPDATE TA_Tbl_Employee SET
				Isdeleted = 1,
				--Report_Exclude = 1,
				Employee_Status = 0,
				InActiveDate = DATEADD(D, 1, DateOfJoining)
			WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> ''18000000'' ) AND
				Employee_Code_Id <> ''18000000'' AND ISNULL(InActive_Status, 0) = 0
			/* End */
			if @Deleted=1
			begin
				Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			end
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveAnalysisNotes]
@Notes as varchar(8000),
@iDate as datetime,
@EmpID as int
AS
BEGIN
SET NOCOUNT ON;
	Insert into TA_Tbl_LeaveAnalysisNotes (
			Notes,
			DateInserted,
			EmpID
			)
	Values
		(
			@Notes,
			@iDate,
			@EmpID
		)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertInDetailsForService]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertInDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Inserting in and out punch details to clock details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertInDetailsForService]
	-- Add the parameters for the stored procedure here	
	@gstrCompanyId varchar(30),
	@inClk_EmpId varchar(30), 
	@inClk_DeviceId varchar(30),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20), 
	@inPunchType varchar(30),
	@gstrClockDate varchar(20),
	@inClk_Remarks varchar(max), 
	@inClk_User varchar(30), 
	@inClk_Status varchar(10),
	@PunchType_Remarks varchar(max),
	@Type char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if(@Type=''I'')
    begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,
		Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status) VALUES(@gstrCompanyId,@inClk_EmpId,
		@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status)
	end
	if(@Type=''O'')
	begin
		INSERT INTO TA_Tbl_ClockDetails (Clk_CompId,Clk_EmpId, Clk_OutDeviceId,Clk_OutDate, Clk_OutTime, Clk_OutPunchType,
		Clk_Process, Clk_Date,Clk_Remarks,Clk_User,Clk_Status,PunchType_Remarks)VALUES(@gstrCompanyId,@inClk_EmpId,
		@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,@PunchType_Remarks)		
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertInAndOutPunchDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Inserting clock details>
-- Modified by manikandan
-- Need to share this procedure to client upto 2.4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertInAndOutPunchDetails]
	@gstrCompanyId varchar(20),
	@inClk_EmpId varchar(50),
	@inClk_DeviceId varchar(50),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20),
	@inPunchType varchar(20),
	@gstrClockDate varchar(20),
	@inClk_Remarks varchar(max),
	@inClk_User varchar(20),
	@inClk_Status varchar(20),
	@Type char(2),
	@PunchType_Remarks varchar(max)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type=''I'')
    begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status) 
		VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status)
	end
	else if(@Type=''O'')
	begin
		INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Date,Clk_Remarks,
		Clk_User,Clk_Status,PunchType_Remarks)
		VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,@PunchType_Remarks)		
	end
	else if(@Type=''IV'')
	begin
		 INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId, Clk_InDeviceId,Clk_InDate, Clk_InTime,Clk_InPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status,IsVoid) 
		 --Modified below line
		 VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,1)
	end
	else if(@Type=''OV'')
	begin
		 INSERT INTO TA_Tbl_ClockDetails(Clk_CompId,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Date,Clk_Remarks,Clk_User,Clk_Status,IsVoid)
		 --Modified below line
		 VALUES(@gstrCompanyId,@inClk_EmpId,@inClk_DeviceId,@inClk_Date,@inClk_Time,@inPunchType,''N'',@gstrClockDate,@inClk_Remarks,@inClk_User,@inClk_Status,1)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterDataStandard]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertImportMasterDataStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORT
-- Modified Date	:	26-Sep-2013
-- Description		:	To Remove the Grade And GradeNo Parameters.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertImportMasterDataStandard]
			@Emp_FirstName varchar(50)
           ,@Emp_MiddleName  varchar(50)
           ,@Emp_LastName  varchar(50)
           ,@Father_Name  varchar(50)
           ,@Mother_Name  varchar(50)
           ,@DateOfBirth   varchar(25)
           ,@DateOfBirth_Record  varchar(25)
           ,@Blood_Group  varchar(5)
           ,@Email_Id  varchar(200)
           ,@Contact_Address  varchar(500)
           ,@Permanent_Address  varchar(500)
           ,@Phone_Number  varchar(50)
           ,@Mobile_Number  varchar(50)
           ,@Gender  varchar(50)
           ,@Marital_Status  varchar(50)
           ,@Nationality  varchar(50)
           ,@Religion  varchar(50)
           ,@Personal_EmailID  varchar(100)
           ,@Passport_No  varchar(50)
           ,@Passport_ExpiryDate  varchar(50)
           ,@Visa_No  varchar(50)
           ,@Visa_ExpiryDate  varchar(25)
           ,@Employee_Code  varchar(50)
           ,@DateOfJoining  varchar(25)
           ,@Qualification_joiningtime  varchar(50)
           ,@Qualification_Employement  varchar(50)
           ,@OutDoorJob  varchar(1)
           ,@CompOff_Eligible  varchar(1)
           ,@OT_Eligible  varchar(1)
           ,@ESI_Eligible  varchar(50)
           ,@PF_Eligible  varchar(1)
           ,@Report_Exclude  varchar(1)
           ,@Employee_Status  varchar(1)
           ,@SwipeCardNo  varchar(50)
           ,@IsDeleted  varchar(1)
           ,@Hostel  varchar(1)
           ,@Designation  varchar(50)           
           ,@EmployeeType  varchar(50)
           ,@EmployeeCategory  varchar(50)
           ,@BasicSalary  varchar(50)
           ,@Level1  varchar(50)
           ,@Level2  varchar(50)
           ,@Level3  varchar(50)
           ,@Level4  varchar(50)
           ,@Level5  varchar(50)
           ,@Level6  varchar(50)
           ,@Level7  varchar(50)
           ,@Level8  varchar(50)
           ,@Level9  varchar(50)
           ,@Level10 varchar(50)
AS
BEGIN
	IF(@BasicSalary='''' or @BasicSalary=''0'')
		BEGIN
			set @BasicSalary=1
		END
	IF(@Passport_No='''')
		BEGIN
			set @Passport_ExpiryDate=null
		END
	IF(@Passport_ExpiryDate='''')
		BEGIN
			set @Passport_ExpiryDate=null
		END
	IF(@Visa_No='''')
		BEGIN
			set @Visa_ExpiryDate=null
		END
	IF(@Visa_ExpiryDate='''')
		BEGIN
			set @Visa_ExpiryDate=null
		END
	IF(@DateOfBirth_Record='''')
		BEGIN
			SET @DateOfBirth_Record=NULL
		END
	IF(@Employee_Status='''')
		BEGIN
			SET @Employee_Status=1
		END
	declare @intEmpCount as int
	set @intEmpCount=(select count(*) from Ta_Tbl_ImportMasterData where Employee_Code=@Employee_Code)
	if(@intEmpCount=0)
		Begin
			INSERT INTO [Ta_Tbl_ImportMasterData]
           ([Emp_FirstName]
           ,[Emp_MiddleName]
           ,[Emp_LastName]
           ,[Father_Name]
           ,[Mother_Name]
           ,[DateOfBirth]
           ,[DateOfBirth_Record]
           ,[Blood_Group]
           ,[Email_Id]
           ,[Contact_Address]
           ,[Permanent_Address]
           ,[Phone_Number]
           ,[Mobile_Number]
           ,[Gender]
           ,[Marital_Status]
           ,[Nationality]
           ,[Religion]
           ,[Personal_EmailID]
           ,[Passport_No]
           ,[Passport_ExpiryDate]
           ,[Visa_No]
           ,[Visa_ExpiryDate]
           ,[Employee_Code]
           ,[DateOfJoining]
           ,[Qualification_joiningtime]
           ,[Qualification_Employement]
           ,[OutDoorJob]
           ,[CompOff_Eligible]
           ,[OT_Eligible]
           ,[ESI_Eligible]
           ,[PF_Eligible]
           ,[Report_Exclude]
           ,[Employee_Status]
           ,[SwipeCardNo]
           ,[IsDeleted]
           ,[Hostel]
           ,[Designation]
           ,[Grade]
		   ,[GradeNo]
           ,[EmployeeType]
           ,[EmployeeCategory]
           ,[BasicSalary]
           ,[Level1]
           ,[Level2]
           ,[Level3]
           ,[Level4]
           ,[Level5]
           ,[Level6]
           ,[Level7]
           ,[Level8]
           ,[Level9]
           ,[Level10])
     VALUES
		   (@Emp_FirstName
           ,@Emp_MiddleName
           ,@Emp_LastName
           ,@Father_Name
           ,@Mother_Name
           ,@DateOfBirth
           ,@DateOfBirth_Record
           ,@Blood_Group
           ,@Email_Id
           ,@Contact_Address
           ,@Permanent_Address
           ,@Phone_Number
           ,@Mobile_Number
           ,dbo.Func_TA_ProperCase(@Gender)
           ,@Marital_Status
           ,@Nationality
           ,@Religion
           ,@Personal_EmailID
           ,@Passport_No
           ,@Passport_ExpiryDate
           ,@Visa_No
           ,@Visa_ExpiryDate
           ,@Employee_Code
           ,@DateOfJoining
           ,@Qualification_joiningtime
           ,@Qualification_Employement
           ,@OutDoorJob
           ,@CompOff_Eligible
           ,@OT_Eligible
           ,@ESI_Eligible
           ,@PF_Eligible
           ,@Report_Exclude
           ,@Employee_Status
           ,@Employee_Code
           ,@IsDeleted
           ,@Hostel
           ,@Designation
           ,0
		   ,0
           ,@EmployeeType
           ,@EmployeeCategory
           ,@BasicSalary
           ,@Level1
           ,@Level2
           ,@Level3
           ,@Level4
           ,@Level5
           ,@Level6
           ,@Level7
           ,@Level8
           ,@Level9,
           @Level10)
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDemoInfo]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDemoInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Thilakraj>
-- Create date: <26-Nov-2013>
-- Description:	<To insert Demo Version in Table>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertDemoInfo]
	@DemoType nVarchar(50)
AS
BEGIN
	if exists(Select * from TA_Tbl_Demo)
	Begin 
	Delete from TA_Tbl_Demo
	Insert Into TA_Tbl_Demo(DemoType) Values(@DemoType)
	End
	Else
	Begin
		Insert Into TA_Tbl_Demo(DemoType) Values(@DemoType)
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertDashboardRightsDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertDashboardRightsDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <07-10-2016 14.39>
-- Description:	<Insert and Update the Dashboard Rights Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertDashboardRightsDetails]
	-- Add the parameters for the stored procedure here
	@UsergroupName varchar(250),
	@BoardId int,
	@Dashboard int,
	@Gridview int,
	@Chart int,	
	@Empid int,
	@Viewprev int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Usergroupid int
    set @UsergroupId=(select groupId from TA_Tbl_Usergroup where groupName=@UsergroupName and isDeleted=0)
	if exists(select * from ta_tbl_DashboardUserrights where Usergroupid=@Usergroupid and BoardId=@BoardId)
	begin
		update ta_tbl_DashboardUserrights set Empid=@Empid,ViewPrev=@Viewprev,Dashboard=@Dashboard,Gridview=@Gridview,Chart=@Chart
		where Usergroupid=@Usergroupid and BoardId=@BoardId
	end 
	else
	begin		
		insert into ta_tbl_DashboardUserrights values(@Usergroupid,@BoardId,@Viewprev,@Dashboard,@Gridview,@Chart,@Empid)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailScheduleStatus]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmailScheduleStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_InsertEmailScheduleStatus]
(
	@ScheduleId int,
	@DurationFrom datetime,
	@DurationTo datetime,
	@SentDate datetime,
	@Status int,
	@To_Mail varchar(20)=null,
	@EmailID varchar(max)=null,
	@ErrorMessage nvarchar(max)=null
)
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	insert into TA_tbl_EmailScheduleStatus values 
	(@ScheduleId,@DurationFrom,@DurationTo,GETDATE(),@Status,@To_Mail,@EmailID,@ErrorMessage)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpDetails](@EmpId varchar(20),@EmpName varchar(50) )
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TA_Tbl_TempShiftAllocation(EmployeeId,EmployeeName) VALUES(@EmpId,@EmpName);
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidaySettings]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_HolidaySettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created by	:	Prabakaran.P
Description	:	Insert and update Holiday Settings based on YearSetting Id
Modified on	:	21-Feb-08
*/
CREATE PROCEDURE [dbo].[Proc_TA_HolidaySettings]  
(
	@GlobalHoliday_Maxno int,
	@YearlyHoliday_Maxno int,
	@YearSettingId int
)
AS  
BEGIN
	DECLARE @HolidayCount INT
	SELECT @HolidayCount=Count(*)FROM TA_Tbl_HolidaySettings WHERE YearSettingId=@YearSettingId
	IF @HolidayCount=0  
	BEGIN  
		INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)  
	END  
	ELSE  
	BEGIN  
		UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno WHERE YearSettingId=@YearSettingId
	END   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InserAuditTable]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InserAuditTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_InserAuditTable  
Description : insert into TA_Tbl_AuditTable with required information
Tables Included : TA_Tbl_AuditTable
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InserAuditTable] 
	-- Add the parameters for the stored procedure here
	@tableName nvarchar(100),
	@tableDescription nvarchar(100),
    @tableStatus bit
AS
DECLARE @tableId as decimal
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @recCount as int
set @recCount = (select count(*) from TA_Tbl_AuditTable where TableName=@tableName)
if(@recCount>0)
	Begin
		update TA_Tbl_AuditTable set status=@tableStatus where TableName=@tableName
		SELECT tableId = (select TableId from ta_Tbl_auditTable where TableName=@tableName)
	End
Else
	Begin
		INSERT INTO TA_Tbl_AuditTable(TableName, TableDescription, Status) VALUES(@tableName, @tableDescription, @tableStatus)
		SELECT tableId = (select @@identity)
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Title_MappingDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Title_MappingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Title_MappingDetails]
(
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT,
	@DepartmentId INT,
	@SectionId INT,
	@TitleId INT
)
AS
SET NOCOUNT ON
	BEGIN
		INSERT INTO TA_Tbl_TitleMapping
		(
		  Company_Id,Region_Id,Branch_Id,Department_Id,Section_Id,TitleId
		)
       		VALUES 
		(	
			@CompanyId,@RegionId, @BranchId,@DepartmentId,@SectionId,@TitleId		   
		)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_ReligionDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_ReligionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_ReligionDetails]   
(    
 @Name nvarchar(50),    
 @Description NVARCHAR(250) 
)    
AS    
SET NOCOUNT ON    
 BEGIN    
  declare @sql nvarchar(2000)  
  set @sql=''INSERT INTO TA_Tbl_Religion(Name,Description,IsDeleted) VALUES (N''''''+ @Name + '''''',N''''''+ @Description + '''''',0)''  
  exec(@sql)  
  select * from TA_Tbl_Religion
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[PROC_TA_INSERT_PROCESSDATA_SERVICE]
AS
BEGIN
	SET NOCOUNT ON
	--CREATE TABLE #tempProcessDataService
	--(
	--	Employee_Code_Id VARCHAR(20),
	--	ProcessDate DATETIME,
	--	InsertedFlag INT
	--)	
	--INSERT INTO #tempProcessDataService
	--SELECT DISTINCT T1.Employee_Code_Id,T1.ProcessDate,0 
	--FROM 
	--(
	--	SELECT E.SwipeCardNo AS Employee_Code_Id,CONVERT(DATETIME,CONVERT(VARCHAR(11),T.ProcessDate)) as ProcessDate,E.Employee_Id 
	--	FROM TA_Tbl_Employee E INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	--	INNER JOIN Ta_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id  
	--	INNER JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId 
	--	WHERE E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	--	IS NOT NULL AND E.Employee_Code_Id <> ''18000000''
	--)AS T1  
	
	--UPDATE #tempProcessDataService set InsertedFlag=1 FROM TA_Tbl_ProcessedData P
	--INNER JOIN #tempProcessDataService T1  ON T1.Employee_Code_Id  = P.Employee_Code_Id and T1.ProcessDate = P.[Date]  
	
	--INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag)  
	--SELECT Employee_Code_Id,ProcessDate as [Date],''0'' AS ProcessFlag from #tempProcessDataService 
	--WHERE InsertedFlag=0 ORDER BY Employee_Code_Id, ProcessDate
	
	--DROP TABLE #tempProcessDataService
	--Inserting current date first for all employees
	INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag) 
	select E.SwipeCardNo,T.ProcessDate as [Date],''0'' FROM TA_Tbl_Employee E 
	INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	Left outer join TA_Tbl_ProcessedData pd on(pd.Employee_Code_Id=E.SwipeCardNo and pd.Date=T.ProcessDate)
	where T.ProcessDate=dbo.DateOnly(getdate()) and pd.Date is null 
	and E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	IS NOT NULL AND E.Employee_Code_Id <> ''18000000''	
	--order by E.SwipeCardNo,T.ProcessDate
	
	--balance dates
	INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id,[Date],ProcessFlag)  
	select E.SwipeCardNo,T.ProcessDate as [Date],''0'' FROM TA_Tbl_Employee E 
	INNER JOIN TA_Tbl_DataProcessTemp T on T.ProcessDate >= E.DateOfJoining
	Left outer join TA_Tbl_ProcessedData pd on(pd.Employee_Code_Id=E.SwipeCardNo and pd.Date=T.ProcessDate)
	where pd.Date is null --order by E.SwipeCardNo,T.ProcessDate
	and E.IsDeleted = 0 AND E.Employee_Status = 1  AND E.SwipeCardNo 
	IS NOT NULL AND E.Employee_Code_Id <> ''18000000''	
	--order by E.SwipeCardNo,T.ProcessDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_LeaveTypeDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_LeaveTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--[Proc_TA_Insert_LeaveTypeDetails] ''ctc'',''common'',1,0,1,1,0,0
--select*from TA_Tbl_LeaveType 
CREATE PROCEDURE [dbo].[Proc_TA_Insert_LeaveTypeDetails]    
(    
	@LeaveType NVARCHAR(50),
	@LeaveDescription NVARCHAR(250),  
	@Emp_Id NVARCHAR(50),  
	@CountFactor int,
	@EmployeeCategory int,
	@EmployeeType int,
	@Gender varchar(10),
	@Religion int
)    
AS    
BEGIN 
	SET NOCOUNT ON       
	insert into TA_Tbl_LeaveType(LeaveType,LeaveDescription,IsDeleted,Emp_ID,CountFactor,EmployeeCategory,EmployeeType,Gender,Religion,Time_Stamp)
	VAlues(@LeaveType,@LeaveDescription,0,@Emp_Id,@CountFactor,@EmployeeCategory,@EmployeeType,@Gender,@Religion,GETDATE())
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_TransportationDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_TransportationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_TransportationDetails]
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
--DECLARE @CountVehicleID INT
--SELECT @CountVehicleID=COUNT(@VehicleNo) FROM TA_Tbl_Transportation WHERE VehicleNo=@VehicleNo
--IF (@CountVehicleID=0) 
	BEGIN
		INSERT INTO TA_Tbl_Transportation
		(
		   VehicleNo,RouteName,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleNo, @RouteName,@CompanyId,@RegionId, @BranchId		   
		)
	END
--ELSE
	--BEGIN
		--UPDATE TA_Tbl_Transportation
		--SET
			--VehicleNo = @VehicleNo, 
			--RouteName = @RouteName,
			--Company_Id =@CompanyId,
			--Region_Id = @RegionId,
			--Branch_Id = @BranchId
--  		WHERE VehicleNo=@VehicleNo
	--END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation_MappingDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation_MappingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation_MappingDetails]
(
	@VehicleId INT,
	@RouteId INT,
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
	BEGIN
		INSERT INTO TA_Tbl_Transportation_Mapping
		(
		   VehicleId,RouteId,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleId, @RouteId,@CompanyId,@RegionId, @BranchId		   
		)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Transportation]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Transportation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Transportation]
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,
	@RegionId INT,
	@BranchId INT
)
AS
SET NOCOUNT ON
DECLARE @CountVehicleNo INT
SELECT @CountVehicleNo = COUNT(@VehicleNo) FROM TA_Tbl_Transportation WHERE VehicleNo=@VehicleNo
IF (@CountVehicleNo=0) 
	BEGIN
		INSERT INTO TA_Tbl_Transportation
		(
		   VehicleNo,RouteName,Company_Id,Region_Id,Branch_Id
		)
       		VALUES 
		(	
			@VehicleNo, @RouteName,@CompanyId ,@RegionId, @BranchId
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_Transportation
		SET
			 VehicleNo = @VehicleNo,   	
			 RouteName = @RouteName,
			 Company_Id = @CompanyId,
			 Region_id = @RegionId,
			 Branch_Id = @BranchId	 
  		WHERE VehicleNo=@VehicleNo
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAccessDeniedSettings]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAccessDeniedSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name : Proc_TA_InsertAccessDeniedSettings
-- Author : Kumuthini.L
-- Created On : 12-Mar-2008
-- Modified On : 13-Mar-2008
-- Tables Used : TA_Tbl_AccessDeniedSettings
-- Purpose : Used to insert the Access Denied Setting Entries
CREATE PROCEDURE [dbo].[Proc_TA_InsertAccessDeniedSettings]
(
   @Terminal_ReaderId NVARCHAR(10),
   @Employee_Code_Id NVARCHAR(10),
   @AccessDeniedKey INT
)
AS
DECLARE @Count INT
SET @Count = 0
BEGIN
   SET @Count = (SELECT Count(*) FROM TA_Tbl_AccessDeniedSettings WHERE Terminal_ReaderID = @Terminal_ReaderId AND Employee_Code_Id = @Employee_Code_Id)
   IF(@Count = 0)
      BEGIN
        INSERT INTO TA_Tbl_AccessDeniedSettings(Terminal_ReaderID,Employee_Code_Id,AccessDeniedKey) VALUES (@Terminal_ReaderId,@Employee_Code_Id,@AccessDeniedKey)
      END
   ELSE 
      BEGIN
        UPDATE TA_Tbl_AccessDeniedSettings SET AccessDeniedKey = @AccessDeniedKey WHERE Terminal_ReaderID = @Terminal_ReaderId AND Employee_Code_Id = @Employee_Code_Id
      END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAttandanceCode]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_InsertAttandanceCode]
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@EmpID as int
AS
BEGIN
	insert into TA_Tbl_AttandanceCode (AttandanceCode,AttandanceValue,EmpID,IsDeleted,CompanyID) 
                values (@AttandanceCode,@AttandanceValue,@EmpID,0,@CompanyID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdateProcessedData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAndUpdateProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-10-2016>
-- Description:	<Insert / Update data into processed data table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAndUpdateProcessedData]
	-- Add the parameters for the stored procedure here
	@Employee_Code_Id varchar(50),
	@Date varchar(20),
	@Shift_Id int,
	@Intime varchar(15),
	@Attendance varchar(20),
	@InNotation char(2),
	@LateIn varchar(6),
	@LateInMins int,
	@Type char(2),
	@ClockAddress varchar(500)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@Type=''I'')
	begin
		INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id, Date, Shift_Id, InTime, Attendance, ProcessFlag,InNotation,LateIn,LateInMins,InLocation) 
		VALUES(@Employee_Code_Id,convert(datetime,convert(varchar(11),@Date)),@Shift_Id,@Intime,@Attendance,0,@InNotation,@LateIn,@LateInMins,@ClockAddress)
	end
	else if(@Type=''U'')
	begin
		if(@Intime='''' and @Attendance='''' and @InNotation='''' and @Shift_Id=0)
		begin
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0 
			WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
		end
		else
		begin
			UPDATE TA_Tbl_ProcessedData SET Shift_Id = @Shift_Id,
											OutNotation=@InNotation,
											OutTime = @Intime,
											Attendance = @Attendance,
											Status = NULL,
											outLocation=@ClockAddress,
											
											ProcessFlag = 0 
			WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
		end
	end	
	else if(@Type=''UI'')
	begin
		UPDATE TA_Tbl_ProcessedData set Shift_Id = @Shift_Id,
										InNotation=@InNotation,
										InTime = @Intime, 
										LateIn = @LateIn, 
										Attendance = @Attendance, 
										LateInMins = @LateInMins, 
										InLocation=@ClockAddress,
										
										Status = NULL, 
										ProcessFlag = 0 
		WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
	end
	else if(@Type=''IO'')	
	begin
		INSERT INTO TA_Tbl_ProcessedData(Employee_Code_Id, Date, Shift_Id, OutTime,Attendance,ProcessFlag,OutNotation,EarlyOut,EarlyOutMins,InLocation)
		VALUES(@Employee_Code_Id,@Date,@Shift_Id,@Intime,@Attendance,0,@InNotation,@LateIn,@LateInMins,@ClockAddress)
	end
	else if(@Type=''UO'')
	begin
		UPDATE TA_Tbl_ProcessedData set Shift_Id = @Shift_Id,
										OutNotation=@InNotation,
										OutTime = @Intime,
										EarlyOut = @LateIn,
										Attendance = @Attendance,
										EarlyOutMins = @LateInMins,
										OutLocation=@ClockAddress,
										
										Status = NULL, 
										ProcessFlag = 0 
		WHERE Employee_Code_Id = @Employee_Code_Id and DATE = CONVERT(DATETIME,@Date)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <17-Jun-2019>
-- Description:	<Insert and Update penalty Percentage of the selected company>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAndUpdatePenaltyPercentage]
	@CompanyID int,
	@categoryID int,
	@StartTime1 varchar(5),
	@EndTime1 varchar(5),
	@StartTime2 varchar(5),
	@EndTime2 varchar(5),
	@StartTime3 varchar(5),
	@EndTime3 varchar(5),
	@Day1 decimal(18,1),
	@Day2 decimal(18,1),
	@Day3 decimal(18,1),
	@Day4 decimal(18,1),
	@Day5 decimal(18,1),
	@Day6 decimal(18,1),
	@Day7 decimal(18,1),
	@Day8 decimal(18,1),
	@Day9 decimal(18,1),
	@Day10 decimal(18,1),
	@Day11 decimal(18,1),
	@Day12 decimal(18,1)
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT CompanyId FROM ta_tbl_PenaltyPercentage WHERE CompanyId=@CompanyID and categoryID=@categoryID)
	BEGIN
		UPDATE ta_tbl_PenaltyPercentage SET StartTime1=@StartTime1, 
											EndTime1=@EndTime1, 
											StartTime2=@StartTime2, 
											EndTime2=@EndTime2, 
											StartTime3=@StartTime3, 
											EndTime3=@EndTime3, 
											Day1=@Day1, 
											Day2=@Day2, 
											Day3=@Day3, 
											Day4=@Day4, 
											Day5=@Day5, 
											Day6=@Day6, 
											Day7=@Day7, 
											Day8=@Day8, 
											Day9=@Day9, 
											Day10=@Day10, 
											Day11=@Day11, 
											Day12=@Day12
		WHERE CompanyId=@CompanyID and categoryID=@categoryID
	END
	ELSE
	BEGIN
		INSERT INTO ta_tbl_PenaltyPercentage(CompanyId, categoryID, StartTime1, EndTime1, StartTime2, EndTime2, StartTime3, EndTime3, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12)
		VALUES(@CompanyId, @categoryID, @StartTime1, @EndTime1, @StartTime2, @EndTime2, @StartTime3, @EndTime3, @Day1, @Day2, @Day3, @Day4, @Day5, @Day6, @Day7, @Day8, @Day9, @Day10, @Day11, @Day12)
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-April-2019 05:48 PM>
-- Description:	<Insert the employee details for email scheduler>
/*
Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler 7,
''<NewDataSet>
  <Table>
    <Employee_Id>2</Employee_Id>
    <Employee_Code_Id>659</Employee_Code_Id>
    <Employee_FirstName>اختبارات S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>34</RowNumber>
    <TitleName>PL (Project Leader)</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>3</Employee_Id>
    <Employee_Code_Id>956</Employee_Code_Id>
    <Employee_FirstName>Karthikeyan R</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>6</RowNumber>
    <TitleName>TL (Team Leader)</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>4</Employee_Id>
    <Employee_Code_Id>787</Employee_Code_Id>
    <Employee_FirstName>Manikandan RR</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>9</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>5</Employee_Id>
    <Employee_Code_Id>758</Employee_Code_Id>
    <Employee_FirstName>Sathishkumar S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>15</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>6</Employee_Id>
    <Employee_Code_Id>916</Employee_Code_Id>
    <Employee_FirstName>Gopinath K</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>5</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>7</Employee_Id>
    <Employee_Code_Id>1010</Employee_Code_Id>
    <Employee_FirstName>Sankar </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>14</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>8</Employee_Id>
    <Employee_Code_Id>976</Employee_Code_Id>
    <Employee_FirstName>Anbu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>1</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>1</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>9</Employee_Id>
    <Employee_Code_Id>8012</Employee_Code_Id>
    <Employee_FirstName>Manikandan V</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>10</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>10</Employee_Id>
    <Employee_Code_Id>8013</Employee_Code_Id>
    <Employee_FirstName>Manoj M</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>12</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>11</Employee_Id>
    <Employee_Code_Id>2500</Employee_Code_Id>
    <Employee_FirstName>mahi S</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>8</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>12</Employee_Id>
    <Employee_Code_Id>1061</Employee_Code_Id>
    <Employee_FirstName>ANTANIJABARAJ </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>2</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>13</Employee_Id>
    <Employee_Code_Id>100101</Employee_Code_Id>
    <Employee_FirstName>ANTANIJABARAJ </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>3</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>14</Employee_Id>
    <Employee_Code_Id>100102</Employee_Code_Id>
    <Employee_FirstName>Antanijabaraj J</Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>4</RowNumber>
    <TitleName>Jr Developer_Angler</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>17</Employee_Id>
    <Employee_Code_Id>100</Employee_Code_Id>
    <Employee_FirstName>TCS Jeffrin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>20</RowNumber>
    <TitleName>TCS Sr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>18</Employee_Id>
    <Employee_Code_Id>101</Employee_Code_Id>
    <Employee_FirstName>TCS Edwin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>18</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>19</Employee_Id>
    <Employee_Code_Id>102</Employee_Code_Id>
    <Employee_FirstName>TCS David </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>17</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>20</Employee_Id>
    <Employee_Code_Id>103</Employee_Code_Id>
    <Employee_FirstName>TCS Babu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>16</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>21</Employee_Id>
    <Employee_Code_Id>104</Employee_Code_Id>
    <Employee_FirstName>TCS Raja </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>24</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>22</Employee_Id>
    <Employee_Code_Id>105</Employee_Code_Id>
    <Employee_FirstName>TCS Kevin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>21</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>23</Employee_Id>
    <Employee_Code_Id>106</Employee_Code_Id>
    <Employee_FirstName>TCS Esther </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>19</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>24</Employee_Id>
    <Employee_Code_Id>107</Employee_Code_Id>
    <Employee_FirstName>TCS Suresh </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>26</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>25</Employee_Id>
    <Employee_Code_Id>108</Employee_Code_Id>
    <Employee_FirstName>TCS Peter </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>22</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>26</Employee_Id>
    <Employee_Code_Id>109</Employee_Code_Id>
    <Employee_FirstName>TCS Poorni </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>23</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>27</Employee_Id>
    <Employee_Code_Id>110</Employee_Code_Id>
    <Employee_FirstName>TCS Sindu </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>25</RowNumber>
    <TitleName>TCS Jr Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>28</Employee_Id>
    <Employee_Code_Id>1000</Employee_Code_Id>
    <Employee_FirstName>Kavin </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>7</RowNumber>
    <TitleName>Jr Developer_Angler</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>29</Employee_Id>
    <Employee_Code_Id>2000</Employee_Code_Id>
    <Employee_FirstName>UserPM </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>33</RowNumber>
    <TitleName>Project Manager</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>30</Employee_Id>
    <Employee_Code_Id>2001</Employee_Code_Id>
    <Employee_FirstName>UserPL </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>32</RowNumber>
    <TitleName>Project Lead</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>31</Employee_Id>
    <Employee_Code_Id>2002</Employee_Code_Id>
    <Employee_FirstName>UserJrA </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>29</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>32</Employee_Id>
    <Employee_Code_Id>2003</Employee_Code_Id>
    <Employee_FirstName>UserJrB </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>30</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>33</Employee_Id>
    <Employee_Code_Id>2004</Employee_Code_Id>
    <Employee_FirstName>UserJrC </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>31</RowNumber>
    <TitleName>Jr Software Engineer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>34</Employee_Id>
    <Employee_Code_Id>1478</Employee_Code_Id>
    <Employee_FirstName>Probation Period </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>13</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>35</Employee_Id>
    <Employee_Code_Id>1479</Employee_Code_Id>
    <Employee_FirstName>TEsting maximum entry </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>28</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>36</Employee_Id>
    <Employee_Code_Id>1592</Employee_Code_Id>
    <Employee_FirstName>Manikandan </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>11</RowNumber>
    <TitleName>PL (Project Leader)</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
  <Table>
    <Employee_Id>37</Employee_Id>
    <Employee_Code_Id>7536</Employee_Code_Id>
    <Employee_FirstName>test </Employee_FirstName>
    <Employee_Status>Active</Employee_Status>
    <Isdeleted>False</Isdeleted>
    <RowNumber>27</RowNumber>
    <TitleName>Developer</TitleName>
    <emailScheduler_flag>0</emailScheduler_flag>
  </Table>
</NewDataSet>''
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertAndUpdatEmployeeDetails_EmailScheduler]
	@InsertedId int,
	@ShiftData XML = NULL
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX))		
	DELETE FROM [TA_Tbl_ImportShiftAllocation]
	Create table #Temp_TA_Tbl_EmailScheduled_Employees(ScheduleId bigint,Employee_id bigint,flag int)
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
	Delete from TA_Tbl_EmailScheduled_Employees where ScheduleId=@InsertedId
	INSERT INTO TA_Tbl_EmailScheduled_Employees
				SELECT @InsertedId,Employee_Id
				FROM OPENXML (@XMLParams, ''NewDataSet/Table'', 2) WITH (Employee_Id VARCHAR(50), emailScheduler_flag int) Tbl
				Where emailScheduler_flag=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-Feb-2020 03:50 PM>
-- Description:	<update log details table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertAndUpdateDeviceLogTableDetails]
	@TblName varchar(50),
	@LastLogID bigint	
AS
BEGIN
	SET NOCOUNT ON;
	IF EXISTS(SELECT DeviceLog_TableName from Ta_Tbl_DeviceLogTableDetails where DeviceLog_TableName=@TblName)
	BEGIN
		UPDATE Ta_Tbl_DeviceLogTableDetails set LastLogID=@LastLogID,LogFetch_LastTime=getdate() where DeviceLog_TableName=@TblName
		and LastLogID<@LastLogID
	END
	ELSE
	BEGIN
		INSERT INTO Ta_Tbl_DeviceLogTableDetails values(@TblName,@LastLogID,GETDATE())
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAutoShiftDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAutoShiftDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<P Velumani>
-- Create date: <13/07/2019>
-- Description:	<Add update Auto Shift Configuration info against Employeeid>
--Proc_TA_InsertAutoShiftDetails 4,1,0,0,0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAutoShiftDetails]
@EmployeeId int,
@shiftID1 int,
@shiftID2 int,
@shiftID3 int,
@shiftID4 int,
@shiftID5 int,
@UserId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF NOT EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId=@EmployeeId )
	BEGIN
		INSERT INTO TA_Tbl_AutoShiftConfiguration(EmployeeId,ShiftId1,ShiftId2,ShiftId3,ShiftId4,ShiftId5,CreatedBy, CreatedDate) 
		values (@EmployeeId,@shiftID1,@shiftID2,@shiftID3,@shiftID4,@shiftID5,@UserId,getdate())
	END
	ELSE IF EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId=@EmployeeId )
	BEGIN
		Update TA_Tbl_AutoShiftConfiguration set
		ShiftId1 = @shiftID1,
		ShiftId2 = @shiftID2,
		ShiftId3 = @shiftID3,
		ShiftId4 = @shiftID4,
		ShiftId5 = @shiftID5,
		ModifiedBy = @UserId,
		ModifiedDate = getdate()
		where EmployeeId = @EmployeeId
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertProcessedData]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertProcessedData]
(
   @SwipeCardNo nvarchar(20),
   @Date nvarchar(15),
   @ShiftId int,
   @Attendance nvarchar(20) 
)
AS
 Insert Into TA_Tbl_ProcessedData (Employee_Code_Id, [Date], Shift_Id, InTime, OutTime, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, Attendance, WorkHrs, HrsLess,HrsExtra,LateInMins,EarlyOutMins,OtMins)
 Values(@SwipeCardNo,@Date,@ShiftId,''0'',''0'',''0'',''0'',''0'',''0'',''0'',''0'',''0'',@Attendance,''0'',''0'',''0'',0,0,0)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPrevPermission_Eastman]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPrevPermission_Eastman]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <25-03-2019 04.20PM>
-- Description:	<Inserting Previous Permission details of the current application>
-- Proc_TA_InsertPrevPermission_Eastman 0,8,''22-Mar-2019'',''09:31:00'',''10:00:00'',''tes'',''22-Mar-2019''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertPrevPermission_Eastman]
	@Cur_Perm_ID bigint,
	@Prev_Perm_ID bigint,
	@Prev_Perm_date varchar(20),
	@Prev_Perm_ShiftTime varchar(20)=null,
	@Prev_Perm_InTime varchar(20)=null,
	@Prev_Perm_LateHours varchar(10)=null,
	@Prev_Perm_Reason varchar(500),
	@Prev_Perm_ReceivedDate varchar(20)=null
AS
BEGIN
	SET NOCOUNT ON;
	Insert into ta_tbl_PrevPermissionDetails_EastMan values
	(
		@Cur_Perm_ID,
		@Prev_Perm_ID,
		getdate(),
		@Prev_Perm_date,
		@Prev_Perm_ShiftTime,
		@Prev_Perm_InTime,
		@Prev_Perm_LateHours,
		@Prev_Perm_Reason,
		@Prev_Perm_ReceivedDate
	)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMailConfiguration]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMailConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,Manjula.P,>
-- Create date: <Create Date,23-Aug-2013,>
-- Description:	<Description,Inserting email configuration details for email scheduling,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMailConfiguration]
(
	@FromEmailId varchar(300),
	@SMTPClientHost varchar(100),
	@SMTPPort varchar(50),
	@SSLEnable bit,
	@MailAuthentication bit,
	@MailAuthenticateUser varchar(30),
	@MailAuthenticatePassword varchar(30),
	@isRequired int
)
AS
BEGIN
	SET NOCOUNT ON;
    delete from TA_Tbl_MailConfiguration
    --alter table TA_Tbl_MailConfiguration add isRequired bit default(0)
    insert into TA_Tbl_MailConfiguration values (@FromEmailId,@SMTPClientHost,@SMTPPort,@SSLEnable,@MailAuthentication,@MailAuthenticateUser,@MailAuthenticatePassword,@isRequired)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftExchange]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftExchange]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_InsertShiftExchange  
Description		:	To Insert the Shift Exchange Employees
Tables Included	:	TA_Tbl_ShiftExchange
Created By			:	Sasireka  
Created On			:	13-Jan-2009 
Modified By		:	A.K.T.MOORTHI
Modified On		:	08-Jan-2014
Description		:	Reprocess The Selected Date.
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_InsertShiftExchange](
	@levelid INT,
	@Date DATETIME,
	@Employee1_Id INT,
	@Employee1_ActualShiftId INT,
	@Employee2_Id INT,
	@Employee2_ActualShiftId INT,
	@Emp_id INT,
	@EntryDate NVARCHAR(15),
	@YearSettingsId INT)
AS
BEGIN
	INSERT INTO TA_Tbl_ShiftExchange(Level_Id, [Date], Employee1_Id, Employee1_ActualShift, Employee2_Id, Employee2_ActualShift, Emp_Id, [TimeStamp], YearSettings_Id)
		VALUES(CAST(@levelId AS NVARCHAR(25)), CAST(@date AS NVARCHAR(20)), CAST(@Employee1_Id AS NVARCHAR(20)), CAST(@Employee1_ActualShiftId AS NVARCHAR(20)), CAST(@Employee2_Id AS NVARCHAR(20)), CAST(@Employee2_ActualShiftId AS NVARCHAR(20)), CAST(@Emp_id AS NVARCHAR(20)), CAST(@EntryDate AS NVARCHAR(20)), CAST(@YearSettingsId AS NVARCHAR(20)))
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData PD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = PD.Employee_Code_Id 
	WHERE PD.[Date] = @Date AND E.Employee_Id IN (@Employee1_Id, @Employee2_Id)
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = CD.Clk_EmpId
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND (CD.Clk_Date = @Date OR CD.Clk_InDate = @Date OR CD.Clk_OutDate = @Date)
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' FROM TA_Tbl_ManualTimeEntry ME
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = ME.ManualTimeEntry_Employee_Id
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND ((ME.ManualTimeEntry_InDate = @Date) OR (ME.ManualTimeEntry_OutDate = @Date))
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = RD.CLK_CARDID
	WHERE E.Employee_Id IN (@Employee1_Id, @Employee2_Id) AND RD.CLK_DATE = @Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LoginLock]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LoginLock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_LoginLock] 
(
	@UserName VARCHAR(1000),
	@IsActive int		
)
AS
DECLARE @CountUser INT
SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_LockLogin WHERE UserName=@UserName
IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_LockLogin
		(
		   UserName,LockedTime,IsActive
		)
       		VALUES 
		(	
		   @UserName, getdate(),@IsActive
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_LockLogin
		SET LockedTime=getdate(),IsActive=@IsActive
  		WHERE UserName=@UserName
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogout]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LastLogout]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Proc_TA_InsertUpdate_LastLogout ''18000008,18000074''
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogout]
(
	@UserName VARCHAR(2000)	
)
AS
DECLARE @CountUser INT
SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName = @UserName
IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_Login
		(
		   UserName,LastLogoutTime
		)
       		VALUES 
		(	
		   @UserName, getdate()
		)
	END
ELSE
	BEGIN
		UPDATE  TA_Tbl_Login SET LastLogoutTime=getdate() WHERE UserName = @UserName
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_LastLogin]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_LastLogin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_InsertUpdate_LastLogin]
(
	@UserName VARCHAR(15)	
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @CountUser INT
	SELECT @CountUser=COUNT(UserName) FROM TA_Tbl_Login WHERE UserName=@UserName
	IF (@CountUser=0) 
	BEGIN
		INSERT INTO TA_Tbl_Login(UserName,LastLoginTime)VALUES(@UserName, getdate())
	END
	ELSE
	BEGIN
		UPDATE  TA_Tbl_Login SET LastLoginTime=getdate(),LastLogoutTime=null WHERE UserName=@UserName
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	18-Jul-2013
Descriptions	:	Adding Employee Leave Type details for Employee Master
*/
CREATE proc [dbo].[Proc_TA_InsertUpdate_EmpLeaveTypes]
(
	@EmployeeId int,
	@LeaveTypeId int,
	@PreviousYearBalance decimal(18,1),
	@NoOffLeaveAvailed decimal(18,1),
	@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	DECLARE @Rowcount INT
	SET @Rowcount=0;
	SELECT @Rowcount = EmployeeId FROM TA_Tbl_Emp_LeaveTypeDetails 
	WHERE EmployeeId=@EmployeeId and LeaveTypeId=@LeaveTypeId and YearSettingsId=@YearSettingsId
	if(@Rowcount > 0)
		BEGIN
			UPDATE TA_Tbl_Emp_LeaveTypeDetails set PreviousYearBalance=@PreviousYearBalance,NoOffLeaveAvailed=@NoOffLeaveAvailed
			WHERE EmployeeId=@EmployeeId and LeaveTypeId=@LeaveTypeId and YearSettingsId=@YearSettingsId
		END
	ELSE
		BEGIN
			INSERT INTO TA_Tbl_Emp_LeaveTypeDetails(EmployeeId,LeaveTypeId,PreviousYearBalance,NoOffLeaveAvailed,YearSettingsId)
			VALUES(@EmployeeId,@LeaveTypeId,@PreviousYearBalance,@NoOffLeaveAvailed,@YearSettingsId)
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTrace]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTrace]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertTrace]
(
	@PageName as nvarchar(100),
	@ErrDescription as nvarchar(2000)
)
AS
BEGIN
	Insert into Ta_Tbl_Trace (PageName,ErrDescription,DateofError) values (@PageName,@ErrDescription,getDate())
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertTimeSheetEntryDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertTimeSheetEntryDetails]
	@TaskID		bigint,
	@projectID	bigint,
	@DefinedHours nvarchar(10),
	@TaskDescription nvarchar(4000),
	@SpentHours varchar(10),
	@TaskSubmittedBy bigint,
	@Status varchar(10),
	@ShiftDate varchar(10),
	@flag char(2)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@flag=''U'')
	BEGIN
		UPDATE Ta_tbl_TaskProgressDetails set	TaskDescription=@TaskDescription,
												SpentHours=@SpentHours,
												TaskModifiedDate=GETDATE(),
												TaskModifiedBy=@TaskSubmittedBy,
												status=@Status
		WHERE TaskID=@TaskID and ProjectID=@projectID and TaskSubmittedBy=@TaskSubmittedBy
	END
	ELSE
	BEGIN
		INSERT INTO Ta_tbl_TaskProgressDetails
		(	
			TaskID,
			ProjectID,
			ShiftDate,
			TaskHours,
			TaskDescription,
			SpentHours,
			TaskSubmittedDate,
			TaskSubmittedBy,
			Status
		) 
		VALUES
		(
			@TaskID,
			@ProjectID,
			@ShiftDate,
			@DefinedHours,
			@TaskDescription,
			@SpentHours,
			GETDATE(),
			@TaskSubmittedBy,
			@Status
		)		
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertTempShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate Varchar(15),
   @DateShift Varchar(15)
)
 AS
BEGIN
               INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES (@EmpId,@Year,@Month,@UserId,@EntryDate,@DateShift)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_InsertTemporaryShiftAllocation_Bulk]
(
   --@EmpId Int,
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nvarchar(15),
   @DateShift nvarchar(15),
   @xml xml
)
 AS
BEGIN
 Declare @Index int
	  Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into TA_Tbl_TemporaryShiftAllocation (EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift)
		  select EmpID,cast(@Year as nvarchar),cast(@Month as nvarchar),cast(@UserId as nvarchar),@EntryDate,@DateShift 
		  from OpenXML(@Index, ''/DocumentElement/Table'')
		  With (EmpID Bigint ''EmpID'') 
		  where not exists (select EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = EmpID AND [Year] = @Year AND [Month] = @Month)
	  Exec sp_xml_removedocument @Index
--if not exists(SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month)
--BEGIN
--	declare @sql nvarchar(3000)
--		set @sql=''INSERT INTO TA_Tbl_TemporaryShiftAllocation(EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift) VALUES ('''''' + cast(@EmpId as nvarchar(25)) + '''''','''''' + cast(@Year as nvarchar(50)) + '''''','''''' + cast(@Month as nvarchar(50)) + '''''','''''' + cast(@UserId as nvarchar(50)) + '''''',N'''''' + @EntryDate + '''''',N'''''' + @DateShift + '''''')''
--	Exec(@sql)
--END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTATblPage]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTATblPage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_InsertTATblPage  
Description : insert into TA_Tbl_Page for licensed modules    
Tables Included : TA_Tbl_Page  
Created By : Christopher S 
Created On : 17-Mar-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InsertTATblPage]
	-- Add the parameters for the stored procedure here
	@pageId float,
	@displayName nvarchar(100),
	@path nvarchar(200),
	@parentId int,
	@orderBy float
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @pageCount as int
	SET @pageCount = (SELECT COUNT(*) FROM TA_Tbl_Page WHERE pageId = @pageId)
	IF(@pageCount=0)
		BEGIN
			INSERT INTO TA_Tbl_Page(pageId, displayName, path, parentId, orderBy) VALUES(@pageId, @displayName, @path, @parentId, @orderBy)
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTA_Tbl_LIC_Details]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_InsertTA_Tbl_LIC_Details  
Description : insert into TA_Tbl_LIC_Details for license information    
Tables Included : TA_Tbl_LIC_Details  
Created By : Christopher S 
Created On : 19-Mar-2008  
Modified By :  
Modified On :  
*/
-- Proc_TA_InsertTA_Tbl_LIC_Details '''','''','''','''','''','''','''','''','''','''','''','''','''','''','''',''''
CREATE PROCEDURE [dbo].[Proc_TA_InsertTA_Tbl_LIC_Details] 
	-- Add the parameters for the stored procedure here
	@customerId nvarchar(200),		
	@packageId nvarchar(200),
	@packageVersion nvarchar(200),
	@noOfConcurrentUser nvarchar(200),
	@noOfEmployee nvarchar(200),
    @noOfTerminal nvarchar(200),
	@macAddress nvarchar(200),	
	@licenseGenerationDate nvarchar(200),
	@expiryDate nvarchar(200),
	@module nvarchar(200),
	@module1 nvarchar(200),
	@module2 nvarchar(200),
	@module3 nvarchar(200),
	@module4 nvarchar(200),
	@module5 nvarchar(200),
    @pageStatusFalse nvarchar(1000)
AS
DECLARE @query as nvarchar(4000)
SET @query = ''''
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_LIC_Details
	IF(@pageStatusFalse<>'''')
		BEGIN
			SET @query = ''DELETE FROM TA_Tbl_userRights WHERE pageId IN (''+@pageStatusFalse+'')''
			EXEC (@query)
		END        
     DELETE FROM TA_Tbl_Page
	INSERT INTO TA_Tbl_LIC_Details(CustomerId, PackageId, PackageVersion, NoOfConcurrentUser, NoOfEmployee, NoOfTerminal, MACAddress, LicenseGenerationDate, ExpiryDate, Module, Module1, Module2, Module3, Module4, Module5) VALUES(@customerId, @packageId, @packageVersion, @noOfConcurrentUser, @noOfEmployee, @noOfTerminal, @macAddress, @licenseGenerationDate, @expiryDate, @module, @module1, @module2, @module3, @module4, @module5)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCompanyGroup]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCompanyGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateCompanyGroup]
@CompanyGroup as varchar(500)
AS
BEGIN
	declare @Count as int
	set @Count = (select count(*) from TA_Tbl_CompanyGroup)
	if (@count=0)
		Begin
			insert into TA_Tbl_CompanyGroup (CompanyGroup) values (@CompanyGroup)
		End
	Else
		Begin
			update Ta_Tbl_CompanyGroup set CompanyGroup=@CompanyGroup
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory_Angler]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCategory_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	30-Mar-2013
-- Description		:	Add Three Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs) in Insert and update Query
/*
	EXEC [Proc_TA_InsertUpdateCategory] ''U'', ''Permanent'', 1, 1, 0, 48.0, 8.0, 8.0
*/
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory_Angler]
	@Opr NVARCHAR(1),
	@Category NVARCHAR(50),
	@EmpID INT,
	@CategoryID INT,
    @IsFlexible BIT = 0,
    @MonToSatWorkHrs NUMERIC(18, 1),
    @SatWorkHrs NUMERIC(18, 1),
    @WeekDayWorkHrs NUMERIC(18, 1),
    @ARMISWorkHrs NUMERIC(18, 1)
AS
BEGIN
	IF(@Opr = ''I'')	
	BEGIN
		INSERT INTO TA_Tbl_Category(CategoryName, IsDeleted, EmpId, IsFlexible, MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs, ARMIS_WorkHrs) 
			VALUES (@Category, 0, @EmpID, @IsFlexible, @MonToSatWorkHrs, @SatWorkHrs, @WeekDayWorkHrs, @ARMISWorkHrs)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_Category SET
			CategoryName = @Category,
			EmpId = @EmpID,
			IsFlexible = @IsFlexible,
			MonToSat_WorkHrs = @MonToSatWorkHrs,
			Sat_WorkHrs = @SatWorkHrs,
			WeekDay_WorkHrs = @WeekDayWorkHrs,
			ARMIS_WorkHrs = @ARMISWorkHrs
		WHERE CategoryId = @CategoryID
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateCategory]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	Karthikeyan.R
-- Modified Date	:	05-Aug-2015
-- Description		:	Add four Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs,ARMISWorkHrs) in Insert and update Query
/*
	EXEC [Proc_TA_InsertUpdateCategory] ''U'', ''Permanent'', 1, 1, 0, 48.0, 8.0, 8.0
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateCategory]
	@Opr NVARCHAR(1),
	@Category NVARCHAR(50),
	@EmpID INT,
	@CategoryID INT,
    @IsFlexible BIT = 0,
    @MonToSatWorkHrs nvarchar(20),
    @WeekDayWorkHrs nvarchar(20)
AS
BEGIN
	IF(@Opr = ''I'')	
	BEGIN
		INSERT INTO TA_Tbl_Category(CategoryName, IsDeleted, EmpId, IsFlexible, MonToSat_WorkHrs, WeekDay_WorkHrs) 
			VALUES (@Category, 0, @EmpID, @IsFlexible, @MonToSatWorkHrs, @WeekDayWorkHrs)
	END
	ELSE
	BEGIN
		UPDATE TA_Tbl_Category SET
			CategoryName = @Category,
			EmpId = @EmpID,
			IsFlexible = @IsFlexible,
			MonToSat_WorkHrs = @MonToSatWorkHrs,
			WeekDay_WorkHrs = @WeekDayWorkHrs
		WHERE CategoryId = @CategoryID
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateApprovalSettings]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateApprovalSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Prabakaran.P
-- Create date: 11-Sep-09
-- Description:	
-- Modifed By :		K.Gopinath
-- Create date: 01-02-2014
-- Description:	Modified to add OD as seperate column
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateApprovalSettings]
@intCompanyId int,  
@intPattern int,  
@intRoster int, 
@intOTApproval int,  
@intLeaveSanction int,  
@intPermissionSanction int, 
@intManualEntry int,
@intOnDutyEntry int,
@Approval int,
@Emp_Id int,
@webClockInOut bit
AS
BEGIN
	declare @CompanyCount as int
	set @CompanyCount=(select count(*) from TA_Tbl_ApprovalSettings where CompanyId=@intCompanyId)
	if (@CompanyCount=0)	
		Begin
			Insert into TA_Tbl_ApprovalSettings 
			(CompanyId,Pattern, Roster,OTApproval,LeaveSanction,PermissionSanction,ManualEntry,ODEntry,Emp_Id,Approval,webClockInOut) 
			values (@intCompanyId,@intPattern,@intRoster,@intOTApproval,@intLeaveSanction,@intPermissionSanction,@intManualEntry,@intOnDutyEntry,@Emp_Id,@Approval,@webClockInOut)
		End
	Else
		Begin
			update TA_Tbl_ApprovalSettings set
			CompanyId=@intCompanyId,
			Pattern = @intPattern,
			Roster = @intRoster,
			OTApproval = @intOTApproval,
			LeaveSanction=@intLeaveSanction,
			PermissionSanction=@intPermissionSanction,
			ManualEntry=@intManualEntry,
			ODEntry=@intOnDutyEntry,
			Approval=@Approval,
			Emp_Id=@Emp_Id,
			webClockInOut=@webClockInOut
			where CompanyId=@intCompanyId
		End
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateActiveLanguage]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateActiveLanguage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_InsertUpdateActiveLanguage
Description	:	Set Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	16-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_InsertUpdateActiveLanguage] 
@Language_Id int
as
begin
	set nocount on
	update TA_Tbl_MultiLingual set IsActive=0
	Update TA_Tbl_MultiLingual set IsActive=1 where Language_Id=@Language_Id
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUserName]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUserName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_InsertUserName ''U'',1,''SuperAdmin'',0,0,0,''1'',''04/05/2012 4:11:13 PM'',1
-- =============================================
-- Proc_TA_InsertUserName ''U'',1,''??????'',0,1,0,''1'',''''
-- Author:		senthil
-- ALTER  date: 13-Aug-07
-- Description:	Inserting/Updating usergroups name
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_InsertUserName]
	(
		@opr varchar(1),
		@groupId int,
		@groupName nvarchar(250),
		@isdeleted bit,
		@IndividualUsers bit,
		@hasSpecialRights bit,
		@emp_id nvarchar(100),
		@timestamp datetime,
		@ReportsBasedOn bit,
		@AllowLeaveApprovalPastEntry bit
	)
AS
BEGIN
	--Insert
	declare @sql as nvarchar(2000)
	if (@opr=''I'')
		Begin
			--insert into ta_tbl_usergroup (groupname,isDeleted,Emp_id) values (@groupname,0,@emp_Id)
			set @sql = ''insert into ta_tbl_usergroup (groupname,isDeleted,Emp_id,IndividualUsers,hasSpecialRights,ReportsBasedOn,AllowLeaveApprovalPastEntry) values (N'''''' +  @groupname + '''''',0, '' + @emp_Id +'','' + cast(@IndividualUsers as nvarchar(5)) + '','' + cast(@hasSpecialRights as nvarchar(5)) + '','' + cast(@ReportsBasedOn as nvarchar(5)) + '','' + cast(@AllowLeaveApprovalPastEntry as nvarchar(5)) + '')''
exec(@sql)
		End
	--Update
	if (@opr=''U'')
		Begin
			--update ta_tbl_usergroup set groupname=@groupname,isDeleted=0,Emp_id=emp_id,timestamp=getDate() where groupId=@groupId
			set @sql = ''update ta_tbl_usergroup set groupname=N''''''+ @groupname + '''''', isDeleted=0,Emp_id='' + @emp_id + '',timestamp=getDate(), IndividualUsers='' + cast(@IndividualUsers as nvarchar(5)) +'',ReportsBasedOn='' + cast(@ReportsBasedOn as nvarchar(5)) +'',AllowLeaveApprovalPastEntry='' + cast(@AllowLeaveApprovalPastEntry as nvarchar(5)) +'', hasSpecialRights='' + cast(@hasSpecialRights as nvarchar(5)) +'' where groupname != ''''SuperAdmin'''' And  groupId='' + cast (@groupId as nvarchar)
			exec(@sql)
		End
	--Delete
	if (@opr=''D'')
		Begin
			update ta_tbl_usergroup set isdeleted=1,timestamp=getdate() where groupname !=''SuperAdmin'' and groupId=@groupId
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateType]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateType]
	@Opr as nvarchar(1),
	@Type as nvarchar(50),
	@EmpID as int,
	@TypeID as int,
	@IsFlexible as bit  =False
AS
BEGIN
	if (@Opr=''I'')	
		Begin
				Insert into Ta_tbl_Type (TypeName,IsDeleted,EmpId,IsFlexible) values (@Type,0,@EmpID,@IsFlexible)
		End
	Else
		Begin
				update TA_Tbl_Type set
					TypeName=@Type,
					EmpId = @EmpID,
					IsFlexible=@IsFlexible
				where TypeId=@TypeID
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateProject]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateProject]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<P.Velumani>
-- Create date: <03-Jan-2020>
-- Description:	<Insert and Update of Project information stored into database through this procedure>
-- [Proc_TA_InsertUpdateProject]0,''Coimabtore Project'',''PR001'',''a'','''','''','''',''yet to start'',0,1,1,12,
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateProject]
	@ProjectId bigint,
	@Project_Name varchar(250),
	@Project_Code varchar(15),
	@Client_Name varchar(150),
	@Project_Description varchar(500),
	@Project_StartTime datetime,
	@Project_EndTime datetime,
	@Project_Status varchar(15),
	@IsDeleted bit,
	@userId bigint,
	@LevelID int,
	@ManDays varchar(10),
	@ManHours varchar(10),
	@TableXML XML =NULL
AS
BEGIN
	SET NOCOUNT ON;
		DECLARE @Index INT 
		set @Index= 0
		declare @Error nvarchar(Max)
		EXEC sp_xml_preparedocument @Index OUTPUT, @TableXML
		declare @TaskList table(TaskID int, TaskName nvarchar(250),Hours varchar(20))
		INSERT INTO @TaskList (TaskID,TaskName,Hours)
		select * from OPENXML(@Index, ''/NewDataSet/TaskDetails'')
		WITH(TaskID nvarchar(10) ''TaskID'',TaskName nvarchar(250) ''TaskName'',Hours varchar(20) ''Hours'') 
		if(@ProjectId = 0)
			Begin
				insert into TA_Tbl_Project(Project_Name,Project_Code,Client_Name,Project_Description,Project_StartTime,Project_EndTime,Project_Status,IsDeleted,Created_By,Created_On,LevelID,Mandays,ManHours) values (@Project_Name,@Project_Code,@Client_Name, @Project_Description,@Project_StartTime,@Project_EndTime,@Project_Status,@IsDeleted,@userId,getdate(),@LevelID,@Mandays,@ManHours)
				 set @ProjectId = SCOPE_IDENTITY()
				 insert into TA_tbl_ProjectTaskList(ProjectID,TaskName,TaskHours) 
				 Select @ProjectId,TaskName,Hours from @TaskList
			End
		else 
			Begin
				update TA_Tbl_Project 
				set
				Project_Name = @Project_Name,
				Project_Code = @Project_Code,
				Client_Name = @Client_Name, 
				Project_Description = @Project_Description,
				Project_StartTime = @Project_StartTime,
				Project_EndTime = @Project_EndTime,
				Project_Status = @Project_Status,
				IsDeleted = @IsDeleted,
				Modified_By = @userId,
				Modified_On = getdate(),
				LevelID=@LevelID,
				Mandays=@Mandays,
				ManHours=@ManHours
				where Project_Id = @ProjectId
				delete from TA_tbl_ProjectTaskList where ProjectID=@ProjectId
				insert into TA_tbl_ProjectTaskList(ProjectID,TaskName,TaskHours) 
				Select @ProjectId,TaskName,Hours from @TaskList
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for Angler
Modified on	:	21-Feb-08
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfigSettings]  
	(
		@StartTime1 nvarchar(20),
		@EndTime1 nvarchar(20),
		@Day1 decimal,
		@StartTime2 nvarchar(20),
		@EndTime2 nvarchar(20),
		@Day2 decimal,
		@StartTime3 nvarchar(20),
		@EndTime3 nvarchar(20),
		@Day3 decimal,
		@StartTime4 nvarchar(20),
		@EndTime4 nvarchar(20),
		@Day4 decimal,
		@StartTime5 nvarchar(20),
		@EndTime5 nvarchar(20),
		@Day5 decimal,
		@StartTime6 nvarchar(20),
		@EndTime6 nvarchar(20),
		@Day6 decimal,
		@StartTime7 nvarchar(20),
		@EndTime7 nvarchar(20),
		@Day7 decimal,
		@StartTime8 nvarchar(20),
		@EndTime8 nvarchar(20),
		@Day8 decimal,
		@StartTime9 nvarchar(20),
		@EndTime9 nvarchar(20),
		@Day9 decimal,
		@StartTime10 nvarchar(20),
		@EndTime10 nvarchar(20),
		@Day10 decimal
	)  
AS  
declare @ArmisConfigCount int  
declare @LateEntryConfigCount int  
declare @WorkHrsConfigCount int  
SELECT @ArmisConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Armis
SELECT @LateEntryConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Lateentry
SELECT @WorkHrsConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_WorkHrs
if @ArmisConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Armis(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,StartTime7,EndTime7,Day7,StartTime8,EndTime8,Day8,
		StartTime9,EndTime9,Day9,StartTime10,EndTime10,Day10) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,@StartTime7,@EndTime7,@Day7,@StartTime8,@EndTime8,@Day8,
		@StartTime9,@EndTime9,@Day9,@StartTime10,@EndTime10,@Day10)       
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Armis SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day5,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,
    	StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,StartTime7=@StartTime7,EndTime7=@EndTime7,Day7=@Day7,StartTime8=@StartTime8,EndTime8=@EndTime8,Day8=@Day8,
    	StartTime9=@StartTime9,EndTime9=@EndTime9,Day9=@Day9,StartTime10=@StartTime10,EndTime10=@EndTime10,Day10=@Day10
    	END
if @LateEntryConfigCount=0   
	BEGIN 
	    	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis  
	--	INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)       
	END    
else    
    BEGIN  
        	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis 
	--	UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno where YearSettingId=@YearSettingId 
	END 
if @WorkHrsConfigCount=0   
	BEGIN
	    	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis   
	--	INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(@GlobalHoliday_Maxno,@YearlyHoliday_Maxno,@YearSettingId)       
	END    
else    
    BEGIN  
        	select  Count(*)  from ta_tbl_NoOfDaysDeduction_Armis 
	--	UPDATE TA_Tbl_HolidaySettings SET Global_Maxdays=@GlobalHoliday_Maxno,Yearly_Maxdays=@YearlyHoliday_Maxno where YearSettingId=@YearSettingId 
	END  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for WorkHours
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_WorkHours]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0,
		@StartTime6 int,
		@EndTime6 int,
		@Day6 FLOAT=0
	)  
AS  
declare @WorkHrsConfigCount int  
SELECT @WorkHrsConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_WorkHrs
if @WorkHrsConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_WorkHrs(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,getdate())   
		select @@identity    
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_WorkHrs SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,Datetime=getdate()
    	select WorkhrsID from ta_tbl_NoOfDaysDeduction_WorkHrs
    	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for LateEntry
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_LateEntry]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0,
		@StartTime6 int,
		@EndTime6 int,
		@Day6 FLOAT=0
	)  
AS  
declare @LateEntryConfigCount int  
SELECT @LateEntryConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Lateentry
if @LateEntryConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Lateentry(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,StartTime6,EndTime6,Day6,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,@StartTime6,@EndTime6,@Day6,getdate())    
		select @@identity   
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Lateentry SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,StartTime6=@StartTime6,EndTime6=@EndTime6,Day6=@Day6,Datetime=getdate()
    	select LateEntryID from ta_tbl_NoOfDaysDeduction_Lateentry
    	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created by	:	Gopinath.k
Description	:	Insert and update payroll configuration Settings for Armis
Modified on	:	21-JUl-2015
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdatePayrollConfig_Armis]  
	(
		@StartTime1 int,
		@EndTime1 int,
		@Day1 FLOAT=0,
		@StartTime2 int,
		@EndTime2 int,
		@Day2 FLOAT=0,
		@StartTime3 int,
		@EndTime3 int,
		@Day3 FLOAT=0,
		@StartTime4 int,
		@EndTime4 int,
		@Day4 FLOAT=0,
		@StartTime5 int,
		@EndTime5 int,
		@Day5 FLOAT=0
	)  
AS  
declare @ArmisConfigCount int
SELECT @ArmisConfigCount = Count(*)  from ta_tbl_NoOfDaysDeduction_Armis
if @ArmisConfigCount=0   
	BEGIN  
		INSERT INTO ta_tbl_NoOfDaysDeduction_Armis(StartTime1,EndTime1,Day1,StartTime2,EndTime2,Day2,StartTime3,EndTime3,Day3,
		StartTime4,EndTime4,Day4,StartTime5,EndTime5,Day5,Datetime) VALUES(@StartTime1,@EndTime1,@Day1,@StartTime2,@EndTime2,@Day2,@StartTime3,@EndTime3,@Day3,
		@StartTime4,@EndTime4,@Day4,@StartTime5,@EndTime5,@Day5,getdate())    
		select @@identity
	END    
else    
    BEGIN 
    	UPDATE ta_tbl_NoOfDaysDeduction_Armis SET StartTime1=@StartTime1,EndTime1=@EndTime1,Day1=@Day1,StartTime2=@StartTime2,EndTime2=@EndTime2,Day2=@Day2,
    	StartTime3=@StartTime3,EndTime3=@EndTime3,Day3=@Day3,StartTime4=@StartTime4,EndTime4=@EndTime4,Day4=@Day4,StartTime5=@StartTime5,EndTime5=@EndTime5,Day5=@Day5,Datetime=getdate()    	
    	select ArmisID from ta_tbl_NoOfDaysDeduction_Armis
    	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_InsertUpdateEmailScheduleDetails ''Test'',41,''Daily'',''Monday'',''Monday'',''Monday'',1,1,1,''10:30 AM'',1,1,1,''PortableDocFormat'',1
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleDetails]
(
	@ScheduleName varchar(250),
	@ReportId int,
	@Frequency varchar(20),
	@DayToSend varchar(10),
	@DayFrom varchar(10),
	@DayTo varchar(10),
	@DateToSend int,
	@DateFrom int,
	@DateTo int,
	@TimeToSend varchar(20),
	@EmployeeId int,
	@EmailSendType int,
	@Authentication int,
	@FileType varchar(20),
	@Enabled int,
	@ScheduleId int,
	@Type varchar(2),
	@ReportName varchar(50),
	@ToWhom bit,
	@TimeSendOption int=null
)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@Type = ''I'')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_EmailSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0)
		BEGIN		
			INSERT INTO TA_Tbl_EmailSchedule (ScheduleName,ReportId,Frequency,DayToSend,DayFrom,DayTo,DateToSend,DateFrom,DateTo,TimeToSend,EmployeeId,EmailSendType,Authentication,FileType,Enabled,IsDeleted,ReportName,ToWhom,TimeSendOption)
			VALUES(@ScheduleName,@ReportId,@Frequency,@DayToSend,@DayFrom,@DayTo,@DateToSend,@DateFrom,@DateTo,@TimeToSend,@EmployeeId,@EmailSendType,@Authentication,@FileType,@Enabled,0,@ReportName,@ToWhom,@TimeSendOption)
			SELECT CAST(@@IDENTITY AS INT) AS InsertedId
		END
		ELSE
		BEGIN
			SELECT 0
		END
	END
	ELSE IF(@Type = ''U'')
	BEGIN
		IF NOT EXISTS(SELECT ScheduleId FROM TA_Tbl_EmailSchedule WHERE ScheduleName = @ScheduleName and IsDeleted=0 and ScheduleId<>@ScheduleId)
		BEGIN
			UPDATE TA_Tbl_EmailSchedule SET ScheduleName = @ScheduleName,ReportId = @ReportId,Frequency = @Frequency,DayToSend = @DayToSend,
			DayFrom = @DayFrom,DayTo = @DayTo,DateToSend = @DateToSend, DateFrom = @DateFrom, DateTo = @DateTo, TimeToSend=@TimeToSend,
			EmployeeId = @EmployeeId, EmailSendType = @EmailSendType, Authentication = @Authentication, FileType = @FileType, Enabled = @Enabled,IsDeleted =0,
			ReportName=@ReportName,ToWhom=@ToWhom,TimeSendOption=@TimeSendOption
			where ScheduleId = @ScheduleId 
			SELECT 1
		END
		ELSE 
		BEGIN
		    SELECT 0
		END
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateLeaveSettings]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateLeaveSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		:  Kumuthini.L
-- Create date		: 19-Apr-08
-- Description		: Insert Update Leave Setting Details
-- Procedure Name	: Proc_TA_InsertUpdateLeaveSettings 12.5,7.5,35,6
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateLeaveSettings]		
(
	@CompanyId INT,
	@Approval INT,
	@FirstLevelIntimation INT,
	@SecondLevelIntimation INT,
	@ApprovalCC varchar(8000),
	@DailyReportTO varchar(8000),
	@DailyReportCC varchar(8000)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @RecCount AS INT
	SET @RecCount = (SELECT COUNT(*)  FROM TA_Tbl_LeaveSettings WHERE  CompanyId=@CompanyId)
	IF (@RecCount=0)
		BEGIN
			INSERT  INTO TA_Tbl_LeaveSettings (CompanyId,Approval,FirstLevelIntimation,SecondLevelIntimation,ApprovalCC,ToMail_DailyReport,CCMail_DailyReport) 
			VALUES (@CompanyId,@Approval,@FirstLevelIntimation,@SecondLevelIntimation,@ApprovalCC,@DailyReportTO,@DailyReportCC)
		END
	ELSE
		BEGIN
			UPDATE TA_Tbl_LeaveSettings SET Approval=@Approval,FirstLevelIntimation=@FirstLevelIntimation,SecondLevelIntimation=@SecondLevelIntimation,
			ApprovalCC=@ApprovalCC,ToMail_DailyReport=@DailyReportTO,CCMail_DailyReport=@DailyReportCC Where CompanyId=@CompanyId	
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_InsertUpdateInDetailsForService]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_InsertUpdateInDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- If Records does not Exist, the Insert the IN Record
-- Else Update the Clock Details Table with In Record with Minimum Clk_OutTime
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_InsertUpdateInDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@gstrClockDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Top 1 Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inClk_EmpId 
	AND (Clk_InTime = '''' OR Clk_InTime IS NULL) AND Clk_OutDate <> '''' AND Clk_OutDate IS NOT NULL AND 
	Clk_OutDeviceId IN (@strOutDeviceId)
	AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND Clk_Date= @gstrClockDate AND IsVoid=0
	ORDER BY (Clk_OutDate+Clk_OutTime) ASC
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_LeaveBonusAbsentees]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_LeaveBonusAbsentees]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-2007
-- Description:	Absentess reports
-- Proc_Ta_LeaveBonusAbsentees ''04/04/2008'',''04/30/2009'','''','''',''1,2,3,4'',0,0,''SuperAdmin'',3
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_Ta_LeaveBonusAbsentees]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
	SET NOCOUNT ON;
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT dbo.TA_Tbl_EmployeeLevel.LevelID, dbo.TA_Tbl_EmployeeDesignation.DesignationId, dbo.TA_Tbl_Employee.Employee_Code_Id, CONVERT(nvarchar(20), ''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_ProcessedData.Date, 101) AS date, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + SPACE(1)'' 
		set @sqlQuery = @sqlQuery + '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') AS empname, dbo.TA_Tbl_ProcessedData.Attendance, replace(dbo.TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName ,'' 
		set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, ta_tbl_shift.Shift_ShortName''
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_ProcessedData INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.SwipeCardNo''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		Set @sqlQuery = @sqlQuery + '' inner JOIN dbo.TA_Tbl_Shift ON dbo.TA_Tbl_Shift.Shift_ID = dbo.TA_Tbl_ProcessedData.Shift_ID  ''
 	        Set @sqlQuery = @sqlQuery + '' inner JOIN dbo.TA_Tbl_EmployeeBonusLeave ON dbo.TA_Tbl_EmployeeBonusLeave.EmployeeId = dbo.ta_tbl_Employee.Employee_Id  ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' WHERE (dbo.TA_Tbl_ProcessedData.Attendance = ''''Absent'''' OR dbo.TA_Tbl_ProcessedData.Attendance =''''LA'''' OR dbo.TA_Tbl_ProcessedData.Attendance = ''''AL'''' OR dbo.TA_Tbl_ProcessedData.LeaveCode = ''''LOP'''') AND (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0)AND (dbo.TA_Tbl_Employee.Report_Exclude = 0)''		
		set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
		set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
		if not(@EmployeeName='''' or @EmployeeName=''0'')
			begin
				set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
			end
		if not (@empId='''' or @empId=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
			end
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryId = '' +cast(@employeeCategory as nvarchar(8))
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' +cast(@employeeType as nvarchar(8))
			end		
		if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and (#EmpLevel.LevelId IN ('' + @LevelId + ''))'' 
			end			
		set @sqlQuery = @sqlQuery + '' order by TA_Tbl_ProcessedData.Employee_Code_Id,dbo.TA_Tbl_ProcessedData.Date''
		exec(@sqlQuery)
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveAvailedinMonth]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveAvailedinMonth]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_LeaveAvailedinMonth 500
-- =============================================
-- Author:		<Angeswaran>
-- Create date: <10-Apr-2012>
-- Description:	<Leave availed in the month wise>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LeaveAvailedinMonth] 
	@LeaveApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @FromDate datetime
	Declare @ToDate datetime
    Declare @EmployeeId int
    select @EmployeeId=Employee_Id from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplicationId
    create table #TempLeave(EmployeeId int,LeaveApplication_Id int,Leave_FromDate datetime,Leave_ToDate datetime,MonthName varchar(25),NumberofDays float)
    insert into #TempLeave
    select LA.Employee_Id,LeaveApplication_Id,Leave_FromDate,Leave_ToDate,DATENAME(month,Leave_FromDate),sum(NumberOfDays) from TA_Tbl_LeaveApplication LA
    inner join TA_Tbl_YearSetting YS on LA.YearSettings_Id=YS.YearSettings_Id where Employee_Id=@EmployeeId and YS.IsActive=1 and LA.IsDeleted=0
    and LA.Status=''Approved'' and LA.Type <> ''Comp Off'' group by Leave_FromDate,Leave_ToDate,DATENAME(month,Leave_FromDate),LeaveApplication_Id,LA.Employee_Id
    create table #TempLeave1(EmployeeId int,LeaveApplication_Id int,Leave_FromDate datetime,Leave_ToDate datetime,MonthName varchar(25),NumberofDays float)
    insert into #TempLeave1
    select LA.Employee_Id, LA.LeaveApplication_Id,LA.Leave_FromDate,LA.Leave_ToDate,DATENAME(month,LA.Leave_FromDate),ISNULL(SUM(TL.NumberofDays),0.0)
    from TA_Tbl_LeaveApplication LA left outer join #TempLeave TL on LA.Employee_Id=TL.EmployeeId and DATENAME(MONTH,LA.Leave_FromDate)=TL.MonthName
    where LA.LeaveApplication_Id=@LeaveApplicationId   group by 
    LA.LeaveApplication_Id,LA.Leave_FromDate,LA.Leave_ToDate,DATENAME(month,LA.Leave_FromDate),LA.Employee_Id
    create table #Month(Monthname varchar(30),Monthvalue int)
    insert into #Month values(''January'',1)
    insert into #Month values(''February'',2)
    insert into #Month values(''March'',3)
    insert into #Month values(''April'',4)
    insert into #Month values(''May'',5)
    insert into #Month values(''June'',6)
    insert into #Month values(''July'',7)
    insert into #Month values(''August'',8)
    insert into #Month values(''September'',9)
    insert into #Month values(''October'',10)
    insert into #Month values(''November'',11)
    insert into #Month values(''December'',12)
   select MonthName, NumberofDays from(select distinct #TempLeave1.MonthName, NumberofDays,Monthvalue from #TempLeave1 inner join #Month
	on #TempLeave1.MonthName=#Month.Monthname) A order by A.Monthvalue
	drop table #TempLeave1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_LateEntry]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_LateEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[proc_TA_LateEntry]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(18) 
)
AS
BEGIN
	declare @sqlQuery as varchar(1500)
	declare @shfTime as dateTime
	set @shfTime = (select Shift_StartTime from ta_tbl_shift where shift_id = @shift)	
	declare @graceTime as decimal
	set @graceTime = (select shift_graceOutTime from ta_tbl_shift where shift_id=@shift)
	set @sqlQuery = ''''	
	set @sqlQuery = @sqlQuery + '' select ta_tbl_Employee.LevelId,CONVERT(nvarchar(20),'''''' + cast( convert( nvarchar(20),@shfTime,108) as nvarchar(50))   + '''''' ,108) as shiftIn	, dbo.TA_Tbl_Employee.Employee_Code_Id, CONVERT(nvarchar(20),dbo.TA_Tbl_ProcessedData.Date,101) as date,TA_Tbl_ProcessedData.InTime,ta_tbl_processeddata.shift_id,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_ProcessedData.LateIn,TA_Tbl_ProcessedData.Reason,(dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + dbo.TA_Tbl_Employee.Employee_LastName) as empname  , dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName  FROM  dbo.TA_Tbl_ProcessedData ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.Employee_Id INNER JOIN''
	set @sqlQuery = @sqlQuery + '' dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_Employee.LevelID = dbo.Ta_Tbl_levelDetails.id INNER JOIN''
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_Employee.Designation_Id = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' where ta_tbl_processeddata.LateIn <> ''''0'''' and ta_tbl_processeddata.LateIn <> ''''00:00:00'''' and ta_tbl_processedData.LateIn is not null'' 
	set @sqlQuery = @sqlQuery + '' And     (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
	set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 
	set @sqlQuery = @sqlQuery + '' and (DATEDIFF(mi, CONVERT(datetime,dbo.TA_Tbl_ProcessedData.LateIn,101), CONVERT(datetime,'''''' + cast (@shfTime as nvarchar(50)) + '''''', 101)) > '' + cast (@graceTime as nvarchar(20)) + '')''
	if not(@EmployeeName='''' or @EmployeeName=''0'')
	begin
		set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
	end
	if not (@empId='''' or @empId=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' and ta_tbl_processedData.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
	end
	if not(@LevelID='''' or @LevelID=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.LevelId = '' + cast (@LevelId as nvarchar(50)) 
	end
	set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_ProcessedData.Date''
	Exec(@sqlQuery)		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_IsAuditTrailSaved]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_IsAuditTrailSaved]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_IsAuditTrailSaved  
Description : select from TA_Tbl_AuditTable to check whether is Audit Trail is saved before
Tables Included : TA_Tbl_AuditTable
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_IsAuditTrailSaved] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_AuditTable
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearSetting]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearSetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_InsertYearSetting  
Description : Save year settings details into table  
Tables Included : TA_Tbl_YearSetting  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
 Proc_TA_InsertYearSetting ''April'',''2017'',''March'',''2018'',''4/1/2017'',''3/31/2018'',1
*/  
CREATE   Procedure [dbo].[Proc_TA_InsertYearSetting]  
	@StartMonth varchar(30),  
	@StartYear varchar(30),  
	@EndMonth varchar(30),  
	@EndYear varchar(30), 
	@FromDate varchar(30),
	@ToDate varchar(30), 
	@Employee_Id int
as  
Begin
	set nocount on
	declare @RecordExiststing as int  
	SELECT @RecordExiststing=count(*) FROM TA_Tbl_YearSetting
	if @RecordExiststing=0  
	begin  
		update TA_Tbl_YearSetting set IsActive=0  
		Insert into TA_Tbl_YearSetting(StartMonth,StartYear,EndMonth,EndYear,FromDate,ToDate,Emp_Id,IsActive)  
		values(@StartMonth,@StartYear, @EndMonth,@EndYear,@FromDate,@ToDate,@Employee_Id,1)  
	end 
	else
	begin
		Insert into TA_Tbl_YearSetting(StartMonth,StartYear,EndMonth,EndYear,FromDate,ToDate,Emp_Id,IsActive)  
		values(@StartMonth,@StartYear, @EndMonth,@EndYear,@FromDate,@ToDate,@Employee_Id,0)  
	end 
	DECLARE @HolidayCount INT
	DECLARE @YearSettingId int
	SELECT @YearSettingId=scope_identity()
	SELECT @HolidayCount=Count(*)FROM TA_Tbl_HolidaySettings WHERE YearSettingId=@YearSettingId
	IF @HolidayCount=0  
	BEGIN  
		INSERT INTO TA_Tbl_HolidaySettings(Global_Maxdays,Yearly_Maxdays,YearSettingId) VALUES(10,10,@YearSettingId)  
	END
	select @YearSettingId as YearSettingsID
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutAdmin]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutAdmin]
	-- Add the parameters for the stored procedure here
	@UserId as nvarchar(15)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_ConcurrentUser WHERE UserId = @UserId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoginOrNot]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoginOrNot]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoginOrNot] 
	@userId as nvarchar(15),
    @ipAddress as nvarchar(15),
    @sessionId as nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ConcurrentUserId, LoginTime  FROM TA_Tbl_ConcurrentUser where UserId = @userId AND IpAddress = @ipAddress AND status=1 AND SessionId = @sessionId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LocationNameExists]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LocationNameExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LocationNameExists]
	@locationname nvarchar(250)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT count(*)as Total from ta_tbl_landmarks where locationname=@locationname
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadShiftByLevelsId]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadShiftByLevelsId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	26-Dec-2013
Descriptions	:	Getting shifts based on selected levels in temp weekday
Proc_TA_LoadShiftByLevelsId ''1,2,3,12,4,16,11,14,13,18,20,22,24''
*/
CREATE proc [dbo].[Proc_TA_LoadShiftByLevelsId]
(
@LevelIds nvarchar(max)
)
as
begin
	declare @SchemaName as varchar(200);
	set @SchemaName=(SELECT top 1 specific_schema FROM INFORMATION_SCHEMA.Routines where specific_name=''Func_TA_GetParentIds'')
	declare @SQLQuery as nvarchar(max);
	set @SQLQuery=''select [''+@SchemaName+''].Func_TA_GetParentIds(''''''+cast(@LevelIds as varchar(250))+'''''')  '';
	create table #Temp
	(
	LevelId varchar(250)
	)
	insert into #Temp
	exec(@SQLQuery);
	select @LevelIds= (select LevelId from #Temp);
	select Shift_Id,Shift_ShortName+'' :''+Shift_StartTime+'' To ''+Shift_EndTime as Shift_ShortName,
	cast(Shift_StartTime as datetime) as Shift_StartTime,
	case when Shift_EndTime like ''%AM'' then DATEADD(DAY,1,cast(Shift_EndTime as datetime))
	else cast (Shift_EndTime as datetime) end as Shift_EndTime
	from TA_Tbl_Shift
	where Level_Id in (select Value from dbo.Split(@LevelIds,'',''))
	drop table #Temp
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadLeaveTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manjula.P>
-- Create date: <18-Jul-2013>
-- Description:	<Loading the leave Types for the Employee Master>
--	Proc_TA_LoadLeaveTypes 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoadLeaveTypes] 
	@YearSettignsId INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @CurrentYear AS INT;
	DECLARE @getFirstPreviousYearCount AS INT;
	DECLARE @EndYear AS INT;
	SET @EndYear=0;
	SET @getFirstPreviousYearCount=0;
	SET @CurrentYear=0;
	SELECT @CurrentYear=StartYear,@EndYear=EndYear FROM TA_Tbl_YearSetting WHERE YearSettings_Id=@YearSettignsId and IsActive=1
	--SELECT @getFirstPreviousYearCount=COUNT(*) FROM TA_Tbl_YearSetting WHERE StartYear<@CurrentYear and EndYear<@EndYear
	--IF(@getFirstPreviousYearCount=0)
	--BEGIN
		SELECT LeaveType_Id as Emp_LeaveType_Id,LeaveType,LeaveDescription=LeaveDescription + '' (''+LeaveType+'')'' FROM ta_tbl_leaveType WHERE isdeleted=0
	--END
	--ELSE
	--BEGIN
	--	SELECT 0 as Emp_LeaveType_Id;
	--END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LookupTable]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LookupTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- Create date: 21 July 2007
-- Description:	Look up Table Queries
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LookupTable] 
@Type CHAR(1),
@ID INT
AS
BEGIN
	SET NOCOUNT ON;
	IF (@Type=''C'')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=1 and isdeleted=0
	ELSE IF (@Type=''S'')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=2 AND Parent=@ID and isdeleted=0
	ELSE IF (@Type=''T'')
		SELECT * FROM TA_Tbl_Lookup WHERE  Type=3 AND Parent=@ID and isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LogoutUserOwn]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LogoutUserOwn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LogoutUserOwn]
	-- Add the parameters for the stored procedure here
	@UserId nvarchar(15),  
	@IpAddress nvarchar(15),  
	@SessionId nvarchar(25)  
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM ta_tbl_concurrentuser where UserId=@UserId and IpAddress=@IpAddress and SessionId=@SessionId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_MappingCorrespondingPunches]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_MappingCorrespondingPunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 25-08-2014
-- Description:	Map the corresponding punch details
-- select * from ta_tbl_MatchedPunches where Clk_Date=''2014-08-11'' and Clk_EmpId=''787''
-- Break In Came
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-11 00:00:00.000'',''1900-01-01 11:02:00.000'',''Break In'',''2014-08-11 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''788'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:13:00.000'',''Break In'',''2014-08-18 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:15:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:14:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:10:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:09:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:07:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:25:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:08:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:05:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:12:00.000'',''Break In'',''2014-08-04 00:00:00.000''
-- Break Out came
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-11 00:00:00.000'',''1900-01-01 11:00:00.000'',''Break Out'',''2014-08-11 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''787'',''2014-08-04 00:00:00.000'',''1900-01-01 11:10:00.000'',''Break Out'',''2014-08-04 00:00:00.000''
-- Proc_Ta_MappingCorrespondingPunches ''787'',''788'',''2014-07-09 00:00:00.000'',''1900-01-01 09:00.000'',''Break Out'',''2014-07-09 00:00:00.000''
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_MappingCorrespondingPunches]
	-- Add the parameters for the stored procedure here
@clk_empid NVARCHAR(20),
@clk_InOrOutDeviceId VARCHAR(20),
@clk_InOrOutDate DATETIME,
@clk_InOrOutTime DATETIME,
@clk_InOrOutPunchType VARCHAR(25),
@clk_date DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	CREATE TABLE #TempInPunchDetails
	(
		TempInPunch_AutoId INT IDENTITY(1,1),
		TempInPunch_clk_empid NVARCHAR(20),
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		TempInPunch_clk_date DATETIME
	)
	CREATE TABLE #TempOutPunchDetails
	(
		TempOutPunch_AutoId INT IDENTITY(1,1),
		TempOutPunch_clk_empid NVARCHAR(20),
		TempOutPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempOutPunch_clk_InOrOutDate DATETIME,
		TempOutPunch_clk_InOrOutTime DATETIME,
		TempOutPunch_clk_InOrOutPunchType VARCHAR(25),
		TempOutPunch_clk_date DATETIME,
		TempOutPunch_MappedOrNot INT,
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25)		
	)	
	CREATE TABLE #TempInPunchDetails1
	(
		TempInPunch_AutoId INT IDENTITY(1,1),
		TempInPunch_clk_empid NVARCHAR(20),
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		TempInPunch_clk_date DATETIME
	)
	CREATE TABLE #TempOutPunchDetails1
	(
		TempOutPunch_AutoId INT IDENTITY(1,1),
		TempOutPunch_clk_empid NVARCHAR(20),
		TempOutPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempOutPunch_clk_InOrOutDate DATETIME,
		TempOutPunch_clk_InOrOutTime DATETIME,
		TempOutPunch_clk_InOrOutPunchType VARCHAR(25),
		TempOutPunch_clk_date DATETIME,
		TempOutPunch_MappedOrNot INT,
		TempInPunch_clk_InOrOutDeviceId VARCHAR(20),
		TempInPunch_clk_InOrOutDate DATETIME,
		TempInPunch_clk_InOrOutTime DATETIME,
		TempInPunch_clk_InOrOutPunchType VARCHAR(25),
		OrderBy int default 787
	)		
	IF(@clk_InOrOutPunchType=''Break Out'' or @clk_InOrOutPunchType=''Break In'')
		BEGIN		
			DELETE FROM ta_tbl_MatchedPunches WHERE Clk_EmpId=@clk_empid and Clk_Date=@clk_date
			and (Clk_InPunchType=''Break Out'' or Clk_OutPunchType=''Break In'')
			INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutDate + '' ''+ Clk_OutTime,Clk_OutPunchType,Clk_Date,0 FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_OutPunchType=''Break Out''
			ORDER BY Clk_OutDate+'' ''+Clk_OutTime
			--Before Adding this procedure means,we need to enable below line
			--IF(@clk_InOrOutPunchType=''Break Out'')
			--	BEGIN
			--		INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date)
			--		VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
			--	END
			INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InDate+'' ''+Clk_InTime,Clk_InPunchType,Clk_Date FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_InPunchType=''Break In''
			ORDER BY Clk_InDate +'' ''+Clk_InTime
			--Before Adding this procedure means,we need to enable below line
			--IF(@clk_InOrOutPunchType=''Break In'')
			--	BEGIN
			--		INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			--		VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
			--	END
			--For ordering the Datetime
			INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,0 FROM #TempOutPunchDetails WHERE TempOutPunch_clk_date=@clk_date and TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_InOrOutPunchType=''Break Out''
			ORDER BY TempOutPunch_clk_InOrOutTime
			INSERT INTO #TempInPunchDetails1(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType=''Break In''
			ORDER BY TempInPunch_clk_InOrOutTime
		END
	IF(@clk_InOrOutPunchType=''Official Out'' or @clk_InOrOutPunchType=''Official In'')
		BEGIN		
			DELETE FROM ta_tbl_MatchedPunches WHERE Clk_EmpId=@clk_empid and Clk_Date=@clk_date
			and (Clk_InPunchType=''Official Out'' or Clk_OutPunchType=''Official In'')
			INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutDate + '' ''+ Clk_OutTime,Clk_OutPunchType,Clk_Date,0 FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_OutPunchType=''Official Out''
			ORDER BY Clk_OutDate+'' ''+Clk_OutTime
			IF(@clk_InOrOutPunchType=''Official Out'')
				BEGIN
					INSERT INTO #TempOutPunchDetails(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date)
					VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
				END
			INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InDate+'' ''+Clk_InTime,Clk_InPunchType,Clk_Date FROM TA_Tbl_ClockDetails WHERE Clk_Date=@clk_date and Clk_EmpId=@clk_empid and Clk_InPunchType=''Official In''
			ORDER BY Clk_InDate +'' ''+Clk_InTime
			IF(@clk_InOrOutPunchType=''Official In'')
				BEGIN
					INSERT INTO #TempInPunchDetails(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
					VALUES(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
				END
			--For ordering the Datetime
			INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,TempOutPunch_MappedOrNot)
			SELECT TempOutPunch_clk_empid,TempOutPunch_clk_InOrOutDeviceId,TempOutPunch_clk_InOrOutDate,TempOutPunch_clk_InOrOutTime,TempOutPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,0 FROM #TempOutPunchDetails WHERE TempOutPunch_clk_date=@clk_date and TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_InOrOutPunchType=''Official Out''
			ORDER BY TempOutPunch_clk_InOrOutTime
			INSERT INTO #TempInPunchDetails1(TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date)
			SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType=''Official In''
			ORDER BY TempInPunch_clk_InOrOutTime
		END
	DECLARE @MatchedPunchesTableCount INT
	DECLARE @InPunchTableCount INT
	DECLARE @MatchedPunchesTableStart INT
	DECLARE @InPunchTableStart INT
	--#TempOutPunchDetails variables
	DECLARE @TempOutPunchInOrOutTime DATETIME
	DECLARE @TempOutPunchAutoId INT
	DECLARE @matchedUpdateId INT
	--#TempInPunchDetails variables
	DECLARE @TempInPunch_Intime DATETIME
	DECLARE @TempInPunch_ClkInDate DATETIME
	DECLARE @TempInPunch_ClkInDeviceId VARCHAR(20)
	DECLARE @TempInPunch_ClkInPunchType VARCHAR(20)
	SET @MatchedPunchesTableStart =1
	SET @InPunchTableStart =1
	SET @MatchedPunchesTableCount=(SELECT COUNT(*) FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid=@clk_empid and TempOutPunch_clk_date=@clk_date)
	SET @InPunchTableCount =(SELECT COUNT(*) FROM #TempInPunchDetails1 WHERE TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_date=@clk_date)
	--select @MatchedPunchesTableCount,@InPunchTableCount	
	select * from #TempInPunchDetails1
	select * from #TempOutPunchDetails1
	IF(@MatchedPunchesTableCount!=0 and @InPunchTableCount!=0)
		BEGIN
			WHILE @InPunchTableCount>0
				begin
					SELECT @TempInPunch_Intime=TempInPunch_clk_InOrOutTime,@TempInPunch_ClkInDate=TempInPunch_clk_InOrOutDate,@TempInPunch_ClkInDeviceId=TempInPunch_clk_InOrOutDeviceId,
					@TempInPunch_ClkInPunchType=TempInPunch_clk_InOrOutPunchType
					FROM #TempInPunchDetails1 WHERE TempInPunch_AutoId=@InPunchTableStart
					SELECT @TempOutPunchInOrOutTime=isnull(TempOutPunch_clk_InOrOutTime,0),@TempOutPunchAutoId=TempOutPunch_AutoId FROM #TempOutPunchDetails1 WHERE TempOutPunch_AutoId=@MatchedPunchesTableStart and TempOutPunch_MappedOrNot=0
					IF(@TempOutPunchInOrOutTime!=''1900-01-01 00:00:00.000'')
						BEGIN
							if @TempOutPunchInOrOutTime<=@TempInPunch_Intime
								BEGIN
									SET @matchedUpdateId=@TempOutPunchAutoId
									SET @TempOutPunchInOrOutTime=''''
									SET @MatchedPunchesTableStart=@MatchedPunchesTableStart+1
									CONTINUE;
								END
							ELSE
								BEGIN
									IF(@matchedUpdateId!=0)
										BEGIN
											UPDATE #TempOutPunchDetails1 SET TempInPunch_clk_InOrOutDeviceId=@TempInPunch_ClkInDeviceId,
											TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate,
											TempInPunch_clk_InOrOutTime=@TempInPunch_Intime,
											TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType,
											TempOutPunch_MappedOrNot=1
											,OrderBy=@InPunchTableStart+3 
											WHERE TempOutPunch_AutoId=@matchedUpdateId
											UPDATE #TempOutPunchDetails1 SET TempOutPunch_MappedOrNot=1 where TempOutPunch_AutoId<@matchedUpdateId
											and TempOutPunch_MappedOrNot=0
											SET @matchedUpdateId=0
										END
									ELSE
										BEGIN
											IF((SELECT COUNT(*)FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid= @clk_empid and TempOutPunch_clk_date = @Clk_Date 
											and TempInPunch_clk_InOrOutTime=@TempInPunch_Intime and TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate 
											and TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType)=0)
											BEGIN
												INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,OrderBy)
												values(@clk_empid,@TempInPunch_ClkInDeviceId,@TempInPunch_ClkInDate,@TempInPunch_Intime,@TempInPunch_ClkInPunchType,@Clk_Date,@InPunchTableStart+3)
											END
										END
								END
						END
					ELSE
						BEGIN
							IF(@matchedUpdateId!=0)
								BEGIN
									UPDATE #TempOutPunchDetails1 SET TempInPunch_clk_InOrOutDeviceId=@TempInPunch_ClkInDeviceId,
									TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate,
									TempInPunch_clk_InOrOutTime=@TempInPunch_Intime,
									TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType,
									TempOutPunch_MappedOrNot=1,
									OrderBy=@InPunchTableStart+3
									WHERE TempOutPunch_AutoId=@matchedUpdateId
									UPDATE #TempOutPunchDetails1 SET TempOutPunch_MappedOrNot=1 where TempOutPunch_AutoId<@matchedUpdateId
									and TempOutPunch_MappedOrNot=0
									SET @matchedUpdateId=0
								END
							ELSE
								BEGIN
									IF((SELECT COUNT(*)FROM #TempOutPunchDetails1 WHERE TempOutPunch_clk_empid= @clk_empid and TempOutPunch_clk_date = @Clk_Date 
									and TempInPunch_clk_InOrOutTime=@TempInPunch_Intime and TempInPunch_clk_InOrOutDate=@TempInPunch_ClkInDate 
									and TempInPunch_clk_InOrOutPunchType=@TempInPunch_ClkInPunchType)=0)
											BEGIN
												INSERT INTO #TempOutPunchDetails1(TempOutPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date,OrderBy)
												values(@clk_empid,@TempInPunch_ClkInDeviceId,@TempInPunch_ClkInDate,@TempInPunch_Intime,@TempInPunch_ClkInPunchType,@Clk_Date,@InPunchTableStart+3)
											END
								END
						END
					SET @InPunchTableCount=@InPunchTableCount-1
					SET @InPunchTableStart=@InPunchTableStart+1
					--SET @MatchedPunchesTableStart=@MatchedPunchesTableStart+1
				END
				IF(@InPunchTableCount<=0)
					BEGIN
						INSERT INTO ta_tbl_MatchedPunches 
						SELECT 	TempOutPunch_clk_empid,
						TempOutPunch_clk_InOrOutDeviceId,
						TempOutPunch_clk_InOrOutDate ,
						TempOutPunch_clk_InOrOutTime ,
						TempOutPunch_clk_InOrOutPunchType,
						TempInPunch_clk_InOrOutDeviceId,
						TempInPunch_clk_InOrOutDate,
						TempInPunch_clk_InOrOutTime,
						TempInPunch_clk_InOrOutPunchType,TempOutPunch_clk_date
						FROM #TempOutPunchDetails1 order by OrderBy,TempOutPunch_clk_InOrOutTime 
					END
		END
	ELSE
		BEGIN
			IF(@MatchedPunchesTableCount=0 and @InPunchTableCount!=0)
				BEGIN
					IF(@clk_InOrOutPunchType=''Break In'' OR @clk_InOrOutPunchType=''Official In'')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails1 WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType=''Break In''
							ORDER BY TempInPunch_clk_InOrOutTime
						END
				END
			IF(@MatchedPunchesTableCount!=0 AND @InPunchTableCount=0)
				BEGIN
					IF(@clk_InOrOutPunchType=''Break Out'' OR @clk_InOrOutPunchType=''Official Out'')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT 	TempOutPunch_clk_empid,
							TempOutPunch_clk_InOrOutDeviceId,
							TempOutPunch_clk_InOrOutDate ,
							TempOutPunch_clk_InOrOutTime ,
							TempOutPunch_clk_InOrOutPunchType,
							TempOutPunch_clk_date
							FROM #TempOutPunchDetails1
						END
				END
			IF(@MatchedPunchesTableCount=0 AND @InPunchTableCount=0)
				BEGIN
					IF(@clk_InOrOutPunchType=''Break Out'' OR @clk_InOrOutPunchType=''Official Out'')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)		
							SELECT 	TempOutPunch_clk_empid,
							TempOutPunch_clk_InOrOutDeviceId,
							TempOutPunch_clk_InOrOutDate ,
							TempOutPunch_clk_InOrOutTime ,
							TempOutPunch_clk_InOrOutPunchType,
							TempOutPunch_clk_date
							FROM #TempOutPunchDetails1
						END
					IF(@clk_InOrOutPunchType=''Break In'' OR @clk_InOrOutPunchType=''Official In'')
						BEGIN
							INSERT INTO ta_tbl_MatchedPunches(Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date)
							--(@clk_empid,@clk_InOrOutDeviceId,@clk_InOrOutDate,@clk_InOrOutDate+'' ''+@clk_InOrOutTime,@clk_InOrOutPunchType,@clk_date)
							SELECT TempInPunch_clk_empid,TempInPunch_clk_InOrOutDeviceId,TempInPunch_clk_InOrOutDate,TempInPunch_clk_InOrOutTime,TempInPunch_clk_InOrOutPunchType,TempInPunch_clk_date FROM #TempInPunchDetails1 WHERE TempInPunch_clk_date=@clk_date and TempInPunch_clk_empid=@clk_empid and TempInPunch_clk_InOrOutPunchType=''Break In''
							ORDER BY TempInPunch_clk_InOrOutTime
						END
				END
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Insert]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Levels_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Levels_Insert] 
(
	@levelName nvarchar(100),
	@parentLevelId int,
	@emp_id nvarchar(20)
)
AS
Begin
	declare @sql as nvarchar(1000)	
	--insert into Ta_Tbl_level (levelname,parentLevelId) values(@levelname,@parentLevelId);
	declare @recCount as int
	set @recCount = (select count(*) from ta_tbl_level where levelname=@levelName and isdeleted=0)
	if (@recCount=0)
	begin
		set @sql = ''insert into Ta_Tbl_level (levelname,parentLevelId,emp_id) values(N'''''' + @levelname + '''''','' + cast(@parentLevelId as nvarchar(25)) + '','' + @emp_id + '')''	
		exec(@sql)
	end
	select @recCount as recCount	
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_NotProcessedDataDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_NotProcessedDataDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_NotProcessedDataDetails]
	-- Add the parameters for the stored procedure here
	@ManualTimeEntry_Id int,
	@ManualTimeEntry_Employee_Id int,
	@ManualTimeEntry_InReaderID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Insert into Ta_tbl_NotProcessedDataDetails values(@ManualTimeEntry_Id,@ManualTimeEntry_Employee_Id,@ManualTimeEntry_InReaderID,''Punch Types is not defined'',''M'')
    -- Insert statements for procedure here
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDiscrepancyData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDiscrepancyData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_InsertDiscrepancyData] ''emp102'',''01/01/2009'',''03:44 pm'',''In'',0,'''','''','''',0,6
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertDiscrepancyData]
	@EmployeeCodeID as nvarchar(25),
	@InDate as nvarchar(20),
	@InTime as nvarchar(20),
	@InPunchType as nvarchar(25),
	@InReaderID as int,
	@OutDate as nvarchar(20),
	@OutTime as nvarchar(20),
	@OutPunchType as nvarchar(25),
	@OutReaderID as int,
	@EmpID as int,
	@strManaulEntryStatus as nvarchar(30),
	@Reason as nvarchar(255)
AS
BEGIN
	set nocount on;
	if @OutDate=''''
	begin
		set @OutDate=NULL
	end
	if @InDate=''''
	begin
		set @InDate=NULL
	end
	if @Intime=''''
	begin
		set @InTime=NULL
	end
	if @OutTime=''''
	begin
		set @OutTime=NULL
	end
	if (@Reason='''' or @Reason is null)
	begin
		set @Reason=''Discrepancy Entry''
	end
	if(@strManaulEntryStatus='''')
	begin
		set @strManaulEntryStatus=''Pending''
	end
	--Declare @Terminal_Id int
	--Declare @Terminal_IdCount int
	--if(@InReaderID=0)
	--BEGIN		
	--	select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787''
	--	if(@Terminal_Id='''')
	--	begin
	--		insert into TA_Tbl_Terminal values(''787'',''787'',''787'',1,GETDATE(),1,0)			
	--		select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787''
	--	end		
	--	if(@Terminal_Id!='''')
	--	begin
	--		select @Terminal_IdCount=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
	--		if(@Terminal_IdCount=2)
	--		begin
	--			set @InReaderID=@Terminal_Id
	--			set @OutReaderID=@Terminal_Id
	--		end
	--		else if(@Terminal_IdCount=1)
	--		begin
	--			set @InReaderID=@Terminal_Id
	--		end			
	--		if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@Terminal_Id and PunchType=@InPunchType)
	--		begin
	--			select top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@Terminal_Id
	--		end
	--		IF(@OutReaderID!=0)
	--		BEGIN
	--			if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID and PunchType=@OutPunchType)
	--			begin
	--				select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID
	--			end
	--		end
	--	end		
	--END	
	--IF(@OutReaderID=0)
	--BEGIN
	--	set @Terminal_Id =''''
	--	select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788''
	--	if(@Terminal_Id='''')
	--	begin
	--		insert into TA_Tbl_Terminal values(''788'',''788'',''788'',1,GETDATE(),1,0)			
	--		select @Terminal_Id =Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788''
	--	end
	--	if(@Terminal_Id!='''')
	--	begin
	--		select @Terminal_IdCount=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
	--		if(@Terminal_IdCount=1)
	--		begin
	--			set @OutReaderID=@Terminal_Id
	--		end
	--		if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID and PunchType=@OutPunchType)
	--		begin
	--			select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutReaderID
	--		end
	--	end	
	--END	
	declare @YearID as int
	select @YearID = YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1
	
	insert into Ta_Tbl_ManualTimeEntry 
	(
		ManualTimeEntry_Date,
		ManualTimeEntry_Employee_Id,
		ManualTimeEntry_InDate,
		ManualTimeEntry_InTime,
		ManualTimeEntry_InPunchType,
		ManualTimeEntry_InReaderID,
		ManualTimeEntry_OutDate,
		ManualTimeEntry_OutTime,
		ManualTimeEntry_OutPunchType,
		ManualTimeEntry_OutReaderID,
		ManualTimeEntry_Reason,
		Clk_Process,
		ManualTimeEntry_Status,
		YearSettings_Id,
		Isdeleted,
		Emp_ID,
		IsDiscrepancyEntry,
		IsOnDuty
	)
	values 
	(
		Convert(varchar(15),getDate(),101),
		@EmployeeCodeID,
		@InDate,
		@InTime,
		@InPunchType,
		@InReaderID,
		@OutDate,
		@OutTime,
		@OutPunchType,
		@OutReaderID,
		@Reason,
		''N'',
		@strManaulEntryStatus,
		@YearID,
		0,
		@EmpID,
		1,
		0
	)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MaxHoliday]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_MaxHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_MaxHoliday]
AS
BEGIN
 	 SELECT *  FROM TA_Tbl_HolidaySettings
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OndutyApplicationApproved]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OndutyApplicationApproved]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan
-- Create date: 14-Mar-2016
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OndutyApplicationApproved]
	@ODID int,
	@Status nvarchar(50),
	@Remarks nvarchar(Max),
	@Emp_ID int
AS
BEGIN
	SET NOCOUNT ON;
	update Ta_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@Emp_ID as nvarchar(20)) where OnDuty_ID=@ODID
	update TA_Tbl_OndutyEntry set Onduty_Status=@Status,Emp_Id=@Emp_ID where Onduty_ID=@ODID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSLogDeatils]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSLogDeatils]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSLogDeatils]
	-- Add the parameters for the stored procedure here
	@templateId int, 
	@fromDate datetime, 
	@toDate datetime, 
	@status int, 
	@receivers varchar(max), 
	@parentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from ta_tbl_smstemplates
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSGateWayDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSGateWayDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016>
-- Description:	<Getting SMS Gateway Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSGateWayDetails]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT id,ServiceUrl,DestinationKey,MessageKey,PhNo,TimeStamp from ta_tbl_SMSGateway
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForOnDuty]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForOnDuty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Amsaveni>
-- Create date: <24/07/2013>
-- Description:	<To retrieve shift and time>
-- [Proc_TA_SelectShiftIdForOnDuty] ''VA163'',''2019'',''11'',''14''
-- Modified the shift name for NOS in condition by gopinath on 31Jul14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForOnDuty]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(15),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)
SET @query = ''SELECT (tsa.Day''+ @date + ''Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''''''+ @Employeecode +'''''' ''  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)
IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
  SET @query = ''SELECT (psa.Day''+ @date + ''Shift)  from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + '' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''''' + @Employeecode +'''''' ''  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
END
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END	
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, ''00:00 AM'' AS Shift_SecondHalf_StartTime, ''00:00 AM'' AS Shift_FirstHalf_EndTime, ''00:00 AM'' AS Shift_EndTime
			,''00:00 AM'' Shift_StartTime
		END
	DROP Table #Temp	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForFieldDuty_Employee] ''Emp2,Emp5,Emp8'',''2013'',''5'',''14''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty_Employee]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(max),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	-- Check Shift in Temporary Shift Allocation
	SET @query = ''SELECT (tsa.Day''+ @date + ''Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp 
				where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
				tsa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo in( ''''''+ @Employeecode +'''''' )''  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)
	Select * from #Temp
	DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = ''SELECT (psa.Day''+ @date + ''Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa,
			TA_Tbl_Employee emp where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + '' and   psa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo in( '''''' + @Employeecode +'''''' )''  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName =''No Shift'' AND IsDeleted = 0)
				END
		END	
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, ''00:00 AM'' AS Shift_SecondHalf_StartTime, ''00:00 AM'' AS Shift_FirstHalf_EndTime, ''00:00 AM'' AS Shift_EndTime
			,''00:00 AM'' Shift_StartTime
		END
	DROP Table #Temp	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForFieldDuty]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForFieldDuty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_TA_SelectShiftIdForFieldDuty] ''emp2'',''2013'',''5'',''3''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForFieldDuty]
	-- Add the parameters for the stored procedure here
	@Employeecode VARCHAR(15),
	@year VARCHAR(5),
	@month VARCHAR(5),
	@date VARCHAR(5)
AS
BEGIN
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	CREATE Table #Temp (ShiftId INT)
	-- Check Shift in Temporary Shift Allocation
	SET @query = ''SELECT (tsa.Day''+ @date + ''Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp 
				where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   
				tsa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo = ''''''+ @Employeecode +'''''' ''  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)
	DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = ''SELECT (psa.Day''+ @date + ''Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa,
			TA_Tbl_Employee emp where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + '' and   psa.EmployeeId = emp.Employee_Id and emp.SwipeCardNo = '''''' + @Employeecode +'''''' ''  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName =''No Shift'' AND IsDeleted = 0)
				END
		END	
	IF(@ShiftId > 0)
		BEGIN
			SELECT ISNULL(@ShiftId,0)ShiftId,Shift_SecondHalf_StartTime,Shift_FirstHalf_EndTime,Shift_EndTime,Shift_StartTime FROM TA_Tbl_Shift
			WHERE Shift_Id = @ShiftId
		END
	ELSE IF (@ShiftId = -1)
		BEGIN
			SELECT @ShiftId as ShiftId, ''00:00 AM'' AS Shift_SecondHalf_StartTime, ''00:00 AM'' AS Shift_FirstHalf_EndTime, ''00:00 AM'' AS Shift_EndTime
			,''00:00 AM'' Shift_StartTime
		END
	DROP Table #Temp	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNameById]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftNameById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftNameById]
@ShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@ShiftId<>0)
	BEGIN
	  select *,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName1 From TA_Tbl_Shift WHERE Isdeleted = 0 and Shift_Id=@ShiftId
	END
	else
	BEGIN
	  select *,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName1 From TA_Tbl_Shift WHERE Isdeleted = 0 
	END
-- 	select Shift_Id,Shift_Name From TA_Tbl_Shift WHERE Isdeleted = 0 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftIdForService]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftIdForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	Getting Employee shift id for particulare date
-- [PROC_TA_SELECTSHIFTIDFORSERVICE] ''2'',''2014/12/04'',''1''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftIdForService]
	@EMPLOYEEAUTOID VARCHAR(50),
	@DATE datetime,
	@COMPANYID INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @QUERY VARCHAR(2000)   
	DECLARE @SHIFTID INT
	SET @SHIFTID=0
	DECLARE @ISDELETED INT
	CREATE TABLE #TEMP (SHIFTID INT)	
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)
	SET @YEAR=DATEPART(YEAR,@DATE)
	SET @MONTH=DATEPART(MONTH,@DATE)	
	-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	SET @QUERY = ''	SELECT (TSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
					WHERE TSA.[YEAR]= '' + @YEAR + ''  AND  TSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = ''''''+ @EMPLOYEEAUTOID +'''''' ''	
	INSERT INTO #TEMP EXEC(@QUERY)
	SELECT @SHIFTID =ISNULL(SHIFTID,0) FROM #TEMP	
	DELETE FROM #TEMP
	-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	IF(@SHIFTID = 0)
		BEGIN
			SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SELECT @SHIFTID =ISNULL(SHIFTID,0) FROM #TEMP	
			DELETE FROM #TEMP
		END
	IF(@SHIFTID != 0)
		BEGIN			
			IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
				BEGIN
					SET @SHIFTID = ISNULL(@SHIFTID,0)			
				END
		END		
	-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	IF(@SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID = ISNULL(SHIFT_ID,0) FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID
			IF(@SHIFTID = 0)
				BEGIN					
					SELECT @SHIFTID =ISNULL(SHIFT_ID,0) FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0					
				END
		END
	IF(@SHIFTID > 0)
		BEGIN
			SELECT ISNULL(@SHIFTID,0)AS SHIFTID FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
		END
	ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID AS SHIFTID
		END		
	DROP TABLE #TEMP
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftByCompany]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftByCompany]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE   PROCEDURE [dbo].[Proc_TA_SelectShiftByCompany]  
	@LevelID int
AS
Begin
	DECLARE @timeformat   varchar(10)
	SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat=''hh:mm tt'')
		begin
			SELECT Shift_Id,Shift_Name,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName 
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=0
		end
	else
		begin
			SELECT Shift_Id,Shift_Name,Shift_ShortName + '' ( '' + convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName 
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' + convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName
				from TA_Tbl_Shift
			where 
				isdeleted=0 and 
				level_id=0
		end
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftForShiftPattern]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftForShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectShiftForShiftPattern  
Description : select shift pattern for respective company
Tables Included : TA_Tbl_ShiftPattern
Created By : Christopher.S   
Created On : 15-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftForShiftPattern] 
	-- Add the parameters for the stored procedure here
	@companyId int
AS
DECLARE @timeformat   varchar(10)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@timeformat=''hh:mm tt'')
		begin
			-- Insert statements for procedure here
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName  FROM TA_Tbl_Shift WHERE Isdeleted=0 AND Level_Id = @companyId
		end
	else
		begin
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' + convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName  FROM TA_Tbl_Shift WHERE Isdeleted=0 AND Level_Id = @companyId
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShiftByShortName]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSearchShiftByShortName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_SelectSearchShiftByShortName ''s'',''0''
CREATE PROCEDURE [dbo].[Proc_TA_SelectSearchShiftByShortName]  
@ShortName as varchar(25),
@CompanyID as int
AS
DECLARE @timeformat   varchar(10)
declare @Query as varchar(7000)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
		if(@timeformat=''hh:mm tt'')
			BEGIN
				set @Query = ''SELECT LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id ''					
				set @Query= @Query +'' WHERE upper(S.shift_ShortName) like '''''' + upper(@ShortName) + ''%'''' ''
				if (@CompanyID!=0 and @CompanyID!='''')
				Begin
						set @Query= @Query +'' And S.Level_Id = '' + cast(@CompanyID as varchar(100))
				End
				set @Query= @Query +'' Union ''
				set @Query = @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' WHERE S.Level_Id=0''
			END
		else
			BEGIN
				set @Query = ''SELECT  LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend, convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' TO '''' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ''    
				set @Query= @Query +'' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id ''							
				set @Query= @Query +'' WHERE upper(S.shift_ShortName) like '''''' + upper(@ShortName) + ''%'''' ''
				if (@CompanyID!=0 and @CompanyID!='''')
				Begin
						set @Query= @Query +'' And S.Level_Id = '' + cast(@CompanyID as varchar(100))
				End
				set @Query= @Query +'' Union ''
				set @Query = @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' WHERE S.Level_Id=0''
			END
	exec(@Query)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSearchShift]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSearchShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    PROCEDURE [dbo].[Proc_TA_SelectSearchShift]  
@ShiftID as int,
@iCompanyID as int
AS
DECLARE @timeformat   varchar(10)
declare @Query as varchar(7000)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
		if(@timeformat=''hh:mm tt'')
			BEGIN
				set @Query = ''SELECT LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id ''					
				set @Query= @Query +'' WHERE  1=1 ''
				if not (@ShiftID=''0'')
				begin
					set @Query= @Query +'' and S.Shift_Id = ''+ cast(@ShiftID as varchar(100))
				end
				if not (@iCompanyID=''0'')
				begin
					set @Query= @Query +'' and S.Level_Id = ''+ cast(@iCompanyID as varchar(100))
				end
				set @Query= @Query +'' Union ''
				set @Query = @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' WHERE S.Level_Id=0''
			END
		else
			BEGIN
				set @Query = ''SELECT  LD.name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend, convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' TO '''' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S ''    
				set @Query= @Query +'' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id ''							
				set @Query= @Query +'' WHERE  1=1 ''
				if not (@ShiftID=''0'')
				begin
					set @Query= @Query +'' and S.Shift_Id = ''+ cast(@ShiftID as varchar(100))
				end
				if not (@iCompanyID=''0'')
				begin
					set @Query= @Query +'' and S.Level_Id = ''+ cast(@iCompanyID as varchar(100))
				end
				set @Query= @Query +'' Union ''
				set @Query = @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_Name, S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime,S.Isdeleted FROM TA_Tbl_Shift S '' 
				set @Query= @Query +'' WHERE S.Level_Id=0''
			END
	exec(@Query)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo_New]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectReaderBasicInfo_New]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.Karthikeyan.
-- Create date: 04-03-2016
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in Terminal sync
-- PROC_TA_SelectReaderBasicInfo_New
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
Create PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo_New]
	-- Add the parameters for the stored procedure here	
	--PROC_TA_SelectReaderBasicInfo_New ''Provider=SQLOLEDB.1;Data Source=angler67\SQL20141;Initial Catalog=biostar;User Id=sa;pwd=angler123;''
	@ConnString as nvarchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
			DECLARE @sql VARCHAR(2000)
			DECLARE @UpdateToTimecheckFlag varchar(8000)
			DECLARE @sql2 varchar(8000)
			DECLARE @sql1 varchar(8000)
			DECLARE @ConnectionString NVARCHAR(2000)
			DECLARE @ServerName NVARCHAR(2000)
			DECLARE @DatabaseName NVARCHAR(2000)
			--Added by Manjula.P on 06-Feb-2014
			DECLARE @UserId NVARCHAR(100)
			DECLARE @Password NVARCHAR(100)
					SET @ConnectionString=@ConnString
					--Create table To splitup the Server and database name
					--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
					IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
						BEGIN
							INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
							SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=2
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=3)
							UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=4)
							--Added by Manjula.P on 06-Feb-2014
							--select * from Ta_tbl_DeviceServerDetails			
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=5)				
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							--select * from  Ta_tbl_DeviceServerDetails
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						END			
					SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
					if not exists(select * from sys.servers where name = N''''+@ServerName+'''')
					begin
						EXEC sp_addlinkedserver @server=@ServerName
					end
					declare @suser_sname nvarchar(256) 
					set @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N''False'',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------
					CREATE TABLE #test(exist int,TableName varchar(500))
					Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
					--Bio admin we dont tested. if we wants to test the bioadmin, just uncomment the below line and comment the next line and check the same
					--03-02-2014 06.00 PM
					--set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''tb_device'''',''''TB_READER'''')''
					set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''TB_READER'''')''
					Insert into #test exec(@sql)			
					if exists(select COUNT(*) from #test where TableName =''TB_READER'')
						begin
							--Declare @sql4 varchar(8000)
							--set @sql4=''select name from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.sys.columns where name=''''ToTimecheck'''' and object_id=(select object_id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.sys.tables where name=''''TB_READER'''')''
							--insert into #DeviceDetailsMovedToTimecheck exec(@sql4)
							--if not exists(select name from #DeviceDetailsMovedToTimecheck where name=''ToTimecheck'')
							--	begin
							--		declare @AlterQuery1 varchar(100)
							--		set @AlterQuery1=''Alter table [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER add ToTimecheck bit''						
							--		Exec(@AlterQuery1)
							--		Declare @sql5 varchar(8000)
							--		set @sql5=''select nReaderIdn,sName,sName,'''''''',getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where ToTimecheck is null''
							--		--insert into TA_Tbl_Terminal 
							--		exec(@sql5)
							--		set @UpdateToTimecheckFlag=''Update [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null''
							--		exec(@UpdateToTimecheckFlag)
							--		--update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
							--		--where TerminalDatatype_ID is null							
							--	end
							--else
							--	begin							
									--Declare @sql6 varchar(8000)
									--set @sql6=''select  nReaderIdn,sName,sName,'''''''',getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where ToTimecheck is null''
									--insert into TA_Tbl_Terminal 
									--exec(@sql6)
									set @sql2=''select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0),getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where 
									convert(varchar(20),nReaderIdn) not in(''
									set @sql2=@sql2+ '' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )''
									insert into TA_Tbl_Terminal exec(@sql2)	
									--set @UpdateToTimecheckFlag=''Update [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null''
									--exec(@UpdateToTimecheckFlag)
									update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0 and FileType=''RDBMS'' and BrandId=3)
									where TerminalDatatype_ID is null	
									--select * from TA_Tbl_Terminal 
								--end					
						end
					delete from Ta_tbl_DeviceServerDetails
END
--------------------------------------------------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectReaderBasicInfo]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectReaderBasicInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ==========================================================================================
-- Author:		R.Manikandan.
-- Create date: 20-11-2013
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in windows service
-- PROC_TA_SelectReaderBasicInfo
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
CREATE PROCEDURE [dbo].[PROC_TA_SelectReaderBasicInfo]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
		BEGIN
			DECLARE @sql VARCHAR(2000)
			DECLARE @UpdateToTimecheckFlag varchar(8000)
			DECLARE @sql2 varchar(8000)
			DECLARE @sql1 varchar(8000)
			DECLARE @ConnectionString NVARCHAR(2000)
			DECLARE @ServerName NVARCHAR(2000)
			DECLARE @DatabaseName NVARCHAR(2000)
			--Added by Manjula.P on 06-Feb-2014
			DECLARE @UserId NVARCHAR(100)
			DECLARE @Password NVARCHAR(100)
			IF((SELECT top 1 FileType FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=''RDBMS'' and (SELECT top 1 BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=3)
				BEGIN
					SET @ConnectionString=(SELECT top 1 ConnectionString FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0 and FileType=''RDBMS'' and BrandId=3)
					--Create table To splitup the Server and database name
					--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
					IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
						BEGIN
							INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
							SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=2
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=3)
							UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=4)
							--Added by Manjula.P on 06-Feb-2014
							--select * from Ta_tbl_DeviceServerDetails			
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=5)				
							UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
							--select * from  Ta_tbl_DeviceServerDetails
							UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						END			
					SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
					if not exists(select * from sys.servers where name = N''''+@ServerName+'''')
					begin
						EXEC sp_addlinkedserver @server=@ServerName
					end
					declare @suser_sname nvarchar(256) 
					set @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N''False'',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------
					CREATE TABLE #test(exist int,TableName varchar(500))
					Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
					--Bio admin we dont tested. if we wants to test the bioadmin, just uncomment the below line and comment the next line and check the same
					--03-02-2014 06.00 PM
					--set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''tb_device'''',''''TB_READER'''')''
					set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''TB_READER'''')''
					Insert into #test exec(@sql)			
					if exists(select COUNT(*) from #test where TableName =''TB_READER'')
						begin
							--Declare @sql4 varchar(8000)
							--set @sql4=''select name from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.sys.columns where name=''''ToTimecheck'''' and object_id=(select object_id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.sys.tables where name=''''TB_READER'''')''
							--insert into #DeviceDetailsMovedToTimecheck exec(@sql4)
							--if not exists(select name from #DeviceDetailsMovedToTimecheck where name=''ToTimecheck'')
							--	begin
							--		declare @AlterQuery1 varchar(100)
							--		set @AlterQuery1=''Alter table [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER add ToTimecheck bit''						
							--		Exec(@AlterQuery1)
							--		Declare @sql5 varchar(8000)
							--		set @sql5=''select nReaderIdn,sName,sName,'''''''',getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where ToTimecheck is null''
							--		--insert into TA_Tbl_Terminal 
							--		exec(@sql5)
							--		set @UpdateToTimecheckFlag=''Update [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null''
							--		exec(@UpdateToTimecheckFlag)
							--		--update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
							--		--where TerminalDatatype_ID is null							
							--	end
							--else
							--	begin							
									--Declare @sql6 varchar(8000)
									--set @sql6=''select  nReaderIdn,sName,sName,'''''''',getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where ToTimecheck is null''
									--insert into TA_Tbl_Terminal 
									--exec(@sql6)
									set @sql2=''select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0),getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where 
									convert(varchar(20),nReaderIdn) not in(''
									set @sql2=@sql2+ '' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )''
									insert into TA_Tbl_Terminal exec(@sql2)	
									--set @UpdateToTimecheckFlag=''Update [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER set ToTimecheck=1 where ToTimecheck is null''
									--exec(@UpdateToTimecheckFlag)
									update TA_Tbl_Terminal set Terminal_ReaderID=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0 and FileType=''RDBMS'' and BrandId=3)
									where TerminalDatatype_ID is null	
									--select * from TA_Tbl_Terminal 
								--end					
						end
					delete from Ta_tbl_DeviceServerDetails
				END
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRawDataFormats]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectRawDataFormats]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectRawDataFormats]
AS
BEGIN 
	SELECT TerminalDatatype_ID,Raw_Data_Format FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 7-12-2011
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthorityforID]
	-- Add the parameters for the stored procedure here
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=@EmployeeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReportingToSanctionAuthority]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReportingToSanctionAuthority]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 7-12-2011
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectReportingToSanctionAuthority]
	-- Add the parameters for the stored procedure here
	@LeaveApplication_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=(
	select Employee_id from ta_tbl_leaveapplication where leaveapplication_id=@LeaveApplication_ID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectReligion]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectReligion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 7-10-2011
-- Description:	SELECTING RELIGIONS
-- =============================================
create PROCEDURE [dbo].[Proc_TA_SelectReligion]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Religion where isDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollFieldNames]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollFieldNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- [Proc_TA_SelectPayrollFieldNames] ''Summarized Data'', 3
CREATE PROCEDURE [dbo].[Proc_TA_SelectPayrollFieldNames]
(
@DataType varchar(50),
@CompanyID int
)
AS
if(@DataType = ''SummarizedData'')
	BEGIN
		if((select DemoType from TA_Tbl_Demo)=''Express'')
			begin
				SELECT column_name+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType=''All'' and TA_ExportData_FieldData.DataType=''SummarizedData'' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = ''TA_TBL_PayrollProcessDetails'' AND column_name <> ''PayrollProcess_Id''
				AND column_name <> ''MonthClosure_Id'' AND column_name <> ''User_Id'' AND  column_name <> ''TimeStamp''
				--AND column_name <> ''MonthClosure_Id'' AND column_name <> ''User_Id''
				AND column_name <> ''Emp_Id'' AND column_name <> ''HrsWork'' AND column_name <> ''HrsOt'' AND column_name <> ''NormOt'' AND column_name <> ''WorkHrs'' AND column_name <> ''HolOT'' AND column_name <> ''OffOT''
				union all
				select '''',''Hours_Worked'','''',''''
				union all
				select '''',''Defined_WorkHours'','''','''' 
				union all
				select '''',''LevelCode'','''',''''	
			end
		else
			begin
				SELECT column_name+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType=''All'' and TA_ExportData_FieldData.DataType=''SummarizedData'' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = ''TA_TBL_PayrollProcessDetails'' AND column_name <> ''PayrollProcess_Id''
				AND column_name <> ''MonthClosure_Id'' AND column_name <> ''User_Id'' AND  column_name <> ''TimeStamp''
				--AND column_name <> ''MonthClosure_Id'' AND column_name <> ''User_Id''
				AND column_name <> ''Emp_Id'' AND column_name <> ''HrsWork'' AND column_name <> ''HrsOt'' AND column_name <> ''NormOt'' AND column_name <> ''WorkHrs'' AND column_name <> ''HolOT'' AND column_name <> ''OffOT''
				union all
				select '''',''Hours_Worked'','''','''' 
				union all
				select '''',''Total_OT'','''','''' 
				union all
				select '''',''WeekDay_OT'','''','''' 
				union all
				select '''',''WeekOff_OT'','''','''' 
				union all
				select '''',''Holiday_OT'','''','''' 
				union all
				select '''',''Defined_WorkHours'','''','''' 
				union all
				select '''',''LevelCode'','''',''''	
			end		
	END
else
	BEGIN
		if((select DemoType from TA_Tbl_Demo)=''Express'')
			begin
				SELECT column_name+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType=''All'' and TA_ExportData_FieldData.DataType=''DailyData'' and TA_ExportData_FieldData.CompanyID=@CompanyID
				WHERE Table_Name = ''TA_Tbl_ProcessedData'' AND column_name <> ''Process_Rec_ID'' AND column_name <> ''LeaveCode''
				AND column_name <> ''Employee_Code_Id'' AND column_name <> ''Shift_Id'' AND  column_name <> ''Status''
				AND column_name <> ''Attendance'' AND column_name <> ''EarlyOutMins'' AND column_name <> ''ExtraMins'' 
				AND column_name <> ''OtMins'' AND column_name <> ''TotalDays'' AND column_name <> ''OvertimeStatus''
				AND column_name <> ''LateEntryReason'' AND column_name <> ''EarlyOutReason'' AND column_name <> ''ProcessFlag''
				AND column_name <> ''LateExit'' AND column_name <> ''EarlyEntry''
				AND column_name <> ''LateInMins'' AND column_name <> ''HrsWork'' AND column_name <> ''HrsOt'' AND column_name <> ''NormOt'' AND column_name <> ''WorkHrs'' AND column_name <> ''HolOT'' AND column_name <> ''OffOT'' 
				union all
				select '''',''Hours_Worked'','''','''' 				 
				union all
				select '''',''Defined_WorkHours'','''','''' 
				union all
				select '''',''Employee_Id'','''','''' 
				union all
				select '''',''EmployeeName'','''',''''
				union all
				select '''',''CardNo'','''','''' 
				union all
				select '''',''ShiftCode'','''','''' 
				union all
				select '''',''ShiftName'','''','''' 
				union all
				select '''',''DateIn'','''',''''
				union all
				select '''',''DateOut'','''',''''
				union all
				select '''',''InReaderId'','''','''' 
				union all
				select '''',''OutReaderId'','''','''' 
				union all
				select '''',''InReaderName'','''','''' 
				union all
				select '''',''OutReaderName'','''','''' 
				union all
				select '''',''Remarks'','''','''' 
				union all
				select '''',''LevelCode'','''','''' 
				union all
				select '''',''LevelName'','''',''''				
				--union all
				--select '''',''AttendanceCode'','''','''' 
			end
		else
			begin
				SELECT column_name+'' (''+isnull(TA_ExportData_FieldData.UserDefinedFieldName,'' '')+'')'' as column_name,column_name as FieldName,TA_ExportData_FieldData.UserDefinedFieldName,TA_ExportData_FieldData.FieldType FROM INFORMATION_SCHEMA.COLUMNS
				left join TA_ExportData_FieldData on  TA_ExportData_FieldData.FieldName=column_name and TA_ExportData_FieldData.OptionType=''All'' and TA_ExportData_FieldData.DataType=''DailyData'' and TA_ExportData_FieldData.CompanyID=2
				WHERE Table_Name = ''TA_Tbl_ProcessedData'' AND column_name <> ''Process_Rec_ID'' AND column_name <> ''LeaveCode''
				AND column_name <> ''Employee_Code_Id'' AND column_name <> ''Shift_Id'' AND  column_name <> ''Status''
				AND column_name <> ''Attendance'' AND column_name <> ''EarlyOutMins'' AND column_name <> ''ExtraMins'' 
				AND column_name <> ''OtMins'' AND column_name <> ''TotalDays'' AND column_name <> ''OvertimeStatus''
				AND column_name <> ''LateEntryReason'' AND column_name <> ''EarlyOutReason'' AND column_name <> ''ProcessFlag''
				AND column_name <> ''LateExit'' AND column_name <> ''EarlyEntry''
				AND column_name <> ''LateInMins'' AND column_name <> ''HrsWork'' AND column_name <> ''HrsOt'' AND column_name <> ''NormOt'' AND column_name <> ''WorkHrs'' AND column_name <> ''HolOT'' AND column_name <> ''OffOT'' 
				union all
				select '''',''Hours_Worked'','''','''' 
				union all
				select '''',''Total_OT'','''','''' 
				union all
				select '''',''WeekDay_OT'','''',''''
				union all
				select '''',''WeekOff_OT'','''','''' 
				union all
				select '''',''Holiday_OT'','''',''''  
				union all
				select '''',''Defined_WorkHours'','''','''' 
				union all
				select '''',''Employee_Id'','''','''' 
				union all
				select '''',''EmployeeName'','''',''''
				union all
				select '''',''CardNo'','''','''' 
				union all
				select '''',''ShiftCode'','''','''' 
				union all
				select '''',''ShiftName'','''','''' 
				union all
				select '''',''DateIn'','''',''''
				union all
				select '''',''DateOut'','''',''''
				union all
				select '''',''InReaderId'','''','''' 
				union all
				select '''',''OutReaderId'','''','''' 
				union all
				select '''',''InReaderName'','''','''' 
				union all
				select '''',''OutReaderName'','''','''' 
				union all
				select '''',''Remarks'','''','''' 
				union all
				select '''',''LevelCode'','''','''' 
				union all
				select '''',''LevelName'','''',''''
				union all
				select '''',''OverTimeType'','''','''' 
				--union all
				--select '''',''AttendanceCode'','''','''' 
			end
	END
/*
declare @TableID as int
set @TableID =(select id from sysobjects where name=''TA_TBL_PayrollProcessDetails'')
exec Proc_TA_SelectAllColumnNames @TableID
*/
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectParentLevel]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectParentLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_selectParentLevel]
(
	@levelId int
)
AS
BEGIN
	select * from ta_tbl_level where levelId=@levelId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <27-Mar-2019 07:29 PM>
-- Description:	<Get the previously availed permission details for printout>
-- Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman 62
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectPermissionDetailsUsingIDForPrint_Eastman]
@PermissionID bigint
AS
BEGIN
	SET NOCOUNT ON;
	SELECT AutoID, Cur_Perm_ID as Permission_Id, Prev_Perm_ID, Timestamp, Prev_Perm_date as Permission_Date, Prev_Perm_ShiftTime as Permission_FromTime, 
	Prev_Perm_InTime as No_Of_Hours , Prev_Perm_LateHours as Permission_ToTime, Prev_Perm_Reason as Permission_Reason, Prev_Perm_ReceivedDate as Permission_AppliedDate 
	from ta_tbl_PrevPermissionDetails_EastMan where Cur_Perm_ID=@PermissionID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPermissionDetailsForService]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectPermissionDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectPermissionDetailsForService]
	-- Add the parameters for the stored procedure here
	@inEmployee_Code_Id varchar(50),
	@dtmDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT P.Permission_FromTime,P.Permission_ToTime,P.No_Of_Hours FROM TA_Tbl_Permission P
	inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id
	WHERE  E.SwipeCardNo= @inEmployee_Code_Id AND P.Permission_Date = @dtmDate AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectPermissionDetailsByPermissionId
Description		:	Get Permisssion Details of Employees Based on Permission_ID
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	20-Jul-07
Modified By		:
Modified On		:
*/
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetailsByPermissionId]
	@Permission_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select * from TA_Tbl_Permission p
	inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
	inner join TA_Tbl_EmployeeLevel EL on E.Employee_Id=EL.EmployeeId
	where Permission_Id=@Permission_Id and P.IsDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectProcessedDatasByEmployeeId]
(
   @SwipeCardNo nVarchar(20),
   @Date Varchar(15)
)
AS
SELECT Employee_Code_Id,[Date],InTime,OutTime FROM TA_Tbl_ProcessedData where Employee_Code_Id = @SwipeCardNo and [Date] = @Date and Attendance = ''Present''
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectPreviousLevelCount]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectPreviousLevelCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectPreviousLevelCount]
	-- Add the parameters for the stored procedure here
	@levelid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select top 1 levelID as count from TA_Tbl_Level where levelID<@levelid and isDeleted=0 order by levelID desc
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextYearSetting]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectNextYearSetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectNextYearSetting]
AS
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + '' - '' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting,convert(nvarchar(20),FromDate,101) as YearSettingFromDate,convert(nvarchar(20),ToDate,101) as YearSettingToDate,* 
from Ta_Tbl_Yearsetting 
where 
YearSettings_Id=(select top 1 YearSettings_Id from Ta_Tbl_Yearsetting where YearSettings_Id > (select YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1) order by YearSettings_Id asc)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectNextShiftId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectNextShiftId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_SelectNextShiftId]
(
	@EmployeeCodeId as varchar(15),
	@ShiftDate as datetime,
	@ShiftInDateTime as datetime,
	@WeeklyOffStartHours as varchar(5),
	@dtNextShiftStartTime as datetime output
)
--RETURNS varchar(20)
AS
--BEGIN
--Declare @dtNextShiftStartTime as varchar(20)
declare @WeeklyOffMinutes as int
set @WeeklyOffMinutes=(select DATePART(hh, cast(@WeeklyOffStartHours as Datetime))*60+DATePART(n, cast(@WeeklyOffStartHours as Datetime)))
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)
SET @query = ''SELECT (tsa.Day''+ cast(datepart(dd,@ShiftDate+1) as varchar(2)) + ''Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= '' + cast(datepart(yyyy,@ShiftDate+1) as varchar(4)) + ''  and  tsa.[Month]= '' + cast(datepart(mm,@ShiftDate+1) as varchar(2)) + '' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''''''+ @EmployeeCodeId +'''''' ''  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)
IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
SET @query = ''SELECT (tsa.Day''+ cast(datepart(dd,@ShiftDate+1) as varchar(2)) + ''Shift)  from TA_Tbl_PermanentShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= '' + cast(datepart(yyyy,@ShiftDate+1) as varchar(4)) + ''  and  tsa.[Month]= '' + cast(datepart(mm,@ShiftDate+1) as varchar(2)) + '' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''''''+ @EmployeeCodeId +'''''' ''  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
  SELECT ISNULL(@ShiftId,0)
END
IF(@ShiftId > 0)
BEGIN
    declare @shiftStartTime as varchar(8)
    set @shiftStartTime=(select Shift_StartTime from TA_tbl_Shift  where Shift_Id=@ShiftId)
 set @dtNextShiftStartTime=(@ShiftDate+1)+ @shiftStartTime
END
ELSE IF(@ShiftId = -1)
BEGIN
set @dtNextShiftStartTime=DateAdd(minute,@WeeklyOffMinutes,@ShiftInDateTime)
END
--ELSE IF(@ShiftId = 0)
--BEGIN
--END
set @dtNextShiftStartTime=''2/01/2010''
DROP TABLE #Temp
DROP TABLE #Temp1
--return @dtNextShiftStartTime
--END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthClosureDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  <Author,,Name>  
-- ALTER  date: <Create Date,,>  select * from ta_tbl_monthclosure
-- Description: <Description,,>  select * from ta_tbl_payrollprocessdetails
-- Proc_TA_SelectMonthClosureDetails 2,1,''02/01/2016'',''02/29/2016'',''02/29/2016''  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthClosureDetails]  
-- Add the parameters for the stored procedure here  
@monthClosureId int,  
@levelId int,   
@startDate nvarchar(25),  
@endDate nvarchar(25),  
@closedDate nvarchar(25)  
AS  
declare @sqlQuery as nvarchar(4000)      
set @sqlQuery=''''      
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from  
	-- interfering with SELECT statements.  
	SET NOCOUNT ON;  
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ,[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ,[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ,[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	-- Insert statements for procedure here  
	set @sqlQuery = @sqlQuery + ''select e.Employee_Code_Id as Employee_Id,
																			isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as EmployeeName,''  
	set @sqlQuery = @sqlQuery + ''				ppd.HrsWork,
																			ppd.NormOT,
																			ppd.OffOT,
																			ppd.HolOT,
																			ppd.LateIn,
																			ppd.EarlyOut,''
	set @sqlQuery = @sqlQuery + ''				mc.MonthClosure_Id,
																			isnull(ppd.LeaveDays,0) as LeaveDays,
																			isnull(ppd.PresentDays,0) as PresentDays,
																			isnull(ppd.AbsentDays,0) as AbsentDays,
																			isnull(ppd.Holidays,0) as Holidays,
																			isnull(ppd.LOPDays,0) as LOPDays,
																			isnull(ppd.TotalPermissionHours,''''00:00'''') TotalPermissionHours,
																			isnull(ppd.WeekOffDays,0) as WeekOffDays,
																			isnull(ppd.HrsLess,''''00:00'''') HrsLess,
																			isnull(ppd.HrsExtra,''''00:00'''') HrsExtra,
																			SPEC_NormOT1=isnull(SPEC_NormOT1,''''00:00''''),
            SPEC_NormOT2=isnull(SPEC_NormOT2,''''00:00''''),
            SPEC_OffOT1=isnull(SPEC_OffOT1,''''00:00''''),SPEC_OffOT2=isnull(SPEC_OffOT2,''''00:00''''),
            SPEC_HOLOT1=isnull(SPEC_HOLOT1,''''00:00''''),SPEC_HOLOT2=isnull(SPEC_HOLOT2,''''00:00'''')
																			from TA_Tbl_MonthClosure mc''   
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_PayrollProcessDetails ppd on ppd.MonthClosure_Id=mc.MonthClosure_Id''      
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_Employee e on e.SwipeCardNo=ppd.Employee_Id''    
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= e.Employee_Id ''  
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id ''   
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= e.Employee_Id ''  
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId ''  
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=Lev.EffectiveDate and #EmpLevel.employeeid=Lev.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and mc.IsDeleted=0 and mc.MonthClosure_StartDate=CONVERT(DATETIME, '''''' +cast( @startDate as nvarchar(50))+ '''''', 102) and mc.MonthClosure_EndDate=CONVERT(DATETIME, '''''' +cast( @endDate as nvarchar(50))+ '''''', 102) and mc.MonthClosure_ClosingDate=CONVERT(DATETIME, '''''' +cast( @closedDate as nvarchar(50))+ '''''', 102) And mc.MonthClosure_Id = ''+cast(@monthClosureId as nvarchar(4))+'' And mc.OrgLevel_Id = ''+cast(@levelId as nvarchar(10))+''''  
	set @sqlQuery = @sqlQuery + '' order by e.Employee_Code_Id''         
	exec(@sqlQuery)  
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLookupData]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLookupData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLookupData]
	@Category CHAR,
	@ID INT,
	@userGroupName nvarchar(25)
AS
BEGIN
	SET NOCOUNT ON;
IF (@Category=''C'')
	IF(@userGroupName=''SuperAdmin'')
		BEGIN
  			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1  
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.Isdeleted=0
		END	
ELSE IF (@Category=''D'')
	IF(@userGroupName=''SuperAdmin'')
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.ID=@ID
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS country,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted FROM TA_Tbl_Lookup L WHERE L.Type=1 AND L.ID=@ID AND L.Isdeleted=0
		END
ELSE IF (@Category=''S'')
	IF(@userGroupName=''SuperAdmin'')
		BEGIN
			SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS country,0 as flag into #tempState FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2
			Update #tempState set flag=1 from #tempState TC inner join ta_tbl_Employee E on TC.ID=E.State --where E.Isdeleted =0
			Update #tempState set flag=1 from #tempState TC inner join ta_tbl_lookup L on TC.ID=L.Parent 
			Select * from #tempState  
		END
	ELSE
		BEGIN
			SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS country,0 as flag into #tempState1 FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2 AND L.Isdeleted=0
			Update #tempState1 set flag=1 from #tempState1 TC inner join ta_tbl_Employee E on TC.ID=E.State --where E.Isdeleted =0			
			Update #tempState1 set flag=1 from #tempState1 TC inner join ta_tbl_lookup L on TC.ID=L.Parent 
			Select * from #tempState1 
		END	
ELSE IF (@Category=''T'')
	IF(@userGroupName=''SuperAdmin'')
		SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		WHERE L.Type=2 AND L.ID=@ID 
	ELSE
		SELECT L.ID,L.Type,L.Title AS state,L.Parent AS countryID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		WHERE L.Type=2 AND L.ID=@ID AND L.Isdeleted=0
ELSE IF (@Category=''N'')
	IF(@userGroupName=''SuperAdmin'')
		begin
			SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country,0 as flag 
			into #TempCity FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3		
			Update #TempCity set flag=1 from #TempCity TC inner join ta_tbl_Employee E on TC.ID=E.Native_Place --where E.Isdeleted =0
			Select * from #TempCity 
		End
	ELSE
		Begin		
			SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country,0 as flag 
			into #TempCity1 FROM TA_Tbl_Lookup L INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3 AND L.Isdeleted=0
			Update #TempCity1 set flag=1 from #TempCity1 TC inner join ta_tbl_Employee E on TC.ID=E.Native_Place --where E.Isdeleted =0
			Select * from #TempCity1 
		End
ELSE IF (@Category=''O'')
	IF(@userGroupName=''SuperAdmin'')
		SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent
		WHERE L.Type=3 AND L.ID=@ID
	ELSE
		SELECT L.ID,L.Type,L.Title AS city,L.Parent AS stateID,case when L.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,LK.Title AS state,LK.Parent AS countryID,LK1.Title AS country FROM TA_Tbl_Lookup L
		INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
		INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent
		WHERE L.Type=3 AND L.ID=@ID AND L.Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogo]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLogo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj.P>
-- Create date: <Create Date,,26-November-07>
-- Description:	<Description,,Select CustomerLogo from database>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLogo]
AS
BEGIN
	SELECT Cus_Image FROM Ta_Tbl_Branding
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginLock]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLoginLock]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectLoginLock]
(
	@UserName VARCHAR(1000)
)
AS
BEGIN
	SELECT * FROM TA_Tbl_LockLogin WHERE UserName=@UserName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLoginDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLoginDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLoginDetails] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
SELECT ConcurrentUserId, UserId, IpAddress, LoginTime, Status 
FROM TA_Tbl_ConcurrentUser where status = 1 ORDER BY LoginTime DESC
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLogDownloaded]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLogDownloaded]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		: Manjula.P
Created Date	: 21-May-2013
Descriptions	: For creating log downloaded details as per the given requirements by sathish sir 
*/
CREATE proc [dbo].[Proc_TA_SelectLogDownloaded]
as
begin
select LoggedEmployeeId,CONVERT(varchar(20), LoggedDate,100) as LoggedDate from ta_tbl_LogDownloaded order by LoggedId desc
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectLocation]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectLocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_SelectLocation 
Description : select the Locatiom  
Tables Included : TA_Tbl_LevelDetails,TA_Tbl_Level  
Created By : velumani  
Created On : 29-Jun - 2019
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_selectLocation]  
AS   
BEGIN  
	select id as LocationId, Options, LocationName, Radius, Description, Address, City, State, Country, latitude, longitude, CreatedBy, CreatedDate, ModifiedBy, ModifiedDate from ta_tbl_landmarks
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXLeavePolicyID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXLeavePolicyID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Max Policy ID - select
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXLeavePolicyID] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(Policy_Id) AS MAX_PolicyID FROM TA_Tbl_LeavePolicy WHERE IsDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaximumNoOfHolidays]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaximumNoOfHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectMaximumNoOfHolidays
Description	:	Get Restricted Holidays from Holiday settings table
Tables Included	:	TA_Tbl_HolidaySettings
Created By	:	Prabakaran
Created On	:	13-Aug-07
Modified By	:
Modified On	:
*/
CREATE      procedure [dbo].[Proc_TA_SelectMaximumNoOfHolidays]
(
	@YearSettingID int
)
as
BEGIN
	if exists(select Yearly_Maxdays as RetrictedHolidays from TA_Tbl_HolidaySettings hs
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId
	where ys.YearSettings_Id=@YearSettingID)
	BEGIN
	    select Yearly_Maxdays as RetrictedHolidays from TA_Tbl_HolidaySettings hs
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId
		where ys.YearSettings_Id=@YearSettingID
	END
	ELSE
	BEGIN
		select 0 as RetrictedHolidays
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxHoliday]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxHoliday]
AS
BEGIN
	Select * from TA_Tbl_HolidaySettings
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxEmpID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxEmpID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxEmpID]
AS
BEGIN
	SELECT MAX(Employee_Id) AS MaxID FROM TA_Tbl_Employee
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLevelRights]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLevelRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Senthil
-- Create date: 23-Aug-08
-- Description:	Get the levels by groups
-- Proc_TA_SelectLevelRights
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLevelRights]
	@GroupID as int
AS
BEGIN	
	Select LevelId from TA_Tbl_LevelRights where groupId= @Groupid
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveType]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveType] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT LeaveType_Id, LeaveType From TA_Tbl_LeaveType Where IsDeleted =''0''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveAnalysisNotes]
	@fromDate as datetime
AS
BEGIN
SET NOCOUNT ON;
		select *,replace(convert(varchar(20),DateInserted,106),'' '',''-'') as DateIns from TA_Tbl_LeaveAnalysisNotes where
			isdeleted=0 and 
			month(DateInserted) = month(@fromDate) and
			year(DateInserted) = year(@fromDate)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectImportErrorData]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectImportErrorData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-Apr-2017
-- Description:	Get the import master error data.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectImportErrorData]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_ImportMasterError order by recordnumber
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectLeaveDetailsForService]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectLeaveDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	To check the employee applied the leave or not
--[Proc_Ta_SelectLeaveDetailsForService] 105,''2015-10-12''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectLeaveDetailsForService]
	@INEMPLOYEE_CODE_ID VARCHAR(50),
	@DTMDATE DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LA.Employee_Id,LA.LEAVETYPE_ID,LA.TYPE,LAE.LEAVE_FROMDATE,LAE.LEAVE_TODATE,LAE.LEAVE_SESSIONFROM,LAE.LEAVE_SESSIONTO,LA.Status FROM TA_TBL_LEAVEAPPLICATION LA
	inner join TA_Tbl_LeaveApplicationExists LAE on la.LeaveApplication_Id=LAE.LeaveApplicationId
	INNER JOIN TA_TBL_EMPLOYEE EMP ON LA.EMPLOYEE_ID = EMP.EMPLOYEE_ID 
	WHERE EMP.SWIPECARDNO =@INEMPLOYEE_CODE_ID AND LA.STATUS = ''APPROVED'' AND LA.ISDELETED = 0 and lae.IsDeleted=0 and EMP.Isdeleted=0
	AND LAE.LEAVE_FROMDATE = @DTMDATE AND LAE.LEAVE_TODATE =  @DTMDATE
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradesStandard]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGradesStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Prabakaran.P
-- ALTER  date: 12-Oct-09
-- Description:	Select All Grades
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectGradesStandard] 
-- Add the parameters for the stored procedure here
@Type CHAR,
@GradeID INT,
@userGroupName nvarchar(25)
AS	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
IF (@Type=''A'')
	IF(@userGroupName=''SuperAdmin'')
		BEGIN
			SELECT * FROM TA_Tbl_Grade where Grade_Name=''StandardGradeDefault'' and Grade_Level=1 order by Grade_Level
		END
	ELSE
		BEGIN
			SELECT * FROM TA_Tbl_Grade where Grade_Name=''StandardGradeDefault'' and Isdeleted=0 order by Grade_Level
		END
ELSE IF (@Type=''I'')
	IF(@userGroupName=''SuperAdmin'')
		BEGIN
			SELECT * FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID and Grade_Name=''StandardGradeDefault'' order by Grade_Level
		END
	ELSE	
		BEGIN
			SELECT * FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID and Grade_Name=''StandardGradeDefault'' order by Grade_Level
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Modified date: <23-11-2016 12.44>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEntranceDetailsForManualTimeEntry]
AS
BEGIN
	SET NOCOUNT ON;
    Select * from TA_Tbl_Entrance E where Entrance_Name=''TimecheckPhase'' and IsDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSatDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeSatDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-Apr-2013
-- Description:	Get the Saturday value 
-- =============================================
create PROCEDURE [dbo].[Proc_TA_SelectEmployeeSatDetails]
	-- Add the parameters for the stored procedure here
	@Empid int,
	@ToDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id	
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
    -- Insert statements for procedure here
	SELECT C.Sat_WorkHrs from #EmpCategory EC
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId 
	where EmployeeId=@Empid
	drop table #EmpCategory
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeLevel]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeLevel]
	@EmployeeId as int
AS
BEGIN
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= getdate() and EL.LevelId is not null
	select TA_Tbl_EmployeeLevel.levelID from TA_Tbl_EmployeeLevel
	Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId 
	where TA_Tbl_EmployeeLevel.EmployeeId=@EmployeeId
--Remove the temporary tables here   
drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeGroupName]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeGroupName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectEmployeeGroupName
Description	:	Get groupName from Ta_tbl_usergroup
Tables Included	:	ta_tbl_employee, Ta_tbl_usergroup
Created By	:	Prabakaran
Created On	:	22-Aug-07
Modified By	:
Modified On	:
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeGroupName]
@employee_Id int
as
BEGIN
	SET NOCOUNT ON
	select ug.groupName as GroupName,ug.hasSpecialRights,isnull(ug.ReportsBasedOn,0)ReportsBasedOn,ug.IndividualUsers from ta_tbl_employee e
	inner join Ta_tbl_usergroup ug on ug.groupId=e.UserGroup_Id where e.employee_Id=@employee_Id and e.isdeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesByIds]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeesByIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created by		:	Manjula.P
Created Date	:	07-Aug-2014
Descriptions	:	Selecting employee details by employees ids
*/
create proc [dbo].[Proc_TA_SelectEmployeesByIds]
(
@Employee_Id nvarchar(max)
)
as
begin
	select Employee_Id as EmpId,Employee_Code_Id as EmployeeId,Employee_FirstName + '' '' + isnull(Employee_LastName,'' '') AS ''EmployeeName'' from TA_Tbl_Employee where Employee_Id in (select Value from dbo.Split(@Employee_Id,'',''));
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeSwipeCardNo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeSwipeCardNo]  
 -- Add the parameters for the stored procedure here  
 @maxID int  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
 SELECT isnull(Employee_FirstName,'''') + Space(1) + isnull(Employee_LastName,'''') as EmployeeName, SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Id = @maxID  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeShift]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeShift] (@Shiftid int)  
AS  
 BEGIN  
if(@shiftid <> -1)
SELECT Shift_Name,* FROM TA_Tbl_Shift WHERE Shift_Id=@Shiftid and isdeleted=0  
else
Select ''Off''
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpDemo]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmpDemo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmpDemo] 
AS
BEGIN
	select * from ta_tbl_employee where employee_id !=1 order by employee_firstname
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	Proc_TA_SelectEmployeeForGroupManualEntry ''3,5,11'',''SuperAdmin'',''0'','''',''2011/09/01'',0
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupManualEntry]
(
    @LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmployeeCodeID as varchar(30),
	@date datetime,
	@ShiftId int
)      
AS      
BEGIN      
	SET NOCOUNT ON;      
	DECLARE @sql AS VARCHAR(5000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	 IF(@LevelId = '''')
		BEGIN
		SET @LevelId = ''0''
		END
	 SET @sql =''SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '''' '''' + cast(Employee_MiddleName as varchar(50)) else '''' '''' end +  isnull(Employee_LastName,'''''''') AS ''''Employee Name'''' FROM TA_Tbl_Employee''
	 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
	 SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''
	 SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	 SET @sql = @sql + '' INNER JOIN TA_Tbl_PermanentShiftAllocation on TA_Tbl_Employee.Employee_Id=TA_Tbl_PermanentShiftAllocation.EmployeeId''
	 SET @sql = @sql + '' LEFT OUTER JOIN dbo.TA_Tbl_Shift ON TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@date) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id''
	SET @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	SET @sql = @sql + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	SET @sql = @sql + '' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1  ''
	if(@LevelId<>''0'')
	Begin
		SET @sql = @sql + '' AND #EmpLevel.LevelId in ('' + @LevelId + '') ''
	End
	if(@EmployeeCodeID<>'''')
	Begin
		SET @sql = @sql + '' AND Employee_Code_Id = ''''''+ @EmployeeCodeID  + '''''' ''     
	End
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	SET @sql = @sql + '' AND Employee_Firstname<>''''Administrator'''' ORDER BY Employee_Code_Id''     
	 EXEC(@sql)          
	drop table #EmpLevel
	drop table #EmpDesignation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_SelectEmployeeDetailsForTesting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Manikandan.RR
-- Create date: 30-01-2014
-- Description:	To select the employee details
-- =============================================
CREATE PROCEDURE [dbo].[PROC_TA_SelectEmployeeDetailsForTesting]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Employee 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_SelectEmailByEmpId
Description	:	Get Email Id of Employees Based on their Employee_Code_Id
Tables Included	:	TA_TBL_Employee
Created By	:	Prabakaran
Created On	:	23-June-07
Modified By	:
Modified On	:
*/
CREATE  procedure [dbo].[Proc_TA_SelectEmailByEmpId]
@EmployeeCodeId nvarchar(50)
as
begin
select EmailId,Employee_FirstName,Employee_code_ID from TA_TBL_Employee 
where Employee_Code_Id=@EmployeeCodeId and employee_status=1
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_SelectEmailOfSanctionAuthorityByEmpId
Description		:	Get Permisssion Details of Employees Based on their Employee_Id
Tables Included	:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	21-Jul-07
Modified By		:
Modified On		:
*/
--Proc_TA_SelectEmailOfSanctionAuthorityByEmpId 304
CREATE  procedure [dbo].[Proc_TA_SelectEmailOfSanctionAuthorityByEmpId]
@Employee_Id bigint
as
select Employee_Id,EmailId from TA_TBL_Employee 
where Employee_Id =(select Leave_Sanc_Authority from TA_TBL_Employee where Employee_Id=@Employee_Id)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectEmailOfReportingToByEmpId
Description		:	Get Email Id of Reporting_To of Employees Based on their Employee_Id
Tables Included	:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_SelectEmailOfReportingToByEmpId]
@Employee_Id nvarchar(50)
as
select Employee_Id,EmailId from TA_TBL_Employee 
where Employee_Id =(select Reporting_To from TA_TBL_Employee where Employee_Id=@Employee_Id)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyGroup]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompanyGroup]
AS
BEGIN
	select  CompanyGroup from Ta_tbl_CompanyGroup
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDeviceFromBiostar]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDeviceFromBiostar]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.Karthikeyan.
-- Create date: 04-03-2016
-- Description:	To get the Device details from biostar\bioadmin database
-- This procedure has been used in Terminal sync
-- Proc_TA_SelectDeviceFromBiostar
-- select * from TA_Tbl_Terminal
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectDeviceFromBiostar]
	@ConnString as nvarchar(max)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	DECLARE @sql2 varchar(8000)
	DECLARE @sql1 varchar(8000)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	SET @ConnectionString=@ConnString
	IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
		BEGIN
			INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
			SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=2
			UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=3)
			UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
			UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
			UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=4)
			UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=5)				
			UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
			--select * from  Ta_tbl_DeviceServerDetails
			UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
		END			
	SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails
	if not exists(select * from sys.servers where name = N''''+@ServerName+'''')
	begin
		EXEC sp_addlinkedserver @server=@ServerName
	end
	declare @suser_sname nvarchar(256) 
	set @suser_sname= suser_sname()
	EXEC master.dbo.sp_addlinkedsrvlogin 
	@rmtsrvname=@ServerName,
	@useself=N''False'',
	@locallogin=@suser_sname,
	@rmtuser=@UserId,
	@rmtpassword=@Password
	CREATE TABLE #test(exist int,TableName varchar(500))
	Create table #DeviceDetailsMovedToTimecheck(name varchar(50))			
	set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''TB_READER'''')''
	Insert into #test exec(@sql)			
		if exists(select COUNT(*) from #test where TableName =''TB_READER'')
		begin
			set @sql2=''select nReaderIdn,nReaderIdn,sName,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0) as DataType,getdate(),1,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_READER where 
			convert(varchar(20),nReaderIdn) not in(''
			set @sql2=@sql2+ '' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )''
			Exec (@sql2)
		end
	delete from Ta_tbl_DeviceServerDetails
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategoryDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCategoryDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_SelectCategoryDetails]      
(      
	@TYPE CHAR(1)='''',
	@CategoryId INT,
	@UserGroupName nVarchar(250)
)      
AS            
BEGIN
	Create table #TempCategory(CategoryId bigint,CategoryName nvarchar(100),IsDeleted bit,IsFlexible bit,flag int)
	IF (@TYPE=''A'')          
		BEGIN  
			IF(@UserGroupName = ''SuperAdmin'')  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category  
				END  
			ELSE  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE IsDeleted=0      
				END  
		END
	-- P Refers Particular     
	ELSE IF (@TYPE=''P'')      
		BEGIN  
			IF(@UserGroupName = ''SuperAdmin'')  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE CategoryId=@CategoryId  
				END  
			ELSE  
				BEGIN
					insert into #TempCategory
					SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category WHERE CategoryId=@CategoryId AND IsDeleted=0      
				END  
		END            
	ELSE If (@TYPE=''I'')            
		BEGIN
			insert into #TempCategory
			SELECT CategoryId,CategoryName,IsDeleted,IsFlexible,0 FROM TA_Tbl_Category  WHERE IsDeleted=0
		END  
	Update #TempCategory set flag=1 from #TempCategory TC inner join ta_tbl_employeeCategory EC on TC.CategoryId=EC.CategoryId
	select * from #TempCategory 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCategory]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCategory]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	30-Mar-2013
-- Description		:	Select Three Columns(MonToSat_WorkHrs, Sat_WorkHrs, WeekDay_WorkHrs) in Insert and update Query
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectCategory]
	@CategoryID INT
AS
BEGIN
	SELECT
		CategoryName,
		CategoryId,
		IsFlexible,
		ISNULL(MonToSat_WorkHrs, 0.0) MonToSat_WorkHrs,
		ISNULL(Sat_WorkHrs, 0.0) Sat_WorkHrs,
		ISNULL(WeekDay_WorkHrs, 0.0) WeekDay_WorkHrs,
		ISNULL(ARMIS_WorkHrs, 0.0) ARMIS_WorkHrs
	FROM Ta_tbl_Category
		WHERE CategoryId = @CategoryId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectClockDetailsByEmployeeId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name : Proc_TA_SelectClockDetailsByEmployeeId
--Tables Used         :TA_Tbl_ClockDetails
-- Author                  : Kumuthini.L
-- Created On          : 13-Sep-2007
-- Modified On         : 19-Feb-2008
CREATE PROCEDURE [dbo].[Proc_TA_SelectClockDetailsByEmployeeId]
(
   @SwipeCardNo Varchar(15),
   @Date Varchar(15)
)
AS
SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId=@SwipeCardNo AND Clk_Date=@Date
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatingSMSGatewayDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatingSMSGatewayDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016 16:54>
-- Description:	<Updating SMS gateway details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdatingSMSGatewayDetails]
	-- Add the parameters for the stored procedure here
	@serviceURL varchar(max), 
	@destinationKey varchar(100), 
	@messageKey varchar(100), 
	@phNo varchar(20),
	@EmpID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	delete from ta_tbl_SMSGateway
	Insert into ta_tbl_SMSGateway values(@serviceURL,@destinationKey,@messageKey,getdate(),@phNo,@EmpID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--[Proc_Ta_UpdatingProcessedDataValuesForService]
--@Process_Rec_ID = 239914,@Shift_Id = 2,@Shift_StartTime = N''09:30:00 AM'',@Shift_EndTime = N''06:00:00 PM'',
--@WorkHrs = N'''',@InTime = N''01:51 PM'',@OutTime = N''05:51 PM'',
--@BreakHrs = N''00:00'',@LunchHrs = N''00:00'',@PermissionHrs = N''00:00'',@HrsWork = N''04:00'',@Attendance = N''Attendance'',
--@HrsOT = N''00:00'',@NormOT = N''00:00'',@OffOT = N''00:00'',@HolOT = N''00:00'',@OvertimeStatus = N''OvertimeStatus'',
--@HrsLess = N''03:30'',@HrsExtra = N''00:00'',@LateIn = N''04:21'',@EarlyOut = N''00:00'',@BreakHrsInMins = 1,@LunchHrsInMins = 1,@PermissionHrsInMins = 1,
--@HoursWorkInMins = 1,@WorkHoursInMins = 1,@LessHoursInMins = 1,@LateInMins = 1,@EarlyOutMins = 1,@ExtraMins = 1,@OtMins = 1,@LateExit = 1,
--@EarlyEntry = 1,@TotalDays = 1,@Status = null,@IsOnduty = 1,@FNAttendanceCode = N''Absent'',@ANAttendanceCode = N''Present'',@LeaveStatus = N''1'',
--@PermissionStatus = N''1'',@NormOtmins = 1,@OffOtmins = 1,@HolOtMins = 1,@CLAvailed = 1,@YearSettingId = 1,@LeaveType_Id = 1,@Holiday_Description = N'''',
--@EarlyInmins = 1,@EarlyInHrs = N''00:00'',@lateExitMins = 1,@LateExitHours = N''00:00'',@Inpunch = N''Shift In'',@Outpunch = N''In Duty'',@Indate = N''09/18/2015'',@Outdate = N''09/18/2015''
CREATE PROCEDURE [dbo].[Proc_Ta_UpdatingProcessedDataValuesForService]
(
	@Process_Rec_ID bigint,		
	@Shift_Id	int,
	@Shift_StartTime	nvarchar(40),
	@Shift_EndTime	nvarchar(40),
	@WorkHrs	nvarchar(20),
	@InTime	nvarchar(50),
	@OutTime	nvarchar(50),
	@BreakHrs	nvarchar(20),
	@LunchHrs	nvarchar(20),
	@PermissionHrs	nvarchar(20),
	@HrsWork	nvarchar(20),
	@Attendance	nvarchar(40),
	@HrsOT	nvarchar(20),
	@NormOT	nvarchar(20),
	@OffOT	nvarchar(20),
	@HolOT	nvarchar(20),
	@OvertimeStatus	nvarchar(100),
	@HrsLess	nvarchar(20),
	@HrsExtra	nvarchar(20),
	@LateIn	nvarchar(20),
	@EarlyOut	nvarchar(20),
	@BreakHrsInMins	float,
	@LunchHrsInMins	float,
	@PermissionHrsInMins	float,
	@HoursWorkInMins float,
	@WorkHoursInMins float,
	@LessHoursInMins float,
	@LateInMins	float,
	@EarlyOutMins float,
	@ExtraMins	float,
	@OtMins	float,
	@LateExit	bit,
	@EarlyEntry	bit,	
	@TotalDays	numeric(9),
	--@LeaveCode	nvarchar(40),	
	@Status	nvarchar(100),
	@IsOnduty	bit,
	@FNAttendanceCode nvarchar(30),
	@ANAttendanceCode nvarchar(30),	
	@LeaveStatus nvarchar(100),
	@PermissionStatus nvarchar(100),
	@NormOtmins float,
	@OffOtmins float,
	@HolOtMins float,
	@CLAvailed numeric(5),
	@YearSettingId int,
	@LeaveType_Id int,
	@Holiday_Description nvarchar(500),
	@EarlyInmins int,
	@EarlyInHrs	varchar(20),
	@lateExitMins int,
	@LateExitHours varchar(20),
	@Inpunch varchar(20),
	@Outpunch varchar(20),
	@Indate	datetime,
	@Outdate datetime
)
AS
BEGIN	
	SET NOCOUNT ON;	
	RETRY: -- Label RETRY
	BEGIN TRANSACTION
	BEGIN TRY
		UPDATE TA_Tbl_ProcessedData SET InTime = @InTime,
									OutTime = @OutTime,
									Shift_Id = @Shift_Id,
									HrsWork = @HrsWork,
									LateIn = @LateIn,
									LateInMins = @LateInMins,
									EarlyOut = @EarlyOut,
									EarlyOutMins = @EarlyOutMins,
									HrsOT = @HrsOT ,
									NormOT = @NormOT,
									Status = NULL,
									OffOT = @OffOT,
									HolOT = @HolOT,
									Attendance = @Attendance,
									FNAttendanceCode=@FNAttendanceCode,
									ANAttendanceCode=@ANAttendanceCode,
									BreakHrs = @BreakHrs,
									LunchHrs = @LunchHrs,
									HoursWorkInMins = @HoursWorkInMins,
									BreakHrsInMins = @BreakHrsInMins,
									LunchHrsInMins = @LunchHrsInMins,
									YearSettingId = @YearSettingId,
									Indate=@Indate,
									Outdate=@Outdate,
									Inpunch=@Inpunch,
									Outpunch=@Outpunch,
									Holiday_Description=@Holiday_Description,
									PermissionHrsInMins=@PermissionHrsInMins,
									PermissionHrs = @PermissionHrs,
									WorkHoursInMins=@WorkHoursInMins,
									Shift_StartTime=@Shift_StartTime,
									Shift_EndTime =@Shift_EndTime, 
									WorkHrs= @WorkHrs,   
									OvertimeStatus=@OvertimeStatus,					
									EarlyEntry = @EarlyEntry,
									EarlyInmins =@EarlyInmins,
									EarlyInHrs = @EarlyInHrs,        
									LateExit= @LateExit,
									lateExitMins=@lateExitMins,
									lateExitHours=@lateExitHours,
									HrsLess = @HrsLess,
									HrsExtra = @HrsExtra,
									ExtraMins = @ExtraMins,
									OtMins = @OtMins,
									TotalDays = @TotalDays,
									--LeaveCode = @LeaveCode,
									ProcessFlag = 1,
									LessHoursInMins =@LessHoursInMins
									WHERE Process_Rec_ID = @Process_Rec_ID
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH		
		ROLLBACK TRANSACTION
		IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
		BEGIN
			WAITFOR DELAY ''00:00:00.05'' -- Wait for 5 ms
			GOTO RETRY -- Go to Label RETRY
		END
	END CATCH   
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearsetting]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearsetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_UpdateYearsetting](@NewId int)
AS
BEGIN TRANSACTION 
UPDATE Ta_Tbl_Yearsetting SET IsActive=0
UPDATE Ta_Tbl_Yearsetting SET IsActive=1 WHERE YearSettings_Id=@NewId
COMMIT TRANSACTION 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid_Group]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateVoidUnVoid_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 04-May-2011
-- Description:	<Description,,>
/*
 [Proc_TA_UpdateVoidUnVoid_Group]
''Void'',
''<DocumentElement>
  <Table>
    <Clk_ID>1812</Clk_ID>
    <EmployeeCode>6599</EmployeeCode>
    <EmpName>Rajendran S</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1811</Clk_ID>
    <EmployeeCode>7588</EmployeeCode>
    <EmpName>Sathishkumar S</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1810</Clk_ID>
    <EmployeeCode>7877</EmployeeCode>
    <EmpName>Manikandan R</EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1813</Clk_ID>
    <EmployeeCode>1234</EmployeeCode>
    <EmpName>Manikandan </EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
  <Table>
    <Clk_ID>1814</Clk_ID>
    <EmployeeCode>1235</EmployeeCode>
    <EmpName>Anitha </EmpName>
    <InDate>13 May 2019</InDate>
    <InTime>10:52:43</InTime>
    <IsVoid>False</IsVoid>
  </Table>
</DocumentElement>''
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid_Group] 
	@opr as varchar(8),
	@xml xml
AS
BEGIN
	set nocount on
	create table #TempClockDetails 
	(
		[CLK_ID] [bigint],		
		employee_code_id varchar(50),
		[CLK_DATE] [datetime] NULL,
		[CLK_TIME] [nvarchar](25) NULL
	)
	DECLARE @Index int
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		insert into #TempClockDetails
		select xm.* from OPENXML(@Index, ''/DocumentElement/Table'',2)
		with (Clk_ID bigint,EmployeeCode varchar(50),InDate varchar(15),InTime varchar(10)) as xm
	Exec sp_xml_removedocument @Index
	
	--Updates the void flag in the ta_tbl_clockdetails table
	update TA_Tbl_Clk_RawData set	ReasonId=case when (@opr=''Void'') then 6 else 0 end,
									Clk_Process=0,
									CLK_FLAG=case when (@opr=''Void'') then 1 else 0 end
	from TA_Tbl_Clk_RawData c 
	inner join TA_Tbl_Employee e on e.SwipeCardNo=c.CLK_CARDID
	inner join #TempClockDetails TCD on TCD.CLK_ID=c.CLK_ID
	
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' from TA_Tbl_ManualTimeEntry m
	inner join TA_Tbl_Employee e on e.SwipeCardNo=m.ManualTimeEntry_Employee_Id
	inner join  #TempClockDetails TCD on TCD.Employee_Code_Id= e.Employee_Code_Id
	WHERE ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,TCD.Clk_Date) AND DateAdd(d,1,TCD.Clk_Date)) 
	OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,TCD.Clk_Date) AND DateAdd(d,1,TCD.Clk_Date)))
	
	delete from TA_Tbl_ClockDetails from TA_Tbl_ClockDetails C
	inner join TA_Tbl_Employee e on e.SwipeCardNo=C.Clk_EmpId
	inner join #TempClockDetails TCD on (TCD.Employee_Code_Id=e.Employee_Code_Id and C.Clk_Date=TCD.Clk_Date)	
	
	delete from TA_Tbl_ProcessedData from TA_Tbl_ProcessedData P 
	inner join TA_Tbl_Employee e on e.SwipeCardNo=P.Employee_Code_Id
	inner join #TempClockDetails TCD on (TCD.Employee_Code_Id=e.Employee_Code_Id and P.Date=TCD.Clk_Date)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateVoidUnVoid]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateVoidUnVoid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author			:	Prabakaran.P
-- Create date		: 
-- Modified date	:	02-May-11
-- Description		:	Procedure used to Ignore and Include punches
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateVoidUnVoid] 
@ClkID as int,
@opr as varchar(8)
AS
BEGIN
	Declare @VoidFlag as int
	
	update TA_Tbl_Clk_RawData set	ReasonId=case when (@opr=''Void'') then 6 else 0 end,
									CLK_FLAG=case when (@opr=''Void'') then 1 else 0 end,
									CLK_PROCESS=0
	Where Clk_ID = @ClkID
	
	declare @InTime as datetime
	declare @InDate as datetime
	declare @OutDate as datetime
	declare @OutTime as datetime
	declare @CardID as varchar(100)
	declare @EmpID as varchar(100)			
	declare @dtClockDate as datetime
	
	select  @InDate  = Clk_Date,
			@InTime  = cast(convert(varchar(10),CLK_TIME,108) as datetime ),
			@CardID = CLK_CARDID
	from TA_Tbl_Clk_RawData   where  Clk_ID = @ClkID
	
	update TA_Tbl_Clk_RawData set CLK_FLAG=0,CLK_PROCESS=0 
	where CLK_CARDID=@CardID and CLK_DATE=@InDate and ReasonId=0
	
	select @EmpID=employee_code_id from ta_tbl_employee where 
	isdeleted=0 and employee_status=1 and swipecardno=@CardID
	
	delete from ta_tbl_clockdetails where Clk_Date=@InDate and Clk_EmpId=@CardID
	
	delete from TA_Tbl_ProcessedData from TA_Tbl_ProcessedData where Date=@InDate and Employee_Code_Id=@CardID
	
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' 
	WHERE ManualTimeEntry_Employee_Id = @EmpID AND 
	((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@InDate) AND DateAdd(d,1,@InDate)) 
	OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@InDate) AND DateAdd(d,1,@InDate))) 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserStatus]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateUserStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateUserStatus] 
	-- Add the parameters for the stored procedure here
	@UserId nvarchar(15),
    @IpAddress nvarchar(15),
    @LoginTime datetime,
    @Status bit,
    @SessionId nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	 INSERT INTO TA_Tbl_ConcurrentUser(UserId, IpAddress, LoginTime, Status, SessionId) VALUES(@UserId, @IpAddress, @LoginTime, @Status, @SessionId) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateUserProfile]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateUserProfile]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Manikandan.R
-- Create date: 16-08-2017
-- Description:	Updating User profile details by users from mobile app
-- updateUserProfile/json?EmpAutoID=48&fatherName=Rajendran&motherName=Mother%20Name&officialmail=manikandan.rr@angleritech.com&address=4/75,koniappa%20pillai%20street,%20kurichi,%20sundarapuram(post),%20Coimbatore-641024&bloodgrp=B%20ive&image=
-- Proc_TA_UpdateUserProfile 48,''Rajendran.r'',''usharani'',''manikandan.rr@angleritech.com'',''4/75,koniappa%20pillai%20street,%20kurichi,%20sundarapuram(post),%20Coimbatore-641024'',''B%20ive'',''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateUserProfile] 
	-- Add the parameters for the stored procedure here
	@EmpAutoID int, 
	@fatherName varchar(100),
	@motherName varchar(100),
	@officialmail varchar(200),
	@address varchar(500),
	@bloodgrp varchar(20),
	@image image=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Update TA_Tbl_Employee set Father_name=@fatherName,Mother_name=@motherName,EmailId=@officialmail,Permanent_Address=@address,
	Blood_Group=@bloodgrp,Photo=@image where Employee_Id=@EmpAutoID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateTimesheetEntry]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateTimesheetEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateTimesheetEntry]
	@TaskDetailID BIGINT,	
	@ApprovedHours varchar(10),
	@status varchar(50),
	@approvedby bigint,
	@Task_EmployeeID bigint,
	@Comments varchar(500)
AS
BEGIN	
	SET NOCOUNT ON;
	if(@TaskDetailID!='''' and @status!='''')
	begin
		update ta_tbl_taskprogressdetails set Status=@status where TaskDetailID=@TaskDetailID	
		Insert into ta_tbl_taskprogressStatus values(@TaskDetailID,@ApprovedHours,@approvedby,GETDATE(),@Comments,@status)
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftSettings]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	01-Apl-2013
-- Description		:	Adding the New Column(Default Lunch hrs)
-- Modified by Gopinath on 18Jun14 for Angler Migration added new column named as ''ExceptionHours''
-- [Proc_TA_UpdateShiftSettings]''OT'',27,'''','''',''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftSettings] 
(
	@tag nvarchar(10),
	@CompanyId as int,
	@maxHoursBeforeShift as varchar(10),
	@maxHoursAfterShift as varchar(10),
	@shiftBreak as varchar(10),
	@shiftMaxBreakHours as varchar(10),
	@monthlyWorkingHours as varchar(10),
	@weeklyWorkingHours as varchar(10),
	@AuditEmp as nvarchar(20),
	@HolidayOT as float,
	@WeekOffOT as float,
	@otOption as varchar(10),
	@strMonthClosureDate as varchar(20),
	@flexibleStatus int,
	@flexibleValue int,
	@otStatus int,		
	@fullAttendance int,
	@halfAttendance int,
	@DefaultLunchHours VARCHAR(10),
	@MaxLunchHrs NVARCHAR(5),
	@WeekOffStartHours as varchar(5),
	@IgnorePunch tinyint,
	@IgnorePunchInterval varchar(5),
	@AfterShiftTime bit,
	@BeforeShiftTime bit,
	@DefinedWorkhrs bit,
	@NoOfSuccessiveDaysInYear int,
	@CompensationValidityDays int,
	@HalfDayCompOff VARCHAR(5),
	@FullDayCompOff VARCHAR(5),
	@VaildityCompOffDays INT,
	@LateEntry bit,
	@EarlyEntry bit,
	@EarlyExit bit,
	@LateExit bit,
	@IsLunchDeduction bit,
	@LunchDeductionHours nvarchar(10)=''00:00'',
	@ExceptionHours as varchar(10),
	@24maxHoursBeforeShift as varchar(10),
	@24weeklyWorkingHours as varchar(10),
	@Flexi_AfterShiftTime	bit,
	@Flexi_BeforeShiftTime	bit,
	@Flexi_DefinedWorkhrs	bit,
	@CumulativeWeekStartDay as varchar(10),
	@CumulativeWeekEndDay as varchar(10),	
	@isCarryForwardCOff int,
	@isRequestingforCompOff int,
	@FirstAndLast bit,
	@SpecialOverTime1 int,
	@SpecialOverTime2 int
	
	--the 2 bewlow fields for vaigai --
	,@LateMinsPerDay int
	,@LateDaysPerMonth int

		--the 2 bewlow fields for sohit--
    ,@EarlyExitperDay int
	,@EarlyExitDaysPerMonth int

	--1 field for vaiagai late point--
	,@EnableAbsent bit
)	
AS
BEGIN
		declare @cou as int
		Select @cou = count(*) from TA_Tbl_shiftSettings where CompanyId=@CompanyId
		if(@tag=''OT'')
		begin
			update TA_Tbl_shiftSettings set 
				HolidayOT=@HolidayOT,
				WeekOffOT=@WeekOffOT, 
				otOption=@otOption , 
				OTRoundoffEnable=@otStatus,
				AfterShiftTime=@AfterShiftTime,
				BeforeShiftTime=@BeforeShiftTime,
				DefinedWorkhrs=@DefinedWorkhrs,
				HalfDayCompOff = @HalfDayCompOff,
				FullDayCompOff = @FullDayCompOff,
				VaildityCompOffDays = @VaildityCompOffDays,
				Flexi_AfterShiftTime=@Flexi_AfterShiftTime,
				Flexi_BeforeShiftTime=@Flexi_BeforeShiftTime,
				Flexi_DefinedWorkhrs=@Flexi_DefinedWorkhrs,
				Carry_Forward_COff_Year=@isCarryForwardCOff,
				isRequestingforCompOff=@isRequestingforCompOff,
				SpecialOverTime1=@SpecialOverTime1,
				SpecialOverTime2=@SpecialOverTime2
				where CompanyId=@CompanyId
			  select ShiftSettingId from TA_Tbl_shiftSettings where CompanyId=@CompanyId
		end
		else
		begin
			if (@cou>0)
			Begin
				update TA_Tbl_shiftSettings set 
				maxHoursBeforeShift=@maxHoursBeforeShift, 
				maxHoursAfterShift=@maxHoursAfterShift,
				shiftBreak=@shiftBreak,
				shiftMaxBreakHours=@shiftMaxBreakHours,
				monthlyWorkingHours=@monthlyWorkingHours,
				weeklyWorkingHours=@weeklyWorkingHours, 
				EmpID=@AuditEmp,
				DefaultMonthClosureDate=@strMonthClosureDate,
				IsFlexible = @flexibleStatus,
				FlexibleFlag=@flexibleValue,
				FullDayAttendance=@fullAttendance,
				halfdayAttendance=@halfAttendance,
				WeeklyOffStartHours=@WeekOffStartHours,
				IgnoreDuplicatePunch=@IgnorePunch,
				PunchInterval=@IgnorePunchInterval,
				NoOfSuccessiveDaysInYear=CONVERT(int, @NoOfSuccessiveDaysInYear),
				lateEntry=@LateEntry,
				EarlyEntry=@EarlyEntry,
				EarlyExit=@EarlyExit,
				LateExit=@LateExit,
				timestamp1=getdate(),
				IsLunchDeduction=@IsLunchDeduction,
				LunchDeductionHours=@LunchDeductionHours,
				MaxHoursBeforeShift_24HrsShift=@24maxHoursBeforeShift,
				WeeklyOffStartHours_24HrsShift=@24weeklyWorkingHours,
				CumulativeWeekStartDay=@CumulativeWeekStartDay,
				CumulativeWeekEndDay=@CumulativeWeekEndDay,
				DefaultLunchHours = @DefaultLunchHours,
				MaxLunchHours = @MaxLunchHrs,
				MaxWorkPlaceInHours=@ExceptionHours,
				FirstAndLast=@FirstAndLast
				,LateMinsPerDay=@LateMinsPerDay
				,LateDaysPerMonth=@LateDaysPerMonth
				,EarlyExitMinsPerDay=@EarlyExitperDay
				,EarlyExitDaysPerMonth=@EarlyExitDaysPerMonth
				,EnableAbsent=@EnableAbsent
				where CompanyId=@CompanyId
			  select ShiftSettingId from TA_Tbl_shiftSettings where CompanyId=@CompanyId
			End
			Else
				Begin
					insert into Ta_Tbl_ShiftSettings (CompanyId,HolidayOT,WeekOffOT, otOption,maxHoursBeforeShift,maxHoursAfterShift,shiftBreak,shiftMaxBreakHours,monthlyWorkingHours,weeklyWorkingHours,EmpID,DefaultMonthClosureDate,IsFlexible,FlexibleFlag,OTRoundoffEnable,FullDayAttendance,halfdayAttendance,WeeklyOffStartHours,IgnoreDuplicatePunch,PunchInterval,AfterShiftTime,BeforeShiftTime,DefinedWorkhrs,NoOfSuccessiveDaysInYear,CompensationValitityDays, HalfDayCompOff, FullDayCompOff, VaildityCompOffDays
					,lateEntry,EarlyEntry,EarlyExit,LateExit
					,timestamp,timestamp1,IsLunchDeduction,LunchDeductionHours,Flexi_AfterShiftTime,Flexi_BeforeShiftTime,Flexi_DefinedWorkhrs,MaxHoursBeforeShift_24HrsShift,WeeklyOffStartHours_24HrsShift
					,CumulativeWeekStartDay,CumulativeWeekEndDay, DefaultLunchHours, MaxLunchHours,MaxWorkPlaceInHours,Carry_Forward_COff_Year,isRequestingforCompOff,FirstAndLast
					,LateMinsPerDay
					,LateDaysPerMonth
					,EarlyExitMinsPerDay
					,EarlyExitDaysPerMonth
					,EnableAbsent
					) 
					values (@CompanyId,null,null, null,@maxHoursBeforeShift,@maxHoursAfterShift,@shiftBreak,@shiftMaxBreakHours,@monthlyWorkingHours,@weeklyWorkingHours,@AuditEmp,@strMonthClosureDate,@flexibleStatus,@flexibleValue,null,@fullAttendance,@halfAttendance,@WeekOffStartHours,@IgnorePunch,@IgnorePunchInterval,null,null,null,CONVERT(int,@NoOfSuccessiveDaysInYear),@CompensationValidityDays, null, null, null
				,@LateEntry,@EarlyEntry,@EarlyExit,@LateExit
					,getdate(),GETDATE(),@IsLunchDeduction,@LunchDeductionHours,null,null,null,@24maxHoursBeforeShift,@24weeklyWorkingHours,@CumulativeWeekStartDay,@CumulativeWeekEndDay,@DefaultLunchHours,
					 @MaxLunchHrs,@ExceptionHours,@isCarryForwardCOff,@isRequestingforCompOff,@FirstAndLast
					 ,@LateMinsPerDay
					 ,@LateDaysPerMonth
					 ,@EarlyExitperDay
					 ,@EarlyExitDaysPerMonth
					 ,@EnableAbsent
					 )
					select @@identity
				End
			end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_UpdateShiftDetails 1,3,''Testing Default Shift'',''TDS'','''',''09:00 AM'',''05:30 PM'',''09:00 AM'',''12:30 PM'',''01:00 PM'',''05:30 PM'','''','''',''12:30 PM'',''01:00 PM'',
--'''','''','''','''',''00:00'',''00:00'',0,''08:00'',''03:30'',''04:30'',1,0,0
CREATE  PROCEDURE [dbo].[Proc_TA_UpdateShiftDetails]     
(    
	@levelId int,    
	@ShiftId int,    
	@ShiftName nvarchar(50),     
	@ShiftShortName nvarchar(50),     
	@ShiftDescription nvarchar(255),    
	@ShiftStartTime nvarchar(10),    
	@ShiftEndTime nvarchar(10),    
	@Shift_FirstHalf_StartTime nvarchar(10),    
	@Shift_FirstHalf_EndTime nvarchar(10),    
	@Shift_SecondHalf_StartTime nvarchar(10),    
	@Shift_SecondHalf_EndTime nvarchar(10),    
	@ShiftGraceInTime nvarchar(10),    
	@ShiftGraceOutTime nvarchar(10),    
	@ShiftBreakStartTime1 nvarchar(10),    
	@ShiftBreakEndTime1 nvarchar(10),    
	@ShiftBreakStartTime2 nvarchar(10),    
	@ShiftBreakEndTime2 nvarchar(10),    
	@ShiftBreakStartTime3 nvarchar(10),    
	@ShiftBreakEndTime3 nvarchar(10),    
	@ShiftMinTimeOT nvarchar(10),    
	@ShiftMaxTimeOT nvarchar(10),    
	@ShiftWorkingDayOverTime float,    
	@ShiftTotalWorkingHours nvarchar(10),  
	@Shift_FirstHalfWorkingHours nvarchar(10),    
	@Shift_SecondHalfWorkingHours nvarchar(10),    
	@Emp_ID nvarchar(50),
	@DefaultShift int,
@ShiftType bit
	)    
AS    
BEGIN
declare @sql as nvarchar(3000)    
   --UPDATE TA_Tbl_Shift  SET Shift_Name=@ShiftName, Shift_ShortName = @ShiftShortName, Shift_Description=@ShiftDescription,Shift_StartTime=@ShiftStartTime,Shift_EndTime=@ShiftEndTime,Shift_GraceInTime=@ShiftGraceInTime,Shift_GraceOutTime=@ShiftGraceOutTi
   --me,Shift_BreakStartTime1=@ShiftBreakStartTime1,Shift_BreakEndTime1=@ShiftBreakEndTime1,Shift_BreakStartTime2=@ShiftBreakStartTime2,Shift_BreakEndTime2=@ShiftBreakEndTime2,Shift_BreakStartTime3 =@ShiftBreakStartTime3,Shift_BreakEndTime3=@ShiftBreakEndTime3
   -- ,Shift_MinTimeOT= @ShiftMinTimeOT, Shift_MaxTimeOT=@ShiftMaxTimeOT,Shift_WorkingDay_OverTime=@ShiftWorkingDayOverTime,Shift_Holiday_OverTime=@ShiftHolidayOverTime,Shift_Weekoff_OverTime= @ShiftWeekoffOverTime,Shift_TotalWorkingHours=@ShiftTotalWorkingHou
   --rs WHERE Shift_Id=@ShiftId 
	Declare @OldGraceShiftIn nvarchar(6)
	Declare @OldGraceShiftOut nvarchar(6)
	Declare @Shift_BreakStartTime1	nvarchar(10)
	Declare @Shift_BreakEndTime1	nvarchar(10)
	Declare @Shift_BreakStartTime2	nvarchar(10)
	Declare @Shift_BreakEndTime2	nvarchar(10)
	Declare @Shift_BreakStartTime3	nvarchar(10)
	Declare @Shift_BreakEndTime3	nvarchar(10)
	select @OldGraceShiftIn=Shift_GraceInTime,@OldGraceShiftOut=Shift_GraceOutTime,
	@Shift_BreakStartTime1=Shift_BreakStartTime1,
	@Shift_BreakEndTime1=Shift_BreakEndTime1,
	@Shift_BreakStartTime2=Shift_BreakStartTime2,
	@Shift_BreakEndTime2=Shift_BreakEndTime2,
	@Shift_BreakStartTime3=Shift_BreakStartTime3,
	@Shift_BreakEndTime3=Shift_BreakEndTime3		
    from TA_Tbl_Shift where Shift_Id=@ShiftId
   insert into ta_tbl_GraceDetails values(@ShiftId,@OldGraceShiftIn,@OldGraceShiftOut,  @Shift_BreakStartTime1,
   @Shift_BreakEndTime1,	@Shift_BreakStartTime2,	@Shift_BreakEndTime2,	@Shift_BreakStartTime3,	@Shift_BreakEndTime3,   GETDATE())
   Declare @DefShift int
	if exists(select DefaultShift from TA_Tbl_Shift where Level_Id=@levelId and DefaultShift=1)
		begin	
			if(@DefaultShift=1)
				begin
					update ta_tbl_shift set DefaultShift=0 where Level_Id =@levelId 
				end
		end
   set @sql = ''UPDATE TA_Tbl_Shift  SET Level_Id=''+cast(@levelId as nvarchar(25))+'', Shift_Name=N''''''+@ShiftName+'''''', Shift_ShortName = N''''''+@ShiftShortName+'''''', Shift_Description=N''''''+@ShiftDescription+'''''',Shift_StartTime=N''''''+@ShiftStartTime+'''''',
   Shift_EndTime=N''''''+@ShiftEndTime+'''''',Shift_FirstHalf_StartTime=N''''''+@Shift_FirstHalf_StartTime+'''''',Shift_FirstHalf_EndTime=N''''''+@Shift_FirstHalf_EndTime+'''''',Shift_SecondHalf_StartTime=N''''''+@Shift_SecondHalf_StartTime+'''''',Shift_SecondHalf_EndTime=N''''''+
   @Shift_SecondHalf_EndTime+'''''',Shift_GraceInTime=N''''''+@ShiftGraceInTime+'''''',Shift_GraceOutTime=N''''''+@ShiftGraceOutTime+'''''',Shift_BreakStartTime1=N''''''+@ShiftBreakStartTime1+'''''',Shift_BreakEndTime1=N''''''+@ShiftBreakEndTime1+'''''',Shift_BreakStartTime2=N''''''+
   @ShiftBreakStartTime2+'''''',Shift_BreakEndTime2=N''''''+@ShiftBreakEndTime2+'''''',Shift_BreakStartTime3 =N''''''+@ShiftBreakStartTime3+'''''',Shift_BreakEndTime3=N''''''+@ShiftBreakEndTime3+'''''' ,Shift_MinTimeOT= N''''''+ @ShiftMinTimeOT +'''''', Shift_MaxTimeOT=N''''''+ @ShiftMaxTimeOT +'''''',
   Shift_WorkingDay_OverTime=''+cast(@ShiftWorkingDayOverTime as nvarchar(25))+'',Shift_TotalWorkingHours=N''''''+@ShiftTotalWorkingHours+'''''',Shift_FirstHalfWorkingHours=N''''''+@Shift_FirstHalfWorkingHours+'''''',Shift_SecondHalfWorkingHours=N''''''+
   @Shift_SecondHalfWorkingHours+'''''',Emp_ID=N'''''' + @Emp_ID + '''''',DefaultShift=''+cast(@DefaultShift as nvarchar(25))+ '',ShiftType='' + cast(@ShiftType as nvarchar(1)) + '',ModifiedDate='''''' + cast(GETDATE() as nvarchar(25)) + '''''' WHERE Shift_Id=''+cast(@ShiftId as nvarchar(25))+''''  
   exec(@sql)  
    --if(cast(@DefaultShift as nvarchar(1))=''1'')
    --BEGIN
    --  update TA_Tbl_Shift set DefaultShift=0 where Shift_Id<>@ShiftId and Level_Id=@levelId
    --END 
END
  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftReport]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:        Karthikeyan.R
-- Create date: 10-Aug-2016
-- Description:   Update Shift Setting week month start and end day update in default company
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftReport]
      -- Add the parameters for the stored procedure here
      @WeekStartDay nvarchar(3),
      @WeekEndDay nvarchar(3),
      @MonthStartDay nvarchar(3),
      @MonthEndDay nvarchar(3),
      @MapKey nvarchar(max)
AS
BEGIN
      SET NOCOUNT ON;
      update ta_tbl_shiftsettings set CumulativeWeekStartDay=@WeekStartDay,CumulativeWeekEndDay=@WeekEndDay,MonthStartDay=@MonthStartDay,MonthEndDay=@MonthEndDay,MapKey=@mapkey
      select -1 as ''ShiftSettingId''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_UpdateResponseDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_UpdateResponseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
=============================================
Procedure Name = [Proc_TC_UpdateResponseDetails]
Created By = K.Gopinath
Created Date = 24 March 2014
Description = Procedure for Update the license requested response details in TA_Tbl_LicenseRequestDetail table
Proc_TC_UpdateResponseDetails 1,1
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_UpdateResponseDetails]
@RequestID bigint,
--@MacAddress nvarchar(50),
@Status bit
AS
BEGIN
update TA_Tbl_LicenseRequestDetail
SET
RequestID=@RequestID,
--MacAddress=@MacAddress,
Status=@Status,
ModifiedDate=GETDATE()
where RequestID=@RequestID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_SelectLicenseReqDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_SelectLicenseReqDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
=============================================
Procedure Name = Proc_TC_SelectLicenseReqDetails
Created By = K.Gopinath
Created Date = 18 March 2014
Description = Procedure for select the license requested details in TA_Tbl_LicenseRequestDetail table
Proc_TC_SelectLicenseReqDetails
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_SelectLicenseReqDetails]
AS
BEGIN
select RequestID, Status from TA_Tbl_LicenseRequestDetail where Status=1 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TC_InsertResponseDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TC_InsertResponseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
=============================================
Procedure Name = Proc_TC_InsertResponseDetails
Created By = K.Gopinath
Created Date = 17 March 2014
Description = Procedure for insert the license requested response details in TA_Tbl_LicenseRequestDetail table
Proc_OL_GenerateLicense 1,1
=============================================
*/
CREATE PROCEDURE [dbo].[Proc_TC_InsertResponseDetails]
@RequestID bigint,
@MacAddress nvarchar(50),
@Status bit
AS
BEGIN
IF NOT EXISTS (select RequestID from TA_Tbl_LicenseRequestDetail where RequestID=@RequestID)
insert into TA_Tbl_LicenseRequestDetail(RequestID,MacAddress,Status,CreatedDate) values 
(@RequestID,@MacAddress,@Status,GETDATE())
else
update TA_Tbl_LicenseRequestDetail
SET
--RequestID=@RequestID,
MacAddress=@MacAddress,
Status=@Status,
ModifiedDate=GETDATE() where RequestID=@RequestID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_WriteErrorDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_WriteErrorDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 15.09>
-- Description:	<Write Error details into Errorlog Table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_WriteErrorDetails]
	-- Add the parameters for the stored procedure here
	@Clk_Id varchar(50),
	@strErrorMessage varchar(max),
	@Type char(2)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	insert into TA_Tbl_ErrorLog_ClockRawData(Clock_Id,ErrorMessage) values(@Type+''-''+ @Clk_Id,@strErrorMessage)
	if(@Type=''C'')
	begin		
		UPDATE TA_Tbl_Clk_RawData SET clk_flag = 0,clk_process=1,ReasonId=5 WHERE clk_Id=@Clk_Id
	end
	if(@Type=''MU'')
	begin
		UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''Y'' WHERE ManualTimeEntry_Id =@Clk_Id
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UserLogin]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UserLogin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UserLogin]
(
	@username NVARCHAR(10),
	@password NVARCHAR(50)
)
AS
BEGIN	
	SELECT	
	Employee_Id,Employee_FirstName + '' '' + Employee_LastName AS ''Employee Name'',
	Employee_Code_Id,EmailId,Photo,
	UserGroup_Id,Designation_Id,ShiftPattern_Id,Bus_Id,
			Employee_MiddleName,Employee_LastName,Father_name,Mother_name,DateofBirth,DateofBirth_Record,Blood_Group,Contact_Address, 
			Permanent_Address, Phone_Number, Mobile_Number, Gender, Marital_status, Nationality, Religion,Personal_mailid, Passport_No, 
			Passport_expirydate, Visa_No, Visa_expirydate, Vehicle_Type, Vehicle_No, Anniversary_Date, Native_Place, District, State, Country, 
			Spouse_No, Children_No, DateOfJoining, Reporting_To, Leave_Sanc_Authority, Prev_Experience, Basic_Salary, Allowances, 
			UserName, Emp_password, Qual_JoiningTime, Qual_Employment, OutDoorJob, CompOff_Eligible, OT_Eligible, ESI_Eligible, PF_Eligible, 
			Report_Exclude, Employee_Status, SwipeCardNo, Time_Stamp, Emp_ID, Isdeleted, Hostel, IsFlexible, InActiveDate, CustomField1, CustomField2, 
			CustomField3, CustomField4, CustomField5, IsComplete, Isdeleted_Status, InActive_Status, IsImported,MobileClockInOUt FROM TA_Tbl_Employee 
	WHERE UserName=@username AND Emp_password=@password AND IsDeleted=0 and Employee_status=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_UpdateOTHours]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_UpdateOTHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_UpdateOTHours]
	-- Add the parameters for the stored procedure here
	@Type nvarchar(50),
	@OTMins int,
	@UpOTHours nvarchar(50),
	@OTHours nvarchar(50),
	@UpOTHrs nvarchar(50),
	@Process_Rec_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@Type=''NormOTHrs'')
	begin
		Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,NormOT=@UpOTHours,ActHrsOT=''00:00'',ActNormOT=@OTHours,NormOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
	end	
	else if(@Type=''WeekOffOT'')
		begin
			Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,OffOT=@UpOTHours,ActHrsOT=''00:00'',ActOffOT=@OTHours,OffOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
		end
	else if(@Type=''HolOT'')
		begin	
			Update TA_Tbl_ProcessedData set ActNormOTMins=@OTMins,ActOTMins=@OTMins,HolOT=@UpOTHours,ActHrsOT=''00:00'',ActOffOT=@OTHours,HolOTMins=@UpOTHrs,OTMins=@UpOTHrs where Process_Rec_ID=@Process_Rec_ID
		end
END
-----------------------------------------------------------------------------------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TransportationMapping]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TransportationMapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_Update_TA_TBL_TransportationMapping]    
(    
 @VehicleId INT,    
 @RouteId INT,    
 @CompanyId INT,     
 @RegionId INT,    
 @BranchId INT,    
 @id int    
)     
As    
BEGIN    
 UPDATE TA_Tbl_Transportation_Mapping    
SET    
   VehicleId = @VehicleId,     
   RouteId = @RouteId,    
   Company_Id =@CompanyId,    
   Region_Id = @RegionId,    
   Branch_Id = @BranchId    
  WHERE VehicleId=@id --and Id=@id    
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_Transportation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_Transportation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Procedure [dbo].[Proc_Update_TA_TBL_Transportation] 
(
	@VehicleNo INT,
	@RouteName VARCHAR(50),
	@CompanyId INT,	
	@RegionId INT,
	@BranchId INT,
	@id int
) 
As
BEGIN
	UPDATE TA_Tbl_Transportation
SET
			VehicleNo = @VehicleNo, 
			RouteName = @RouteName,
			Company_Id =@CompanyId,
			Region_Id = @RegionId,
			Branch_Id = @BranchId
  		WHERE VehicleNo=@VehicleNo and Id=@id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Update_TA_TBL_TitleMapping]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Update_TA_TBL_TitleMapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_Update_TA_TBL_TitleMapping]
(    
	 @CompanyId INT,     
	 @RegionId INT,    
	 @BranchId INT,
	 @DepartmentId INT,
	 @SectionId INT,
	 @TitleId INT,
	@id INT
)     
As    
BEGIN    
	UPDATE TA_Tbl_TitleMapping  
	SET    
	   Company_Id =@CompanyId,    
	   Region_Id = @RegionId,    
	   Branch_Id = @BranchId,
	   Department_Id=@DepartmentId,
	   Section_Id=@SectionId,
	   TitleId=@TitleId	    
  WHERE Id=@Id
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateSelectedLeavePolicy]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateSelectedLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <15-July-2019>
-- Description:	<Validating the selected leave policy for insertion>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ValidateSelectedLeavePolicy]
	@PolicyName varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT companyid=isnull(companyid,'''') from TA_Tbl_LeavePolicy where PolicyName=@PolicyName
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi_All]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeFlexi_All]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_UpdateEmployeeFlexi 0,
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi_All]
(
@Flexi as int,
@xml xml
)
AS
BEGIN
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
  --update ta_tbl_employee set isFlexible=@Flexi where Employee_ID = @EmployeeID
  Update E set E.isFlexible = @Flexi
  from OpenXML(@Index, ''/DocumentElement/Table'')
  With (empAutoID Bigint ''empAutoId'') As xm 
  inner join ta_tbl_employee as E on E.Employee_ID = xm.empAutoID
  Exec sp_xml_removedocument @Index
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeFlexi]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeFlexi]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeFlexi]
@EmployeeID as int,
@Flexi as int
AS
BEGIN
	update ta_tbl_employee set isFlexible=@Flexi where Employee_ID = @EmployeeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_EmployeeOTStatus  
Description		:	To Update the OverTime Status in ta_tbl_processedData  table
Tables Included :	ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		:	A.K.T.MOORTHI
Created On		:	22-July-2013
Modified By		:	A.K.T.MOORTHI
Modified On		:	02-AUG-2013
Description		:	BUG FIXING FOR 0018037 NO.
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
--[Proc_TA_UpdateEmployeeCompOffOTStatus]''<NewDataSet><ColumnValues><Process_Rec_ID>3422</Process_Rec_ID><Employee_ID>12</Employee_ID><Employee_Code_ID>1007</Employee_Code_ID><Date>2015-05-01T00:00:00+05:30</Date><Employee_FirstName>VinojOTCOMPOFF</Employee_FirstName><Level_x0020_Name>Production Erode Branch</Level_x0020_Name><HrsExtra>05:20</HrsExtra><ExtraMins>320</ExtraMins><OverTimeStatus>Forwarded</OverTimeStatus><CompOffEligible>1</CompOffEligible><OTEligible>1</OTEligible><CompOffChecked>0</CompOffChecked><OTChecked>1</OTChecked><Status>Approved</Status><TopLevelID>1</TopLevelID><IsUpdated>U</IsUpdated></ColumnValues></NewDataSet>''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_UpdateEmployeeCompOffOTStatus]
	@Xml XML
As
BEGIN 
	set nocount on
	DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,[Date] varchar(20), HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT, DateToExpired DATETIME, NoOfDays NUMERIC(18,1), RemainingDays NUMERIC(18,1), CompOffSatus VARCHAR(30), TopLevelId INT, UpdatedRow VARCHAR(1))
	DECLARE @Index INT 
	set @Index= 0
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	INSERT INTO @TblRecords(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, TopLevelId)
		SELECT Process_Rec_ID, Employee_Id, convert(varchar(20),[Date]), HrsExtra, ExtraMins, (CASE WHEN CompOffEligible = 1 OR OTEligible = 1 THEN [Status] ELSE ''Pending'' END),
		 CompOffEligible, OTEligible, TopLevelId FROM OPENXML(@Index, ''/NewDataSet/ColumnValues'')
		WITH(
			Process_Rec_ID BIGINT ''Process_Rec_ID'',
			Employee_Id INT ''Employee_ID'',
			[Date] varchar(50) ''Date'',
			HrsExtra VARCHAR(5) ''HrsExtra'',
			ExtraMins INT ''ExtraMins'',
			[Status] VARCHAR(50) ''Status'',
			CompOffEligible BIT ''CompOffChecked'',
			OTEligible BIT ''OTChecked'',
			TopLevelId INT ''TopLevelID''--,
			--UpdateRow VARCHAR(1) ''UpdateRow''
		   ) AS OT 
		ORDER BY OT.[Date]	
	EXEC sp_xml_removedocument @Index
	UPDATE @TblRecords SET 
		DateToExpired = CASE WHEN TR.OverTimeStatus != ''Pending'' 
		AND TR.CompOffEligible = 1 THEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0), CONVERT(datetime,TR.[Date],103)) END,
		--DateToExpired = DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),TR.[Date]),
		--NoOfDays = CASE WHEN TR.OverTimeStatus = ''Approved'' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEDIFF(MI,''00:00'' ,TR.HrsExtra) / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN CAST(DATEDIFF(MI,''00:00'' ,TR.HrsExtra)/ DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) AS NUMERIC(18, 1)) WHEN DATEDIFF(MI,''00:00'' ,TR.HrsExtra)/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' END) END,
		--RemainingDays = CASE WHEN TR.OverTimeStatus = ''Approved'' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEDIFF(MI,''00:00'' ,TR.HrsExtra) / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN CAST(DATEDIFF(MI,''00:00'' ,TR.HrsExtra)/ DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) AS NUMERIC(18, 1)) WHEN DATEDIFF(MI,''00:00'' ,TR.HrsExtra)/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' END) END,
		NoOfDays =	CASE WHEN TR.OverTimeStatus = ''Approved'' AND TR.CompOffEligible = 1 THEN	
										(	CASE	WHEN TR.ExtraMins / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN ''1.0'' 
														WHEN TR.ExtraMins/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' 
											END
										) 
								END,
		RemainingDays = CASE WHEN TR.OverTimeStatus = ''Approved'' AND TR.CompOffEligible = 1 THEN (CASE WHEN TR.ExtraMins / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN ''1.0'' WHEN TR.ExtraMins/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' END) END,
		CompOffSatus = CASE WHEN TR.OverTimeStatus = ''Approved'' AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),CONVERT(datetime,TR.[Date],103)) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END) END
	FROM @TblRecords TR
	INNER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = TR.Process_RecID
	--LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id
	LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = TR.TopLevelId
	INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest)
		SELECT Process_RecID, Employee_Id,CONVERT(datetime,[Date],103), 
		HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, 
		DateToExpired, NoOfDays, RemainingDays, CompOffSatus,0 FROM @TblRecords 
		WHERE Process_RecID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus)
	UPDATE TA_Tbl_OverTimeStatus SET 
		Process_RecID = TR.Process_RecID,
		Employee_Id = TR.Employee_Id,
		[Date] =CONVERT(datetime,TR.[Date],103),
		HrsExtra = TR.HrsExtra,
		ExtraMins = TR.ExtraMins,
		OverTimeStatus = TR.OverTimeStatus,
		CompOffEligible = TR.CompOffEligible,
		OTEligible = TR.OTEligible,
		DateToExpired = TR.DateToExpired,
		NoOfDays = TR.NoOfDays,
		RemainingDays = TR.RemainingDays,
		CompOffSatus = TR.CompOffSatus,
		isRequest=0
	FROM TA_Tbl_OverTimeStatus OTS
	INNER JOIN @TblRecords TR ON TR.Process_RecID = OTS.Process_RecID
	WHERE ISNULL(OTS.OverTimeStatus, ''Pending'') != ''Approved'' AND ISNULL(OTS.CompOffSatus, ''Not Taken'') != ''Taken'' 
	--Added by manikandan.R
	-- On 30-july-2013
	update TA_Tbl_ProcessedData set TA_Tbl_ProcessedData.OvertimeStatus=OS.OverTimeStatus from TA_Tbl_ProcessedData P
	inner join TA_Tbl_OverTimeStatus OS on P.Process_Rec_ID=OS.Process_RecID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExpInfo]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateExpInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateExpInfo]
(
	@InstalledDate as nvarchar(100),
	@DemoExpiryDate as nvarchar(100)
)
AS
BEGIN
	update TA_Tbl_Demo  set  InstalledDate=@InstalledDate,DemoExpiryDate=@DemoExpiryDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateExistingUserStatusFalse]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateExistingUserStatusFalse]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateExistingUserStatusFalse] 
	-- Add the parameters for the stored procedure here	
    @UserId nvarchar(10)    
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ConcurrentUser SET Status = 0 WHERE UserId = @UserId AND Status = 1 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePassword]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePassword]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_UpdatePassword]
(
@username NVARCHAR(10),
@password NVARCHAR(50)
)
AS
BEGIN
	UPDATE TA_Tbl_Employee SET Emp_password=@password  WHERE Employee_Id=@username 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationMaster]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_UpdateLeaveApplicationMaster 323,''To go to temple with my family. (Please consider this as a CL of May-11 Month) ''
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationMaster]  
(
--Proc_TA_UpdateLeaveApplicationMaster   
@LeaveApplication_Id int,
@Reason nvarchar(1000) 
)  
as  
begin
	Set NOCOUNT ON;
  UPDATE TA_Tbl_LeaveApplicationMaster SET Reason=@Reason where LeaveApplication_Id=@LeaveApplication_Id
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationConversation] 
	-- Add the parameters for the stored procedure here
	@leaveApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	SET NOCOUNT ON;
	if(@status=''Resend'')
		begin
			UPDATE TA_Tbl_LeaveApplication SET Status = @status,Remarks = @remarks,Emp_Id = @empAutoId WHERE LeaveApplication_Id = @leaveApplicationId
		end	
	SET @leaveConversationCount = (SELECT COUNT(*) FROM TA_Tbl_LeaveConversation WHERE LeaveApplicationId = @leaveApplicationId)
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_LeaveConversation(LeaveApplicationId,CommentsBy,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@leaveApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId,GETDATE())
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveAnalysisNotes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveAnalysisNotes]
@Opr as varchar(1),  -- U - update , D- Delete
@ID as int,
@Notes as varchar(8000),
@EmpID as int
AS
BEGIN
	if (@Opr=''U'')
		Begin
			update TA_Tbl_LeaveAnalysisNotes set
					Notes = @Notes,
					EmpID = @EmpID			
			Where
					ID = @ID		
		End
	Else
		Begin
			update TA_Tbl_LeaveAnalysisNotes set
					IsDeleted = 1				
			Where			
					ID = @ID		
		End		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <21-06-2016>
-- Description:	<Update the userrights table if client upgrade the latest version>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateLatestVersionDetails_UserRights]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if not exists(select * from sys.tables where name=''Ta_tbl_ExistingRightsDetails'')
    begin
				create table Ta_tbl_ExistingRightsDetails(id	int,groupName	nvarchar(500),groupId	int,
				pageId	float,pageGroupId	int,addPrv	bit,modifyPrv	bit,deletePrv	bit,viewPrv	bit,isDeleted	bit,timeStamp	datetime,employeeId	decimal)
		end
		delete from Ta_tbl_ExistingRightsDetails
		insert into Ta_tbl_ExistingRightsDetails select * from TA_Tbl_userRights
    Create table #TempPage(Autoid int identity(1,1),pageid int,parentid int)
		Insert into #TempPage 
		select pageId,parentId from TA_Tbl_Page 
		Declare @Start int
		Declare @TotRecord int
		Declare @parentId int
		Declare @pageid int
		set @Start=1
		set @TotRecord=(select COUNT(*) from #TempPage)
		while @Start<=@TotRecord
		begin
			select @parentId=parentid,@pageid=pageid from #TempPage where Autoid=@Start
			if(@pageid in(177))
			begin
				set @parentId=177
			end
			if(@pageid in(179))
			begin
				set @parentId=179
			end
			if(@pageid in(246))
			begin
				set @parentId=246
			end
			update TA_Tbl_userRights set pageGroupId=@parentId where pageId=@pageid
			set @Start=@Start+1
		end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCountStandard]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRowsCountStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name> Ta_Tbl_PageRedirectStandard
-- Create date: <Create Date,,> TA_Tbl_PageMandatoryFlagStandard
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRowsCountStandard] 
AS
BEGIN
	DECLARE cur CURSOR STATIC LOCAL FOR
	SELECT TableName,active,Module FROM Ta_Tbl_PageRedirectStandard
	declare @TableNameTemp as varchar(200)
	declare @ActiveTemp as varchar(200)
	declare @ModuleTemp as varchar(500)
	declare @sql as varchar(1000)
	declare @Flag as int
	OPEN cur
	WHILE 1 = 1
	BEGIN
		FETCH cur INTO @TableNameTemp,@ActiveTemp,@ModuleTemp
		IF @@fetch_status <> 0
			BREAK
		if (@ActiveTemp=1)
		Begin
			set @sql =  ''update Ta_Tbl_PageRedirectStandard set rows=temp.RecCount from (select * from (''
			set @sql = @sql + '' select count(*) as RecCount   from    '' + @TableNameTemp
			set @sql = @sql +  '' )A)Temp where Active=1 and Tablename= '''''' + @TableNameTemp + '''''' ''		
			exec (@sql)
		End
	END
	update Ta_Tbl_PageRedirectStandard set rows=temp.RecCount from (
	select * from ( 
				select count(*) as RecCount   from    TA_Tbl_Employee where employee_firstname <> ''Administrator''
	 )A)Temp where Active=1 and Tablename= ''TA_Tbl_Employee'' 
	declare @RecCount as int
	set @RecCount = (select count(*) from Ta_Tbl_PageRedirectStandard where (Rows =0 or Rows is null) and Active=1)
	Declare @RecTotal as int 
	set @RecTotal = (select count(*) from TA_Tbl_PageMandatoryFlagStandard)
	if @RecCount=0
		Begin	
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlagStandard set MandatoryChecking =0
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlagStandard (MandatoryChecking) values (0)
				End
		End
	Else
		Begin
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlagStandard set MandatoryChecking =1
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlagStandard (MandatoryChecking) values (1)
				End
		End
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRowsCount]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRowsCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRowsCount] 
AS
BEGIN
	DECLARE cur CURSOR STATIC LOCAL FOR
	SELECT TableName,active,Module FROM ta_tbl_pageredirect
	declare @TableNameTemp as varchar(200)
	declare @ActiveTemp as varchar(200)
	declare @ModuleTemp as varchar(500)
	declare @sql as varchar(1000)
	declare @Flag as int
	OPEN cur
	WHILE 1 = 1
	BEGIN
		FETCH cur INTO @TableNameTemp,@ActiveTemp,@ModuleTemp
		IF @@fetch_status <> 0
			BREAK
		if (@ActiveTemp=1)
		Begin
			set @sql =  ''update ta_tbl_pageredirect set rows=temp.RecCount from (select * from (''
			set @sql = @sql + '' select count(*) as RecCount   from    '' + @TableNameTemp
			set @sql = @sql +  '' )A)Temp where Active=1 and Tablename= '''''' + @TableNameTemp + '''''' ''		
			exec (@sql)
		End
	END
	update ta_tbl_pageredirect set rows=temp.RecCount from (
	select * from ( 
				select count(*) as RecCount   from    TA_Tbl_Employee where employee_firstname <> ''Administrator''
	 )A)Temp where Active=1 and Tablename= ''TA_Tbl_Employee'' 
	declare @RecCount as int
	set @RecCount = (select count(*) from ta_tbl_pageredirect where (Rows =0 or Rows is null) and Active=1)
	Declare @RecTotal as int 
	set @RecTotal = (select count(*) from TA_Tbl_PageMandatoryFlag)
	if @RecCount=0
		Begin	
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlag set MandatoryChecking =0
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlag (MandatoryChecking) values (0)
				End
		End
	Else
		Begin
			if (@RecTotal>0)
				Begin
					update TA_Tbl_PageMandatoryFlag set MandatoryChecking =1
				End
			Else
				Begin
					insert into TA_Tbl_PageMandatoryFlag (MandatoryChecking) values (1)
				End
		End
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateRawDataFlag]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateRawDataFlag]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Update Raw data flag>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateRawDataFlag]
	-- Add the parameters for the stored procedure here
	@CLK_ID bigint,
	@ReasonId int,
	@Clk_Flag int,
	@Clk_Process int,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''C'')
	begin
		update TA_Tbl_Clk_RawData set Clk_Flag =@Clk_Flag,Clk_Process = @Clk_Process,ReasonId=@ReasonId where Clk_Id = @CLK_ID
	end
	if(@Type=''M'')
	begin
		UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''Y'' WHERE ManualTimeEntry_Id = @CLK_ID
	end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessFlagForBonusLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateProcessFlagForBonusLeave ''12121'',''1/1/2009 12:00:00 AM''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessFlagForBonusLeave] 
	-- Add the parameters for the stored procedure here
	@employeeCodeId nvarchar(25), 
	@processFromDate nvarchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	update ta_tbl_processeddata set processflag = 0 where employee_code_id = @employeeCodeId and date >= CONVERT(DATETIME,'''' + cast(@processFromDate as nvarchar(25))  + '''', 102)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessflag]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessflag]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 12.06 PM>
-- Description:	<Update process flag from previous to next date>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessflag]
	@inClk_EmpId varchar(50),
	@inClockDate varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0 where Employee_Code_Id = @inClk_EmpId 
	and Date BETWEEN DATEADD(d,-1,convert(datetime,@inClockDate)) AND DATEADD(d,1,convert(datetime,@inClockDate))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlagAfterDeletion]
	-- Add the parameters for the stored procedure here	
	@EmployeeId nvarchar(20),
	@FromDate DateTime,
	@ToDate DateTime,
	@ProcessFlag int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @IsDeleted BIT
	SET @IsDeleted=0
	DECLARE @Employee_Code_Id VARCHAR(20)
	DECLARE @SwipeCardNo AS NVARCHAR(20)
	DECLARE @dtFROMDate AS DATETIME
	Declare @count int
	Declare @Start int
	set @Start=1
	set @count=(select count(EmployeeId) from TA_Tbl_TempShiftAllocation)
	CREATE TABLE #TA_Tbl_TempShiftAllocation
	(
		AutoId int identity(1,1),
		[EmpID] [int] NOT NULL,
		[EmployeeId] [nvarchar](50) NOT NULL,
		[EmployeeName] [nvarchar](50) NOT NULL,
		[LoginEmployeeId] [int] NOT NULL
	)
	insert into #TA_Tbl_TempShiftAllocation
	select * from TA_Tbl_TempShiftAllocation
	while @count>=@Start
		begin
			set @Employee_Code_Id=(select EmployeeId from #TA_Tbl_TempShiftAllocation where AutoId=@Start)
			--SET @Employee_Code_Id = (SELECT Employee_code_id  FROM Ta_tbl_Employee where Ta_tbl_Employee.Employee_id=@EmployeeID)
			SET @SwipeCardNo = (SELECT SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id and (InActiveDate is null or
			 InActiveDate='''' or InActiveDate>=GETDATE()) and isDeleted=0)   
			DELETE FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id = @SwipeCardNo AND Date BETWEEN @FROMDate AND @ToDate  
			DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_Date BETWEEN @FROMDate AND @ToDate 
			SET @dtFROMDate=@FROMDate
			WHILE(@dtFROMDate<=@ToDate)
				BEGIN
					DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_InDate=@dtFROMDate		
					DELETE FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @SwipeCardNo AND Clk_OutDate=@dtFROMDate and Clk_InDate is null			
					UPDATE TA_Tbl_ManualTimeEntry set Clk_Process=''N'' 
					where (ManualTimeEntry_InDate = @dtFROMDate or ManualTimeEntry_OutDate = @dtFROMDate)		
					SET @dtFROMDate=DateAdd(d,1,@dtFROMDate)
				END				
			UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 WHERE Clk_CardId = @SwipeCardNo AND Clk_Date BETWEEN DateAdd(d,-1,@FROMDate) AND DateAdd(d,1,@ToDate)  
			set @Start=@Start+1			
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedDataFlag]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedDataFlag]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_UpdateProcessedDataFlag 0,''07/20/2011'',''07/20/2011'',0
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessedDataFlag]
(
  @EmployeeId nvarchar(20),
  @FromDate DateTime,
  @ToDate DateTime,
  @ProcessFlag int
)
AS
begin
	if(@EmployeeId <> ''0'')
		BEGIN
			declare @SwipeCardNo as nvarchar(20)
			set @SwipeCardNo=(select SwipeCardNo from TA_TBL_Employee where Employee_Id =@EmployeeId)
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = @ProcessFlag
			WHERE Employee_Code_Id = @SwipeCardNo 
			AND [Date] between @FromDate and @ToDate
		END
	else
		BEGIN
			UPDATE TA_Tbl_ProcessedData SET ProcessFlag = @ProcessFlag
			WHERE [Date] between @FromDate and @ToDate
		END
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateProcessedData]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_UpdateProcessedData] 
(
  @FirstIn nvarchar(25),
  @LastOut nvarchar(25),
  @ShiftId int,
  @TotalWorkHours nvarchar(10),
  @HrsOT nvarchar(10),
  @NorOT nvarchar(10),
  @WeekOffOT nvarchar(10),
  @HoliOT nvarchar(10),
  @EarlyExit nvarchar(10),
  @LateInTime nvarchar(10),
  @WorkHrs nvarchar(10),
  @LessHours nvarchar(10),
  @ExtraHours nvarchar(10),
  @LateInMins float,
  @EarlyOutMins float,
  @OTmins float,
  @Process_Rec_ID BIGINT
)
AS
     UPDATE TA_Tbl_ProcessedData SET InTime = @FirstIn,OutTime = @LastOut,Shift_Id = @ShiftId,HrsWork = @TotalWorkHours,HrsOT = @HrsOT, NormOT = @NorOT, OffOT = @WeekOffOT, HolOT = @HoliOT,
     EarlyOut = @EarlyExit, LateIn = @LateInTime, Attendance = ''Present'', WorkHrs = @WorkHrs, HrsLess = @LessHours,HrsExtra = @ExtraHours,LateInMins = @LateInMins,EarlyOutMins = @EarlyOutMins,OtMins = @OTmins,ProcessFlag = 1                                 
     WHERE Process_Rec_ID = @Process_Rec_ID
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePerShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePerShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_UpdatePerShiftAllocation] 
(@EmpId int,@year int,@month int,@Day1Shift int,@Day2Shift int,@Day3Shift int,@Day4Shift int,@Day5Shift int,@Day6Shift int,@Day7Shift int,@Day8Shift int,@Day9Shift int,@Day10Shift int,@Day11Shift int,@Day12Shift int,@Day13Shift int,@Day14Shift int,@Day15Shift int,@Day16Shift int,@Day17Shift int,@Day18Shift int,@Day19Shift int,@Day20Shift int,@Day21Shift int,@Day22Shift int,@Day23Shift int,@Day24Shift int,@Day25Shift int,@Day26Shift int,@Day27Shift int,@Day28Shift int,@Day29Shift int,@Day30Shift int,@Day31Shift int)
AS
	BEGIN 
		UPDATE TA_Tbl_TemporaryShiftAllocation SET Day1Shift=@Day1Shift,Day2Shift=@Day2Shift,Day3Shift=@Day3Shift,Day4Shift=@Day4Shift,Day5Shift=@Day5Shift,Day6Shift=@Day6Shift,Day7Shift=@Day7Shift,Day8Shift=@Day8Shift,Day9Shift=@Day9Shift,Day10Shift=@Day10Shift,Day11Shift=@Day11Shift,Day12Shift=@Day12Shift,Day13Shift=@Day13Shift,Day14Shift=@Day14Shift,Day15Shift=@Day15Shift,Day16Shift=@Day16Shift,Day17Shift=@Day17Shift,Day18Shift=@Day18Shift,Day19Shift=@Day19Shift,Day20Shift=@Day20Shift,Day21Shift=@Day21Shift,Day22Shift=@Day22Shift,Day23Shift=@Day23Shift,Day24Shift=@Day24Shift,Day25Shift=@Day25Shift,Day26Shift=@Day26Shift,Day27Shift=@Day27Shift,Day28Shift=@Day28Shift,Day29Shift=@Day29Shift,Day30Shift=@Day30Shift,Day31Shift=@Day31Shift WHERE [Year]=@year and [Month]=@month and  EmployeeId=@EmpId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionSanction]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_UpdatePermissionSanction
Description		:	Update Permission Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_UpdatePermissionSanction]
	@Permission_Id int,
	@Permission_Status nvarchar(20),
	@Remarks nvarchar(300),
	@auEmpId int  
as
BEGIN
	declare @sql nvarchar(2000)
	set nocount on;
		UPDATE TA_Tbl_Permission set Permission_Status=@Permission_Status ,Remarks= @Remarks ,Emp_Id= cast(@auEmpId as nvarchar(20)) Where Permission_Id= cast(@Permission_Id as nvarchar(25))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTypeDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_SelectTypeDetails]    
(    
	@TYPE CHAR(1)='''',    
	@TypeId INT,
	@UserGroupName nVarchar(250)    
)    
AS    
BEGIN    
IF (@TYPE=''A'')    
BEGIN
   IF(@UserGroupName = ''SuperAdmin'')
      BEGIN 
		SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type
      END
   ELSE
      BEGIN   
  		SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
  		WHERE IsDeleted=0    
      END
 END    
-- P Refers Particular   
ELSE IF (@TYPE=''P'')    
 BEGIN
     IF(@UserGroupName = ''SuperAdmin'')
      BEGIN 
        SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
        WHERE TypeId=@TypeId
      END
    ELSE
      BEGIN    
        SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  
        WHERE TypeId=@TypeId AND IsDeleted=0    
      END
 END    
ELSE If (@TYPE=''I'')    
  BEGIN    
	SELECT TypeId,TypeName,IsDeleted,IsFlexible FROM TA_Tbl_Type  WHERE IsDeleted=0 
  END    
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectType]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectType]	
	@TypeID as int
AS
BEGIN
	select 
		TypeName,TypeId,isnull(IsFlexible,0) ''IsFlexible''
	From Ta_tbl_Type where TypeId=@TypeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails_CMITech]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetails_CMITech]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'create PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails_CMITech] 
AS
BEGIN
			SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,
			case when T.IsDeleted=1 then ''True'' else ''False'' end IsDeleted
			FROM TA_Tbl_Terminal T LEFT OUTER JOIN TA_tbl_TerminalDatatype TD ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
			Where Terminal_ReaderID not in(''787'',''788'')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetails] 
(  
	@Type CHAR(1),  
	@TerminalID INT=0,  
	@UserGroupName nVarchar(50)
)  
AS
BEGIN
	DECLARE @dynamicquery VARCHAR(MAX)
	IF(@Type=''A'')  
	BEGIN
		set @dynamicquery=''
			SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name,T.Terminal_Description,TD.Raw_Data_Format,
			case when T.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted
			FROM TA_Tbl_Terminal T LEFT OUTER JOIN TA_tbl_TerminalDatatype TD ON TD.TerminalDatatype_ID=T.TerminalDatatype_ID
			Where Terminal_ReaderID not in(''''787'''',''''788'''')''
		IF(@UserGroupName = ''SuperAdmin'')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN
			Execute(@dynamicquery+ '' and T.IsDeleted=0'')
		END
	END    
	IF(@Type=''P'')  
	BEGIN
		set @dynamicquery=''SELECT Terminal_Id, Terminal_ReaderID, Terminal_Name, Terminal_Description, TerminalDatatype_ID, Time_Stamp, Emp_ID, 
			case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted  FROM TA_Tbl_Terminal Where Terminal_ReaderID not in(''''787'''',''''788'''')
			and Terminal_Id =''+convert(varchar(20),@TerminalID)
		IF(@UserGroupName = ''SuperAdmin'')
		BEGIN
			Execute(@dynamicquery)
		END
		ELSE
		BEGIN   
			Execute(@dynamicquery + '' AND IsDeleted=0'')
		END
	END
	IF(@Type=''C'')  
	BEGIN   
		Select Count(TerminalDatatype_ID) as TerminalCount from TA_Tbl_Terminal Where TerminalDatatype_ID =@TerminalID  and Terminal_ReaderID not in(''787'',''788'')
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettings]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectYearSettings]    
AS    
select YearSettings_Id,Fromdate,Todate,StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + '' - '' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting  from Ta_Tbl_Yearsetting  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingForLeaveReport]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettingForLeaveReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectYearSettingForLeaveReport]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select convert(varchar(20),FromDate,111) as YearSettingFromDate,CONVERT(varchar(20),ToDate,111) as YearSettingToDate
	from Ta_Tbl_Yearsetting where IsActive=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSettingbyId]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSettingbyId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectYearSettingbyId]      
(  
@YearSettingId int  
)  
AS      
select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + '' - '' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting ,     
convert(varchar,fromdate,102) as fromdate,convert(varchar,todate,102) as todate
from Ta_Tbl_Yearsetting    where yearsettings_Id=@YearSettingId  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearSetting]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearSetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectYearSetting]
AS
BEGIN
	SET NOCOUNT ON;
	select StartMonth+ space(1)+ cast(StartYear as nvarchar(20)) + '' - '' +EndMonth+ space(1)+ cast(EndYear as nvarchar(20))as YearSetting,
	convert(nvarchar(20),FromDate,102) as YearSettingFromDate,convert(nvarchar(20),ToDate,102) as YearSettingToDate, 
	YearSettings_Id, StartMonth, StartYear, EndMonth, EndYear, FromDate, ToDate, TimeStamp, Emp_Id, IsActive from Ta_Tbl_Yearsetting where IsActive=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_RawData]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_RawData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_RawData ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_RawData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS  
BEGIN
	--create table #TempSwipeCardNo(SwipeCardNo nvarchar(20)) 
	----#TempSwipeCardNo Indexes    
	--/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 05/27/2009 16:28:22 ******/  
	--CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	--(  
	-- [SwipeCardNo] ASC  
	--) ON [PRIMARY]  
	-- --select * from TA_Tbl_TempShiftAllocation
	--insert into #TempSwipeCardNo SELECT SwipeCardNo FROM TA_Tbl_Employee 
	--inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	--where SwipeCardNo is not null and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0,ReasonId = 0 FROM TA_Tbl_Employee 
	inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	inner join TA_Tbl_Clk_RawData on TA_Tbl_Employee.SwipeCardNo = TA_Tbl_Clk_RawData.Clk_CardId 
	AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) and ReasonId!=6
	where TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	-- and isnull(ReasonId,0)=0
	--drop table #TempSwipeCardNo
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_ProcessedData ''01/01/2011 12:00:00 AM'',''04/30/2011 12:00:00 AM'',''1''
--update a set day1shift= 0 from TA_Tbl_PermanentShiftAllocation  a
--inner join TA_Tbl_TempShiftAllocation b on b.EmpID = a.EmployeeId
--inner join TA_Tbl_AutoShiftConfiguration c on c.EmployeeId = a.EmployeeId
--where
--month=8 and year=2019 
--and (c.ShiftId1!=0 or c.ShiftId2!=0 or c.ShiftId3!=0 or c.ShiftId4!=0 or c.ShiftId5!=0)
--Proc_TA_ShiftAllocReprocess_ProcessedData ''2020-01-01 00:00:00.000'',''2020-12-31 00:00:00.000'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ProcessedData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS
BEGIN	
	--Autoshift employee Reprocessing
	set @Fromdate= @FromDate
	set @todate= dateadd(DAY,1,@ToDate) 
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	declare @DynamicQuery varchar(max)
	set @DynamicQuery = '''';
	while (@Fromdate < @todate)
	Begin
		if (@Fromdate < @todate)
		begin	
			set @day =DATEPART(DAY,@Fromdate)
			SET @YEAR=DATEPART(YEAR,@Fromdate)
			SET @MONTH=DATEPART(MONTH,@Fromdate)	
			set @DynamicQuery=''''
			SET @DynamicQuery = @DynamicQuery +'' update a set day''+CONVERT(VARCHAR(2),@day)+''shift= 0 from TA_Tbl_PermanentShiftAllocation  a
			inner join TA_Tbl_TempShiftAllocation b on b.EmpID = a.EmployeeId
			inner join TA_Tbl_AutoShiftConfiguration c on c.EmployeeId = a.EmployeeId
			where
			month=''+ CONVERT(VARCHAR(2),@month)  +''and year=''+CONVERT(VARCHAR(4),@year)+'' 
			and (c.ShiftId1!=0 or c.ShiftId2!=0 or c.ShiftId3!=0 or c.ShiftId4!=0 or c.ShiftId5!=0)''
			exec (@DynamicQuery)
			set @Fromdate =  dateadd(DAY,1,@Fromdate)			
			continue;
		End
		else
		begin
			break;
		End
	End
	set @DynamicQuery=''''
	-- Non Auto shift employee
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_TempShiftAllocation
	inner join TA_Tbl_Employee on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	inner join TA_Tbl_ProcessedData on TA_Tbl_Employee.SwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id
	where (Date BETWEEN @FromDate AND @ToDate)
	and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_ManualEntry ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ManualEntry]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @LoginEmployeeId varchar(50)   
)  
AS  
BEGIN
	SET NOCOUNT ON;
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' from TA_Tbl_TempShiftAllocation
	inner join TA_Tbl_Employee on TA_Tbl_TempShiftAllocation.EmpID = TA_Tbl_Employee.Employee_Id
	inner join TA_Tbl_ManualTimeEntry on TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id 
	AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	where TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_ClockDetails ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocReprocess_ClockDetails]  
(   
	 @FromDate Datetime,  
	 @ToDate Datetime,
	 @LoginEmployeeId varchar(50)
)  
AS  
BEGIN
	DECLARE @SwipeCardNo AS nvarchar(20)  
	DECLARE @Employee_Code_Id AS nvarchar(20)  
	create table #TempSwipeCardNo(SwipeCardNo nvarchar(20)) 
	--#TempSwipeCardNo Indexes    
	/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 05/27/2009 16:28:22 ******/  
	CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	(  
		[SwipeCardNo] ASC  
	) ON [PRIMARY]  
	 --select * from TA_Tbl_TempShiftAllocation
	insert into #TempSwipeCardNo SELECT SwipeCardNo FROM TA_Tbl_Employee
	inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id 
	where SwipeCardNo is not null and TA_Tbl_TempShiftAllocation.LoginEmployeeId=@LoginEmployeeId
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	--Matched Punches
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM ta_tbl_MatchedPunches FROM ta_tbl_MatchedPunches inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=ta_tbl_MatchedPunches.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	drop table #TempSwipeCardNo
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectVersion]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectVersion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectVersion] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select top 1 * from ta_tbl_version order by VersionId desc 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUserName]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectUserName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_SelectUserName]
(
	@username NVARCHAR(10),
	@password NVARCHAR(50)
)
AS
BEGIN
	Select Employee_Id,Employee_FirstName + '' '' + Employee_LastName AS ''Employee Name'',
	Employee_Code_Id,EmailId,Photo  
	From TA_Tbl_Employee WHERE UserName=@username AND Emp_password=@password 
	AND IsDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllocationReprocess]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllocationReprocess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocationReprocess ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''11442,3480,3482,3483,3490,3500,3503,3537,3538,3539,3657,3665,4441,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457,11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,11470,11471,11472,11473,11474,11475,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486,11487,11488,11489,11490,11491,11492,11493,11494,11495,11496,11497,11498,11499,11500,11501,11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517,11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,11530,11531,11532,11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548,11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578,11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,11592,11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,11605,11606,11607,11608,11609,11610,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622,11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638,11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654,11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670,11671,11672,11673,11674,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685,11686,11687,11688,11689,11690,11691,11692,11693,11694,11695,11696,11697,11698,11699,11700,11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716,11717,11718,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,11741,11742,11743,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776,11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,11791,11792,11793,11794,11795,11796,11797,11798,11799,11800,11801,11802,11803,11804,11805,11806,11807,11808,11809,11810,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821,11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,11835,11836,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850,11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866,11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882,11883,11884,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897,11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913,11914,11915,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928,11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944,11945,11946,11947,11948,11949,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959,11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975,11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,11988,11989,11990,11991,11992,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005,12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021,12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037,12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053,12054,12055,12056,12057,12058,12059,12060,12061,12062,12063,12064,12065,12066,12067,12068,12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084,12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100,12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116,12117,12118,12119,12120,12121,12122,12123,12124,12125,12126,12127,12128,12129,12130,12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146,12147,12148,12149,12150,12151,12152,12153,12154,12155,12156,12157,12158,12159,12160,12161,12162,12163,12164,12165,12166,12167,12168,12169,12170,12171,12172,12173,12174,12175,12176,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188,12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204,12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220,12221,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,12246,12247,12248,12249,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264,12265,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278,12279,12280,12281,12282,12283,12284,12285,12286,12287,12288,12289,12290,12291,12292,12293,12294,12295,12296,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308,12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,12320,12321,12322,12323,12324,12325,12326,12327,12328,12329,12330,12331,12332,12333,12334,12335,12336,12337,12338,12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,12436,12437,12438,12439,12440,12441,12442,12443,12444,12445,12446,12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539,12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600,12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616,12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632,12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,12647,12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663,12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679,12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695,12696,12697,12698,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710,12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726,12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742,12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758,12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774,12775,12776,12777,12778,12779,12780,12781,12782,12783,12784,12785,12786,12787,12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803,12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819,12820,12821,12822,12823,12824,12825,12826,12827,12828,12829,12830,12831,12832,12833,12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849,12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,12862,12863,12864,12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880,12881,12882,12883,12884,12885,12886,12887,12888,12889,12890,12891,12892,12893,12894,12895,12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911,12912,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926,12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942,12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,12957,12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973,12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989,12990,12991,12992,12993,12994,12995,12996,12997,12998,12999,13000,13001,13002,13003,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018,13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,13030,13031,13032,13033,13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049,13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065,13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081,13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097,13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113,13114,13115,13116,13117,13118,13119,13120,13121,13122,13123,13124,13125,13126,13127,13128,13129,13130,13131,13132,13133,13134,13135,13136,13137,13138,13139,13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155,13156,13157,13158,13159,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170,13171,13172,13173,13174,13175,13176,13177,13178,13179,13180,13181,13182,13183,13184,13185,13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201,13202,13203,13204,13205,13206,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216,13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,13228,13229,13230,13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,13241,13242,13243,13244,13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260,13261,13262,13263,13264,13265,13266,13267,13268,13269,13270,13271,13272,13273,13274,13275,13276,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290,13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,13303,13304,13305,13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321,13322,13323,13324,13325,13326,13327,13328,13329,13330,13331,13332,13333,13334,13335,13336,13337,13338,13339,13340,13341,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351,13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382,13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398,13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414,13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430,13431,13432,13433,13434,13435,13436,13437,13438,13439,13440,13441,13442,13443,13444,13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,13458,13459,13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,13471,13472,13473,13474,13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490,13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506,13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522,13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538,13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554,13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570,13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586,13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602,13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618,13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634,13635,13636,13637,13638,13639,13640,13641,13642,13643,13644,13645,13646,13647,13648,13649,13650,13651,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664,13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680,13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696,13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712,13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728,13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744,13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760,13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,13775,13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791,13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807,13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823,13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839,13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855,13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871,13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887,13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903,13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919,13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935,13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951,13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967,13968,13969,13970,13971,13972,13973,13974,13975,13976,13977,13978,13979,13980,13981,13982,13983,13984,13985,13986,13987,13988,13989,13990,13991,13992,13993,13994,13995,13996,13997,13998,13999,14000,14001,14002,14003,14004,14005,14006,14007,14008,14009,14010,14011,14012,14013,14014,14015,14016,14017,14018,14019,14020,14021,14022,14023,14024,14025,14026,14027,14028,14029,14030,14031,14032,14033,14034,14035,14036,14037,14038,14039,14040,14041,14042,14043,14044,14045,14046,14047,14048,14049,14050,14051,14052,14053,14054,14055,14056,14057,14058,14059,14060,14061,14062,14063,14064,14065,14066,14067,14068,14069,14070,14071,14072,14073,14074,14075,14076,14077,14078,14079,14080,14081,14082,14083,14084,14085,14086,14087,14088,14089,14090,14091,14092,14093,14094,14095,14096,14097,14098,14099,14100,14101,14102,14103,14104,14105,14106,14107,14108,14109,14110,14111,14112,14113,14114,14115,14116,14117,14118,14119,14120,14121,14122,14123,14124,14125,14126,14127,14128,14129,14130,14131,14132,14133,14134,14135,14136,14137,14138,14139,14140,14141,14142,14143,14144,14145,14146,14147,14148,14149,14150,14151,14152,14153,14154,14155,14156,14157,14158,14159,14160,14161,14162,14163,14164,14165,14166,14167,14168,14169,14170,14171,14172,14173,14174,14175,14176,14177,14178,14179,14180,14181,14182,14183,14184,14185,14186,14187,14188,14189,14190,14191,14192,14193,14194,14195,14196,14197,14198,14199,14200,14201,14202,14203,14204,14205,14206,14207,14208,14209,14210,14211,14212,14213,14214,14215,14216,14217,14218,14219,14220,14221,14222,14223,14224,14225,14226,14227,14228,14229,14230,14231,14232,14233,14234,14235,14236,14237,14238,14239,14240,14241,14242,14243,14244,14245,14246,14247,14248,14249,14250,14251,14252,14253,14254,14255,14256,14257,14258,14259,14260,14261,14262,14263,14264,14265,14266,14267,14268,14269,14270,14271,14272,14273,14274,14275,14276,14277,14278,14279,14280,14281,14282,14283,14284,14285,14286,14287,14288,14289,14290,14291,14292,14293,14294,14295,14296,14297,14298,14299,14300,14301,14302,14303,14304,14305,14306,14307,14308,14309,14310,14311,14312,14313,14314,14315,14316,14317,14318,14319,14320,14321,14322,14323,14324,14325,14326,14327,14328,14329,14330,14331,14332,14333,14334,14335,14336,14337,14338,14339,14340,14341,14342,14343,14344,14345,14346,14347,14348,14349,14350,14351,14352,14353,14354,14355,14356,14357,14358,14359,14360,14361,14362,14363,14364,14365,14366,14367,14368,14369,14370,14371,14372,14373,14374,14375,14376,14377,14378,14379,14380,14381,14382,14383,14384,14385,14386,14387,14388,14389,14390,14391,14392,14393,14394,14395,14396,14397,14398,14399,14400,14401,14402,14403,14404,14405,14406,14407,14408,14409,14410,14411,14412,14413,14414,14415,14416,14417,14418,14419,14420,14421,14422,14423,14424,14425,14426,14427,14428,14429,14430,14431,14432,14433,14434,14435,14436,14437,14438,14439,14440,14441,14442,14443,14444,14445,14446,14447,14448,14449,14450,14451,14452,14453,14454,14455,14456,14457,14458,14459,14460,14461,14462,14463,14464,14465,14466,14467,14468,14469,14470,14471,14472,14473,14474,14475,14476,14477,14478,14479,14480,14481,14482,14483,14484,14485,14486,14487,14488,14489,14490,14491,14492,14493,14494,14495,14496,14497,14498,14499,14500,14501,14502,14503,14504,14505,14506,14507,14508,14509,14510,14511,14512,14513,14514,14515,14516,14517,14518,14519,14520,14521,14522,14523,14524,14525,14526,14527,14528,14529,14530,14531,14532,14533,14534,14535,14536,14537,14538,14539,14540,14541,14542,14543,14544,14545,14546,14547,14548,14549,14550,14551,14552,14553,14554,14555,14556,14557,14558,14559,14560,14561,14562,14563,14564,14565,14566,14567,14568,14569,14570,14571,14572,14573,14574,14575,14576,14577,14578,14579,14580,14581,14582,14583,14584,14585,14586,14587,14588,14589,14590,14591,14592,14593,14594,14595,14596,14597,14598,14599,14600,14601,14602,14603,14604,14605,14606,14607,14608,14609,14610,14611,14612,14613,14614,14615,14616,14617,14618,14619,14620,14621,14622,14623,14624,14625,14626,14627,14628,14629,14630,14631,14632,14633,14634,14635,14636,14637,14638,14639,14640,14641,14642,14643,14644,14645,14646,14647,14648,14649,14650,14651,14652,14653,14654,14655,14656,14657,14658,14659,14660,14661,14662,14663,14664,14665,14666,14667,14668,14669,14670,14671,14672,14673,14674,14675,14676,14677,14678,14679,14680,14681,14682,14683,14684,14685,14686,14687,14688,14689,14690,14691,14692,14693,14694,14695,14696,14697,14698,14699,14700,14701,14702,14703,14704,14705,14706,14707,14708,14709,14710,14711,14712,14713,14714,14715,14716,14717,14718,14719,14720,14721,14722,14723,14724,14725,14726,14727,14728,14729,14730,14731,14732,14733,14734,14735,14736,14737,14738,14739,14740,14741,14742,14743,14744,14745,14746,14747,14748,14749,14750,14751,14752,14753,14754,14755,14756,14757,14758,14759,14760,14761,14762,14763,14764,14765,14766,14767,14768,14769,14770,14771,14772,14773,14774,14775,14776,14777,14778,14779,14780,14781,14782,14783,14784,14785,14786,14787,14788,14789,14790,14791,14792,14793,14794,14795,14796,14797,14798,14799,14800,14801,14802,14803,14804,14805,14806,14807,14808,14809,14810,14811,14812,14813,14814,14815,14816,14817,14818,14819,14820,14821,14822,14823,14824,14825,14826,14827,14828,14829,14830,14831,14832,14833,14834,14835,14836,14837,14838,14839,14840,14841,14842,14843,14844,14845,14846,14847,14848,14849,14850,14851,14852,14853,14854,14855,14856,14857,14858,14859,14860,14861,14862,14863,14864,14865,14866,14867,14868,14869,14870,14871,14872,14873,14874,14875,14876,14877,14878,14879,14880,14881,14882,14883,14884,14885,14886,14887,14888,14889,14890,14891,14892,14893,14894,14895,14896,14897,14898,14899,14900,14901,14902,14903,14904,14905,14906,14907,14908,14909,14910,14911,14912,14913,14914,14915,14916,14917,14918,14919,14920,14921,14922,14923,14924,14925,14926,14927,14928,14929,14930,14931,14932,14933,14934,14935,14936,14937,14938,14939,14940,14941,14942,14943,14944,14945,14946,14947,14948,14949,14950,14951,14952,14953,14954,14955,14956,14957,14958,14959,14960,14961,14962,14963,14964,14965,14966,14967,14968,14969,14970,14971,14972,14973,14974,14975,14976,14977,14978,14979,14980,14981,14982,14983,14984,14985,14986,14987,14988,14989,14990,14991,14992,14993,14994,14995,14996,14997,14998,14999,15000,15001,15002,15003,15004,15005,15006,15007,15008,15009,15010,15011,15012,15013,15014,15015,15016,15017,15018,15019,15020,15021,15022,15023,15024,15025,15026,15027,15028,15029,15030,15031,15032,15033,15034,15035,15036,15037,15038,15039,15040,15041,15042,15043,15044,15045,15046,15047,15048,15049,15050,15051,15052,15053,15054,15055,15056,15057,15058,15059,15060,15061,15062,15063,15064,15065,15066,15067,15068,15069,15070,15071,15072,15073,15074,15075,15076,15077,15078,15079,15080,15081,15082,15083,15084,15085,15086,15087,15088,15089,15090,15091,15092,15093,15094,15095,15096,15097,15098,15099,15100,15101,15102,15103,15104,15105,15106,15107,15108,15109,15110,15111,15112,15113,15114,15115,15116,15117,15118,15119,15120,15121,15122,15123,15124,15125,15126,15127,15128,15129,15130,15131,15132,15133,15134,15135,15136,15137,15138,15139,15140,15141,15142,15143,15144,15145,15146,15147,15148,15149,15150,15151,15152,15153,15154,15155,15156,15157,15158,15159,15160,15161,15162,15163,15164,15165,15166,15167,15168,15169,15170,15171,15172,15173,15174,15175,15176,15177,15178,15179,15180,15181,15182,15183,15184,15185,15186,15187,15188,15189,15190,15191,15192,15193,15194,15195,15196,15197,15198,15199,15200,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15238,15239,15240,15241,15242,15243,15244,15245,15246,15247,15248,15249,15250,15251,15252,15253,15254,15255,15256,15257,15258,15259,15260,15261,15262,15263,15264,15265,15266,15267,15268,15269,15270,15271,15272,15273,15274,15275,15276,15277,15278,15279,15280,15281,15282,15283,15284,15285,15286,15287,15288,15289,15290,15291,15292,15293,15294,15295,15296,15297,15298,15299,15300,15301,15302,15303,15304,15305,15306,15307,15308,15309,15310,15311,15312,15313,15314,15315,15316,15317,15318,15319,15320,15321,15322,15323,15324,15325,15326,15327,15328,15329,15330,15331,15332,15333,15334,15335,15336,15337,15338,15339,15340,15341,15342,15343,15344,15345,15346,15347,15348,15349,15350,15351,15352,15353,15354,15355,15356,15357,15358,15359,15360,15361,15362,15363,15364,15365,15366,15367,15368,15369,15370,15371,15372,15373,15374,15375,15376,15377,15378,15379,15380,15381,15382,15383,15384,15385,15386,15387,15388,15389,15390,15391,15392,15393,15394,15395,15396,15397,15398,15399,15400,15401,15402,15403,15404,15405,15406,15407,15408,15409,15410,15411,15412,15413,15414,15415,15416,15417,15418,15419,15420,15421,15422,15423,15424,15425,15426,15427,15428,15429,15430,15431,15432,15433,15434,2247,2248,2250,2252,2253,2254,2255,2256,2258,2259,2260,2262,2263,2266,2268,2270,2271,2273,2274,2277,2278,2280,2281,2282,2283,2284,2285,2287,2288,2289,2290,2291,2293,2294,2295,2297,2298,2299,2301,2305,632,3681,706,731,2313,2314,2320,3697,2322,2461,2325,3002,3437,3439,3446,3447,3448''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllocationReprocess]  
(   
@FromDate Datetime,  
@ToDate Datetime,  
@EmployeeId varchar(8000)   
)  
AS  
BEGIN
	DECLARE @SwipeCardNo AS nvarchar(20)  
	DECLARE @Employee_Code_Id AS nvarchar(20)  
	DECLARE @dtFromDate as datetime
	CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[#TempSwipeCardNo]   
	(  
		[SwipeCardNo] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempEmployee_Code_Id]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	create table #TempSwipeCardNo(SwipeCardNo nvarchar(20),Employee_Code_Id nvarchar(20)) 
	insert into #TempSwipeCardNo SELECT SwipeCardNo,Employee_Code_Id FROM TA_Tbl_Employee inner join TA_Tbl_TempShiftAllocation on TA_Tbl_TempShiftAllocation.EmpID=TA_Tbl_Employee.Employee_Id where SwipeCardNo is not null
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
	where Date BETWEEN @FromDate AND @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	set @dtFromDate=@FromDate
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@dtFromDate and Clk_InDate between @dtFromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@dtFromDate and Clk_InDate is null and Clk_OutDate between @dtFromDate and @ToDate
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from TA_Tbl_Clk_RawData inner join #TempSwipeCardNo on #TempSwipeCardNo.SwipeCardNo=TA_Tbl_Clk_RawData.Clk_CardId AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)  
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' from TA_Tbl_ManualTimeEntry inner join #TempSwipeCardNo on #TempSwipeCardNo.Employee_Code_Id=TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	drop table #TempSwipeCardNo
	drop table  #TempEmployee_Code_Id 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <19-09-2016>
-- Description:	<Getting Template and Gateway details for SMS triggering>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTemplateDetailsForSMSTriggering]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF EXISTS(SELECT ServiceUrl FROM TA_TBL_SMSGATEWAY)
	BEGIN
		SELECT * FROM Ta_Tbl_SMSGateway
		SELECT * FROM Ta_Tbl_SMSTemplates WHERE TemplateName in(''Late Entry'',''Early Exit'',''Less Hours Worked'',''Absent - Single Day'',''Continuous Absent'',''Leave Application - Apply'', ''Leave Application - Forward'', ''Leave Application - Approved'', ''Permission Application - Apply'', ''Permission Application - Forward'',''Permission Application - Approved'', ''OnDuty - Apply'', ''OnDuty - Forward'', ''OnDuty - Approved'')
		and status=1		
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-09-2016 17:14>
-- Description:	<Getting Tag Details Using Template>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectTagDetailsUsingTemplate]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * from ta_tbl_SMSTags where TemplateName=@TemplateName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_SelectTATblLicenseInfo  
Description : Selects license from protection table
Tables Included : TA_Tbl_LIC_Details
Created By : Christopher S  
Created On : 21-Mar-08  
Modified By :  
Modified On :  
*/  
-- Exec Proc_TA_SelectTA_Tbl_LIC_Details ''eDTwx5/xztpwt0pKDW+e2U7v3kW7I4RJbqPxV1Q5xEA=''
CREATE PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details_Application]
@macAddress nvarchar(200)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_LIC_Details where MACAddress = @macAddress
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_SelectTATblLicenseInfo  
Description : Selects license from protection table
Tables Included : TA_Tbl_LIC_Details
Created By : Christopher S  
Created On : 21-Mar-08  
Modified By :  
Modified On :  
*/  
-- Exec Proc_TA_SelectTA_Tbl_LIC_Details ''eDTwx5/xztpwt0pKDW+e2U7v3kW7I4RJbqPxV1Q5xEA=''
CREATE PROCEDURE [dbo].[Proc_TA_SelectTA_Tbl_LIC_Details]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_LIC_Details
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpellCountByLeaveType]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSpellCountByLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectSpellCountByLeaveType 202, 52
Description		:	Select Spell count of Leave applications based on leaveTypeId and EmployeeAutoId
Tables Included	:	TA_Tbl_LeaveApplication
Created By		:	Prabakaran
Created On		:	11-Aug-07
Modified By		:
Modified On		:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectSpellCountByLeaveType] 
@Employee_Id int,
@leaveType_Id int
AS
BEGIN
	SET NOCOUNT ON;
	select isnull(Count(la.NumberOfDays),0) as SpellCount from TA_Tbl_LeaveApplication la
	inner join Ta_Tbl_yearsetting ys on (la.Leave_FromDate between ys.FromDate and ys.ToDate) and ys.YearSettings_Id=la.YearSettings_Id
	Where la.Employee_Id=@Employee_Id and la.leaveType_Id=@leaveType_Id and la.Status!=''Rejected'' and la.Type=''Leave'' and la.Isdeleted=0
	and ys.IsActive=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSuccessiveDates]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSuccessiveDates]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--	Modified by		:	Manjula.P
--	Modified On		:	21-Apr-2014
--	Descriptinos	:	Changing select 0 as NoOfSuccessiveDaysInYear from select 0 to avoiding invalid column NoOfSuccessiveDaysInYear error
--Proc_TA_SelectSuccessiveDates 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectSuccessiveDates]
	@levelId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if exists (select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@levelId)
	BEGIN
		select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@levelId
	END
	else if exists(select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=-1)
	BEGIN 
		select NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=-1
	END
	else
	BEGIN
	   select 0 as NoOfSuccessiveDaysInYear
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalName]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalName]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Terminal_Id, Terminal_Name From TA_Tbl_Terminal Where IsDeleted =''1''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForPermanentDelete]
	@Type CHAR(1),  
	@TerminalID INT=0,  
	@UserGroupName nVarchar(250)
AS
BEGIN
	SET NOCOUNT ON;
	Select Count(TerminalDatatype_ID) as TerminalCount from TA_Tbl_Terminal	Where TerminalDatatype_ID =@TerminalID 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempUpdateEmployee]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Tbl_TempUpdateEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_Tbl_TempUpdateEmployee]
/****************************************************************************************/
-- Name				:	Proc_TA_Tbl_TempUpdateEmployee
-- Desc				:	To add or update the enties in Employee table.
-- Company			:   Angler Technologies
-- Author			:	P.Santhosh Raj
-- Date				:	29-Feb-2009
-- Update History	:   [Date Updated By (Initials) Reason]
/****************************************************************************************/
AS
BEGIN
delete from TA_Tbl_TempUpdateEmployee
update TA_Tbl_Employee Set Isdeleted=1  WHERE [Employee_Code_Id] IN ( select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id not in (select employee_code from [Customer].dbo.tbl_Cus))
DECLARE @employee_code		nvarchar(50)
DECLARE @first_name			nvarchar(50)
DECLARE @last_name			nvarchar(50)    
DECLARE @birth_date			datetime 
DECLARE @local_addr1		nvarchar(50)  
DECLARE @local_addr2		nvarchar(50) 
DECLARE @local_addr3		nvarchar(50)     
DECLARE @join_date			datetime
DECLARE @desg_name			nvarchar(50) 
DECLARE @section_name		nvarchar(50) 
DECLARE @category_name	nvarchar(50)  
DECLARE @basic			nvarchar(50)   
declare DNCList cursor FOR select employee_code,first_name,last_name,birth_date,local_addr1,local_addr2,local_addr3,join_date,
section_name,desg_name,category_name,[basic] from [Customer].dbo.tbl_Cus where employee_code in (select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0)
OPEN DNCList
	FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic   
		while @@fetch_status = 0
		begin
			insert into TA_Tbl_TempUpdateEmployee VALUES (@employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic)
			FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic
		end
	CLOSE DNCList
DEALLOCATE DNCList
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Tbl_TempInsertEmployee]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Tbl_TempInsertEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_Tbl_TempInsertEmployee]
/****************************************************************************************/
-- Name				:	Proc_TA_Tbl_TempInsertEmployee
-- Desc				:	To add or update the enties in TA_Tbl_TempInsertEmployee
-- Company			:   Angler Technologies
-- Author			:	P.Santhosh Raj
-- Date				:	29-Feb-2009
-- Update History	:   [Date Updated By (Initials) Reason]
/****************************************************************************************/
AS
BEGIN
delete from TA_Tbl_TempInsertEmployee
DECLARE @employee_code		nvarchar(50)
DECLARE @first_name			nvarchar(50)
DECLARE @last_name			nvarchar(50)    
DECLARE @birth_date			datetime 
DECLARE @local_addr1		nvarchar(50)  
DECLARE @local_addr2		nvarchar(50) 
DECLARE @local_addr3		nvarchar(50)     
DECLARE @join_date			datetime
DECLARE @desg_name			nvarchar(50) 
DECLARE @section_name		nvarchar(50) 
DECLARE @category_name	nvarchar(50)  
DECLARE @basic			nvarchar(50)   
declare DNCList cursor FOR select employee_code,first_name,last_name,birth_date,local_addr1,local_addr2,local_addr3,
join_date,
section_name,desg_name,category_name,[basic] from [Customer].dbo.tbl_Cus where employee_code not in (select Employee_Code_Id from TA_Tbl_Employee)
OPEN DNCList
	FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic   
		while @@fetch_status = 0
		begin
			insert into TA_Tbl_TempInsertEmployee VALUES (@employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic)
			FETCH NEXT FROM DNCList into @employee_code,@first_name,@last_name,@birth_date,@local_addr1,
@local_addr2,@local_addr3,@join_date,@section_name,@desg_name,@category_name,@basic
		end
	CLOSE DNCList
DEALLOCATE DNCList
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SwipeCardNoExists]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SwipeCardNoExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Created By : Prabakaran.P  
Created On : 26-Feb-09  
Proc_TA_SwipeCardNoExists 101  
*/  
CREATE procedure [dbo].[Proc_TA_SwipeCardNoExists]  
@SwipeCardNo varchar(20)  
AS  
BEGIN  
	DECLARE @rawdatacount as BIGINT  
	SELECT @rawdatacount=count(CLK_ID) from Ta_Tbl_clk_rawdata where CLK_CARDID=@SwipeCardNo
	IF(@rawdatacount>0)  
	BEGIN  
		SELECT 1 as RawDataCount  
	END  
	ELSE  
	BEGIN  
		SELECT 0 as RawDataCount  
	END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SuccessiveYearSettings]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SuccessiveYearSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SuccessiveYearSettings] 
	-- Add the parameters for the stored procedure here
	AS
BEGIN	
	SET NOCOUNT ON;
    select top 1 Yearsettings_Id as SuccessiveYearSetting from ta_tbl_yearSetting 
    where Yearsettings_Id > (select Yearsettings_Id from ta_tbl_yearSetting where Isactive=1)	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SkipErroredDataForService]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SkipErroredDataForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SkipErroredDataForService]
	-- Add the parameters for the stored procedure here
	@Process_Rec_ID bigint,
	@errorMessage varchar(max)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	insert into TA_Tbl_ErrorLog_ProcessedData (Process_Rec_ID,ErrorMessage) values
	(@Process_Rec_ID,@errorMessage )
	UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 1 WHERE Process_Rec_Id = @Process_Rec_ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShrinkDatabase]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShrinkDatabase]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_ShrinkDatabase]
AS
BEGIN
	SET NOCOUNT ON
	CREATE TABLE #tFileList
	(
	databaseName sysname,
	logSize decimal(18,5),
	logUsed decimal(18,5),
	status INT
	)
	Declare @intSize as int
	declare @inStrdatabaseName as varchar(200)
	--Get Database Name
	set @inStrdatabaseName=(select db_name(dbid) from master..sysprocesses where spid=@@SPID)
	INSERT INTO #tFileList EXEC Proc_TA_GetLogFileSize
	set @intSize=(SELECT  cast(logSize as int) FROM #tFileList where databasename=@inStrdatabaseName)
	if(@intSize>=512)
		begin
			--Database Shrink done here
			--BACKUP LOG @inStrdatabaseName WITH TRUNCATE_ONLY 
			DBCC SHRINKDATABASE (@inStrdatabaseName, 10, TRUNCATEONLY)
		end
DROP TABLE #tFileList 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftReAlloc_Reprocess_RawData ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_RawData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
  Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 from  
	OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = xm.EmployeeAutoID
	inner join TA_Tbl_Clk_RawData on TA_Tbl_Clk_RawData.CLK_CARDID = TA_Tbl_Employee.SwipeCardNo
	AND Clk_Date BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate) 
  Exec sp_xml_removedocument @Index 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ProcessedData]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml,
 @ShiftId int    
)  
AS  
BEGIN
 Declare @Index int
  Set @Index = 0;
  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	DELETE FROM TA_Tbl_ProcessedData FROM 
	OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id = xm.EmployeeAutoID
	inner join TA_Tbl_ProcessedData on TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo
	where TA_Tbl_ProcessedData.Date BETWEEN @FromDate AND @ToDate and TA_Tbl_ProcessedData.Shift_Id = @ShiftId
	Exec sp_xml_removedocument @Index  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_ManualEntry ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ManualEntry]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
	SET NOCOUNT ON;
    Declare @Index int
    Set @Index = 0;
    EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N''  
	from OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ManualTimeEntry on TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id = TA_Tbl_Employee.Employee_Code_Id
	AND ((ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)) OR (ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@FromDate) AND DateAdd(d,1,@ToDate)))  
	Exec sp_xml_removedocument @Index 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_ShiftAllocReprocess_ClockDetails ''04/01/2011 12:00:00 AM'',''12/31/2011 12:00:00 AM'',''1''
CREATE PROCEDURE [dbo].[Proc_TA_ShiftReAlloc_Reprocess_ClockDetails]  
(   
 @FromDate Datetime,  
 @ToDate Datetime,  
 @xml xml   
)  
AS  
BEGIN
    Declare @Index int
    Set @Index = 0;
    EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_Date BETWEEN @FromDate AND @ToDate 
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_InDate=@FromDate and Clk_InDate between @FromDate and @ToDate  
	DELETE FROM TA_Tbl_ClockDetails 
	from OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') As xm 
	inner join TA_Tbl_Employee on TA_Tbl_Employee.Employee_Id= xm.EmployeeAutoID
	inner join TA_Tbl_ClockDetails on TA_Tbl_Employee.SwipeCardNo=TA_Tbl_ClockDetails.Clk_EmpId
	WHERE Clk_OutDate=@FromDate and Clk_InDate is null and Clk_OutDate between @FromDate and @ToDate
	Exec sp_xml_removedocument @Index 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsByIdForService]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftDetailsByIdForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Exec Proc_TA_ShiftDetailsByIdForService 4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftDetailsByIdForService]
	-- Add the parameters for the stored procedure here
	@intShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select Shift_Id, Level_Id, Shift_Name, Shift_ShortName, Shift_Description, Shift_StartTime, Shift_EndTime, Shift_FirstHalf_StartTime, 
	Shift_FirstHalf_EndTime, Shift_SecondHalf_StartTime, Shift_SecondHalf_EndTime, Shift_GraceInTime, Shift_GraceOutTime, Shift_BreakStartTime1, 
	Shift_BreakEndTime1, Shift_BreakStartTime2, Shift_BreakEndTime2, Shift_BreakStartTime3, Shift_BreakEndTime3, Shift_MinTimeOT, Shift_MaxTimeOT, 
	Shift_WorkingDay_OverTime, Shift_TotalWorkingHours, Isdeleted, Emp_ID, Shift_FirstHalfWorkingHours, Shift_SecondHalfWorkingHours, IsBreakDeducted, 
	DefaultShift, ShiftType, CreatedDate, ModifiedDate,[24HrsShift],isStraightShift,StraightPresentTime,
	BreakMins=substring(BreakHours,0,CHARINDEX('':'',BreakHours))*60+substring(BreakHours,CHARINDEX('':'',BreakHours)+1,LEN(BreakHours))
    From TA_Tbl_Shift Where Shift_Id =@intShiftId and Isdeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Mapping_Delete]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Mapping_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Transportation_Mapping_Delete]  
  @id INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=0  
 BEGIN  
  UPDATE TA_Tbl_Transportation_Mapping SET IsDeleted=@DEL WHERE VehicleId=@id  
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Transportation_Delete]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Transportation_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Transportation_Delete]
		@id INT
	AS
	DECLARE @DEL BIT
	SET @DEL=0
	BEGIN
		UPDATE TA_Tbl_Transportation SET IsDeleted=@DEL WHERE id=@id
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_TotalBreakHours]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_TotalBreakHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 26-08-2014
-- Description:	To Get the Total Break Hours Minutes using employeeid and Shift date
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_TotalBreakHours]
	-- Add the parameters for the stored procedure here
	@clk_empid NVARCHAR(20),
	@clk_date DATETIME
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT isnull(SUM(PunchDiffInMin),0)As TotalBreakHours from ta_tbl_MatchedPunches where Clk_Date=@clk_date and Clk_EmpId=@clk_empid
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UnUsedTerminalsinProject]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UnUsedTerminalsinProject]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani. P>
-- Create date: <04-Jan-2020>
-- Description:	<This procedure used to bring unused termianls from project table>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UnUsedTerminalsinProject]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	select isnull(Terminal_ReaderID,0), isnull(Terminal_Name,'''') from ta_tbl_terminal
	where terminal_Id in (
	select isnull(Terminal_id,0) from TA_Tbl_ProjectTerminals
	where Project_Id in (
	select isnull(Project_Id,0) from TA_Tbl_Project
	where (project_status = ''Completed'' or project_status = ''Rejected'')
	) 
	)

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ToCheckTimesheetEntryAvailableForParticularDate]
	@ShiftDate datetime,
	@empID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * from Ta_tbl_TaskProgressDetails where TaskSubmittedBy=@empID and Shiftdate=@ShiftDate and isSubmitted_Completely=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToCheckLastOutIsManual]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ToCheckLastOutIsManual]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ToCheckLastOutIsManual]
	@EmployeeSwipeCardNumber varchar(50),
	@ClockDate varchar(30),
	@Its24Hrs int
AS
BEGIN
	SET NOCOUNT ON;
	if((SELECT count(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @EmployeeSwipeCardNumber AND (ManualTimeEntry_OutDate + ManualTimeEntry_OutTime)=@ClockDate and Isdeleted=0 and ManualTimeEntry_Status=''Approved'')>0)
		begin
			select 1
		end
	else
		begin
			if(@Its24Hrs=1)
				begin
					if((SELECT count(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @EmployeeSwipeCardNumber AND (ManualTimeEntry_OutDate + ManualTimeEntry_OutTime)=dateadd(d,1,@ClockDate) and Isdeleted=0 and ManualTimeEntry_Status=''Approved'')>0)
						begin
							select 1
						end
					else
						begin
							select 0
						end
				end
			else
				begin
					select 0
				end
		end	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance_Eastman]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAttendance_Eastman]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <01-April-2019 02:44 PM>
-- Description:	<Updating the attendance as per the shift creation and allocation to employees>
-- Proc_TA_UpdateAttendance_Eastman ''787'',''2019-03-08 00:00:00.000'',4,''Present'',''Absent'',''11:31:00'','''',14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAttendance_Eastman]
	@EmployeeCodeID VARCHAR(50),
	@Date DATETIME,
	@EmpCategoryID INT,
	@FirstSession VARCHAR(20),
	@SecondSession VARCHAR(20),
	@Intime VARCHAR(10),
	@Outtime VARCHAR(10),
	@ShiftID INT
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @empCategory VARCHAR(30)
	--DECLARE @Shift_StartTime VARCHAR(10)
	--DECLARE @Shift_EndTime VARCHAR(10)
	--DECLARE @Shift_FirstHalf_StartTime VARCHAR(10)
	--DECLARE @Shift_FirstHalf_EndTime VARCHAR(10)
	--DECLARE @Shift_SecondHalf_StartTime VARCHAR(10)
	--DECLARE @Shift_SecondHalf_EndTime VARCHAR(10)
	--DECLARE @Shift_GraceInTime VARCHAR(10)
	--DECLARE @Shift_GraceOutTime VARCHAR(10)
	--select top 1 @EmpCategoryID=EC.CategoryId from TA_Tbl_EmployeeCategory EC
	--inner join TA_Tbl_Employee E on EC.EmployeeId=E.Employee_Id
	--where E.SwipeCardNo=@EmployeeCodeID
	--order by EC.EffectiveDate desc
	SELECT	@EmpCategoryID=empCategory FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	SELECT @empCategory=CategoryName FROM TA_Tbl_Category WHERE CategoryId=@EmpCategoryID
	--SELECT @empCategory
	--SELECT	@Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime,@Shift_FirstHalf_StartTime=Shift_FirstHalf_StartTime,@Shift_FirstHalf_EndTime=Shift_FirstHalf_EndTime,@Shift_SecondHalf_StartTime=Shift_SecondHalf_StartTime,
	--		@Shift_SecondHalf_EndTime=Shift_SecondHalf_EndTime,@Shift_GraceInTime=Shift_GraceInTime,@Shift_GraceOutTime=Shift_GraceOutTime 
	--FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	--STAFF AND SHIFT EXEMPTION
	BEGIN 
		IF(@empCategory=''STAFF SHIFT'' OR @empCategory=''SHIFT EXEMPTION'')
		BEGIN
			--select ''Entered''
			IF (@FirstSession not in(''Present'',''Weekly off'',''Holiday'',''Absent'',''RH''))
			BEGIN
				IF(CONVERT(DATETIME,@Intime)>''14:30'')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET ANAttendanceCode=''Absent'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET ANAttendanceCode=''Present'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
			END		
			ELSE
			BEGIN
				IF(@SHIFTID!=-1)
				BEGIN
					--Print ''Entered into first if loop''
					IF(@Intime IS NOT NULL AND @Intime<>'''')
					BEGIN
						--Print ''Entered into second if loop''
						IF(CONVERT(DATETIME,@Intime)>''14:30'')
						BEGIN
							--Print ''Entered '' + ''14:30''
							UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Absent'',ANAttendanceCode=''Absent'' WHERE Employee_Code_Id=@EmployeeCodeID and Date=@Date
						END
						ELSE IF(CONVERT(DATETIME,@Intime)>''11:30'')
						BEGIN
							--Print ''Entered '' + ''11:30''
							UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Absent'' WHERE Employee_Code_Id=@EmployeeCodeID and Date=@Date
						END					
					END
				END
				ELSE
				BEGIN
					SELECT 1
				END
			END			
		END
	END
	--HOD
	BEGIN
	-- As per the client requisition, we dont need to check anything for HOD category employees
		IF(@empCategory=''HOD'')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Present'',ANAttendanceCode=''Present'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
			END		
		END
	END	
	--DRIVER SHIFT
	BEGIN
	--For driver category employees if any one punches are available in a day, that time attendance should be updated as present.
		IF(@empCategory=''Driver'')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				IF((@Intime IS NOT NULL AND @Intime<>'''') or (@Outtime IS NOT NULL AND @Outtime<>''''))
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Present'',ANAttendanceCode=''Present'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
			END
		END
	END
	--NIGHT SHIFT
	--select @Date+@Intime,@Date+ ''05:00 PM'',@Date+ ''08:30 PM''
	BEGIN
		IF(@empCategory=''Night Shift'')
		BEGIN
			IF(@SHIFTID!=-1)
			BEGIN
				IF(@Date+@Intime > @Date+ ''08:30 PM'')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Absent'',ANAttendanceCode=''Absent'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE IF(@Date+@Intime between @Date+ ''05:00 PM'' and @Date+ ''08:30 PM'')
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET FNAttendanceCode=''Present'',ANAttendanceCode=''Present'' where Employee_Code_Id=@EmployeeCodeID and Date=@Date
				END
				ELSE
				BEGIN
					--Here need to discuss this point with client
					select 1
				END
			END
		END
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAttendance]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UpdateAttendance]
(
  @ShiftId int,
  @WorkHrs nvarchar(10),
  @Attendance nvarchar(20),
  @Process_Rec_ID BIGINT
)
AS
BEGIN
	UPDATE TA_TBL_PROCESSEDDATA SET SHIFT_ID = @SHIFTID,WORKHRS = @WORKHRS,ATTENDANCE = @ATTENDANCE,PROCESSFLAG = 1 
	WHERE PROCESS_REC_ID = @PROCESS_REC_ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateAttandanceCode]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_updateAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_updateAttandanceCode]
	@AttandanceID as int,
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@EmpID as int
AS
BEGIN
	update  TA_Tbl_AttandanceCode set 
				AttandanceCode=@AttandanceCode,
				AttandanceValue=@AttandanceValue,
				CompanyID=@CompanyID,
				EmpID=@EmpID where 
		AttandanceID=@AttandanceID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateActiveLanguage]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateActiveLanguage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_UpdateActiveLanguage
Description	:	Set Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	16-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_UpdateActiveLanguage] 
@Language_Id int
as
Update TA_Tbl_MultiLingual set IsActive=1 where Language_Id=@Language_Id
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_LeaveTypeDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_LeaveTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_Update_LeaveTypeDetails]        
(        
 @LeaveType NVARCHAR(50),        
 @LeaveDescription NVARCHAR(250),      
 @TypeId INT,    
 @employeeId int,  
 @CountFactor int,
 @EmpCategory int,
 @EmpType int,
 @Gender varchar(10),
 @Religion int
)        
AS        
 BEGIN        
  --declare @sql nvarchar(2000)          
  --SET @sql=''
  UPDATE TA_Tbl_LeaveType SET LeaveType =@LeaveType,LeaveDescription= @LeaveDescription, 
  Emp_ID=@employeeId,CountFactor=@CountFactor,EmployeeCategory=@EmpCategory,EmployeeType=@EmpType,Gender=@Gender,Religion=@Religion WHERE LeaveType_Id=@TypeId
 -- exec(@sql)    
 END 
 --[Proc_TA_Update_LeaveTypeDetails] ''ctc'',''common'',8,1,0,1,1,1,1' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting all Companies shift Setting details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShiftSettingsAllCompaniesForservice]
	-- Add the parameters for the stored procedure here		
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MaxHoursBeforeShift,MaxHoursAfterShift,WeeklyOffStartHours,CompanyId,IgnoreDuplicatePunch,PunchInterval,MaxHoursBeforeShift_24HrsShift,WeeklyOffStartHours_24HrsShift FROM TA_Tbl_ShiftSettings
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultRights]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDefaultRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateDefaultRights ''6,7,10,15,68,12,16,64,17,94,95,18,19,20,69,99,100,21,22,23,24,96,25,26,98,97,27,28,29,60,76,62,102,108,37,38,65,36,35,34,41,30,40,45,39,33,44,32,42,43,79,71,70,80,84,89,92,93,101,105,47,48,49,50,51,52,53,72,103,110,54,55,66,67,75,77,78,104,106,107,109'',''1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDefaultRights]
	-- Add the parameters for the stored procedure here
	@enterprisePageIds varchar(8000),
	@parenIds varchar(8000),
	@employeeId int 	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
declare @concat as nvarchar(100)
declare @concatPID as nvarchar(100)
declare @pos as int
declare @pos1 as int
declare @flag as int
if (@enterprisePageIds is null or @enterprisePageIds='''')    
    set @flag=0
else
    set @flag=1    
while (@flag=1)
    Begin
        set @pos = charINDEX('','',@enterprisePageIds)
		set @pos1 = charINDEX('','',@parenIds)
        if (@pos=0)
            Begin
                select @concat = @enterprisePageIds
                set @enterprisePageIds=''''
				select @concatPID = @parenIds
                set @parenIds=''''
            End
        else
            Begin
                select @concat = substring(@enterprisePageIds,0,@pos)
				select @concatPID = substring(@parenIds,0,@pos1)
            End
		declare @exists as int
		set @exists = (select count(*) from TA_Tbl_userRights where pageId=cast(@concat as float) and groupId=1)
		if(@exists=0)
			INSERT INTO TA_Tbl_userRights (groupName,groupId,pageId,pageGroupId,addPrv,modifyPrv,deletePrv,viewPrv,isDeleted,employeeId) 
			VALUES (''SuperAdmin'',1,cast(@concat as float),cast(@concatPID as int),1,1,1,1,0,@employeeId)
        set @enterprisePageIds = substring(@enterprisePageIds,@pos+1,len(@enterprisePageIds))
		set @parenIds = substring(@parenIds,@pos1+1,len(@parenIds))
        if (@enterprisePageIds is null or @enterprisePageIds='''')
            set @flag=0
        else
            set @flag=1            
    End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateConcurrentUser]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateConcurrentUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_UpdateConcurrentUser] 
@UserId nvarchar(10),  
@IpAddress nvarchar(15),  
@SessionId nvarchar(25)  
as  
update ta_tbl_concurrentuser   
set status = 0 where UserId=@UserId and IpAddress=@IpAddress and SessionId=@SessionId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Update 2nd grid info which is already exist employee info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateCMITechAlreadyExistEmployee]
@EmployeeCodeId varchar(30),
--@EmployeeName varchar(100),
--@Designation varchar(100),
--@Level	varchar(250),
@DOJ datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Declare @DesignationId int
	--Declare @LevelId int
	--Declare @ParentLevelId int
	--set @DesignationId = 0;

	IF Exists(select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id = @EmployeeCodeId)
	Begin
		update ta_tbl_employee set DateOfJoining = @DOJ where (Employee_Code_Id = @EmployeeCodeId) 
	End

	--set @DesignationId = (select isnull(TitleId,0) from TA_Tbl_Title)
	--set @LevelId = (select isnull(levelID,0) from TA_Tbl_Level)
	--set @ParentLevelId =(select dbo.Func_TA_GetParentIds(convert(varchar,@LevelId)))

	--select * from TA_Tbl_Employee
	--select * from TA_Tbl_EmployeeDesignation
	--select * from TA_Tbl_EmployeeLevel
	--select * from TA_Tbl_Level
	--select * from TA_Tbl_Title

	

END


' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBLStatusByService]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateBLStatusByService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateBLStatusByService]
	-- Add the parameters for the stored procedure here	
	@Process_Rec_Id bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET Attendance = ''Present'',Status = ''BL'',ProcessFlag = 1, fnAttendanceCode=''Present'', anAttendanceCode=''Present'' 
	WHERE Process_Rec_Id = @Process_Rec_Id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockProcess]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateClockProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_UpdateClockProcess]
@EmployeeId as int, 
@dtmStartDate as datetime,
@dtmToDate as datetime
AS
BEGIN
Declare @SwipeCardNo as nvarchar(20)
--Get swipecardno from employee table
set @SwipeCardNo=(SELECT SwipeCardNo FROM TA_Tbl_Employee Where Employee_Id = @EmployeeId and Isdeleted=0)
--update raw data table
update TA_Tbl_Clk_RawData set CLK_Flag=0 where (clk_Date between @dtmStartDate
and @dtmToDate) and CLK_CARDID=@SwipeCardNo and CLK_PROCESS=0 and CLK_Flag=1 
UPDATE TA_Tbl_ProcessedData SET ProcessFlag = 0
WHERE Employee_Code_Id = @SwipeCardNo 
AND [Date] between @dtmStartDate and @dtmToDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_one]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_one]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_get_level_one]
	@para int
AS
BEGIN
	SELECT levelID,levelname from Ta_Tbl_level where isdeleted=0 and parentlevelId=2  order by levelname
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FinalProgressUpdation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_FinalProgressUpdation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_FinalProgressUpdation ''06/10/2020'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_FinalProgressUpdation]
	@ShiftDate datetime,
	@empID bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	update Ta_tbl_TaskProgressDetails set isSubmitted_Completely=1 where shiftDate=@ShiftDate and TaskSubmittedby=@empID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_FillTempProcessTable]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_FillTempProcessTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_FillTempProcessTable]
	-- Add the parameters for the stored procedure here
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	DELETE FROM TA_Tbl_DataProcessTemp
    -- Insert statements for procedure here
	;WITH CTE AS
	(    
		SELECT @date as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,convert(datetime,convert(varchar(11),[DATE])))FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetBrandDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetBrandDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 10-Nov-2010
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetBrandDetails]		
AS
BEGIN
	set nocount on
    select DisplayName,KeyValue from TA_Tbl_TerminalBrand	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	To get the shift settings details by using company id
-- Proc_Ta_GetBasicShiftSettingDetailsForService 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetailsForService]
	@COMPANYID INT
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		BEGIN TRANSACTION
		IF EXISTS(SELECT SHIFTSETTINGID FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID)
		BEGIN			
			SET @COMPANYID=@COMPANYID
		END	
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT SHIFTSETTINGID FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = -1)
				BEGIN
					INSERT INTO TA_Tbl_ShiftSettings([CompanyId],[MaxHoursBeforeShift],[MaxHoursAfterShift],[ShiftBreak],[ShiftMaxBreakHours],	 
					[MonthlyWorkingHours],[WeeklyWorkingHours],[EmpID],[HolidayOT],[WeekOffOT],[otOption],[DefaultMonthClosureDate],[IsFlexible],
					[FlexibleFlag],[OTRoundoffEnable],[FullDayAttendanceHrs],[HalfDayAttendanceHrs],[HalfDayAttendance],[FullDayAttendance],
					[WeeklyOffStartHours],[IgnoreDuplicatePunch],[PunchInterval],[AfterShiftTime],[BeforeShiftTime],[DefinedWorkhrs],
					[NoOfSuccessiveDaysInYear],[CompensationValitityDays],[VaildityCompOffDays],[HalfDayCompOff],[FullDayCompOff],
					[LateEntry],[EarlyEntry],[EarlyExit],[LateExit])
					VALUES(-1,''02:00'',''02:00'','''','''','''','''',''1'',''1'',''1'',''WeeklyOff'',
					DATEADD(MONTH,DATEDIFF(MONTH,0,dateadd(month,-1,GETDATE())),-1)
					,''0'',''0'',''0'','''','''',''1'',''1'',''16:00'',''1'',''00:10'',''1'',''1'',''1'',30,''0'',90,''11:00'',''12:00'',''1'',''1'',''1'',''1'')
				END						
			SET @COMPANYID=-1
		END
		SELECT	SHIFTSETTINGID,COMPANYID,MAXHOURSBEFORESHIFT,MAXHOURSAFTERSHIFT,SHIFTBREAK,SHIFTMAXBREAKHOURS, 
				MONTHLYWORKINGHOURS,WEEKLYWORKINGHOURS,EMPID,HOLIDAYOT, 
				WEEKOFFOT,OTOPTION,CONVERT(VARCHAR(25),DEFAULTMONTHCLOSUREDATE,120) AS MONTHCLOSURE_ENDDATE, 
				ISFLEXIBLE,FLEXIBLEFLAG,OTROUNDOFFENABLE,FULLDAYATTENDANCEHRS, 
				HALFDAYATTENDANCEHRS,HALFDAYATTENDANCE,FULLDAYATTENDANCE, WEEKLYOFFSTARTHOURS, 
				IGNOREDUPLICATEPUNCH,PUNCHINTERVAL,AFTERSHIFTTIME,BEFORESHIFTTIME, 
				DEFINEDWORKHRS,NOOFSUCCESSIVEDAYSINYEAR,COMPENSATIONVALITITYDAYS,VAILDITYCOMPOFFDAYS, 
				HALFDAYCOMPOFF, FULLDAYCOMPOFF,LATEENTRY,EARLYENTRY, 
				EARLYEXIT,LATEEXIT, TIMESTAMP,TIMESTAMP1, 
				ISLUNCHDEDUCTION,LUNCHDEDUCTIONHOURS,FLEXI_AFTERSHIFTTIME,FLEXI_BEFORESHIFTTIME,FLEXI_DEFINEDWORKHRS
		FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID= @COMPANYID			
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetBasicShiftSettingDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetBasicShiftSettingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetBasicShiftSettingDetails]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if Exists(SELECT ShiftSettingId FROM TA_Tbl_ShiftSettings WHERE CompanyId = @CompanyId)
		begin
			SELECT ShiftSettingId,HolidayOT,WeekOffOT,otOption,IsFlexible,FlexibleFlag,HalfDayAttendance,OTRoundoffEnable,DefaultMonthClosureDate as MonthClosure_EndDate FROM TA_Tbl_ShiftSettings WHERE CompanyId = @CompanyId
		end
	else
		begin
			SELECT ShiftSettingId,HolidayOT,WeekOffOT,otOption,IsFlexible,FlexibleFlag,HalfDayAttendance,OTRoundoffEnable,DefaultMonthClosureDate as MonthClosure_EndDate FROM TA_Tbl_ShiftSettings WHERE CompanyId = -1
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAttendanceData]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAttendanceData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'  
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_GetAttendanceData]   
 -- Add the parameters for the stored procedure here  
 @AttendanceDate datetime  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
    -- Insert statements for procedure here  
 select TA_Tbl_Employee.Employee_Code_id as ''Employee Code'',Employee_FirstName as ''Employee Name'',InTime as ''In Time'',OutTime as ''Out Time'',HrsWork as  ''No of Hours'',HrsOt as ''No of OT Hours''  
from ta_tbl_processeddata INNER JOIN   
TA_Tbl_Employee on TA_Tbl_Employee.SwipeCardNo=ta_tbl_processeddata.Employee_Code_id  
where ta_tbl_processeddata.Date=@AttendanceDate  
END  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetApprovalStatus]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetApprovalStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:           <R.Manikandan>
-- Create date: <26-04-2017,10.23 AM,>
-- Description:      <Get the Approval Status for each Transaction>
-- We got some issue in onduty screen due to that we changed this procedue coding on 30-12-2019 06:02 PM by Manikandan.rr
-- Proc_Ta_GetApprovalStatus 1,3,0
-- Mobile app will not worked if WHERE Employee_Id=@EmpCodeID and Isdeleted=0
-- if you change Employee_Id means, application will not work. verified on 06Feb2020 05:35 PM
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetApprovalStatus]
       @EmpAutoId bigint,
       @EmpCodeID varchar(20),
       @ReportBasedOn bit
AS
BEGIN
	SET NOCOUNT ON;
	Declare @ReportingTo varchar(50)
	Declare @SanctioningAuthority varchar(50)
	Declare @Status varchar(20)
	set @Status =''''
	Declare @EnteredEmployeeAutoID varchar(20)
	Declare @UserGroup_Id varchar(50)
	Declare @UserGroup_Name varchar(50)
	select @UserGroup_Id=UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId and Isdeleted=0
	select @UserGroup_Name=groupName from ta_tbl_usergroup where groupId=@UserGroup_Id
	SELECT @ReportingTo=Reporting_To,@SanctioningAuthority=Leave_Sanc_Authority,@EnteredEmployeeAutoID=Employee_Id from TA_Tbl_Employee
	WHERE Employee_Id=@EmpCodeID and Isdeleted=0
	--select @ReportingTo,@SanctioningAuthority
	IF(@EmpAutoId=@ReportingTo and @EmpAutoId=@SanctioningAuthority)
	BEGIN
		SET @Status=''Approved''
	END
	ELSE IF(@EmpAutoId=@SanctioningAuthority)
	BEGIN
		SET @Status=''Approved''
	END
	ELSE IF(@EmpAutoId=@ReportingTo)
	BEGIN
		SET @Status=''Forwarded''
	END
	ELSE
	BEGIN
		IF (@UserGroup_Name!=''Superadmin'')
		begin
			IF(@EmpAutoId!=@EnteredEmployeeAutoID)
			BEGIN
				IF(@ReportBasedOn=0 OR @ReportBasedOn=1)
				BEGIN
					IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
					BEGIN
						SET @Status=''Forwarded''
					END
					Else
					BEGIN
						SET @Status=''Pending''
					END
				END				
			END
			--this part added newly by Manikandan.RR on 30-12-2019 06:02 PM
			ELSE
			BEGIN
				IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
				BEGIN
					SET @Status=''Forwarded''
				END
				Else
				BEGIN
					SET @Status=''Pending''
				END
			END
		END
		ELSE
		BEGIN
			IF(isnull(@ReportingTo,0)=isnull(@SanctioningAuthority,0))
			BEGIN
				SET @Status=''Forwarded''
			END
			Else
			BEGIN
				SET @Status=''Pending''
			END
		END
	END
	select @Status as Status
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetApprovalAuthority]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetApprovalAuthority]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetApprovalAuthority
Description		:	Get First and Second Level Authority Ids by passing the Applicant Id
Tables Included		:	TA_TBL_Employee
Created By		:	Kumuthini
Created On		:	06-Apr-2009
Modified By		:	Kumuthini
Modified On		:	07-Apr-2009
-- Proc_TA_GetApprovalAuthority 5
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetApprovalAuthority] 
(
	@Applicant_Id int
)
AS
BEGIN
	SELECT R.Employee_FirstName AS ReportingToEmployee,E.Reporting_To,S.Employee_FirstName AS SanctioningEmployee,E.Leave_Sanc_Authority 
	FROM TA_Tbl_Employee E  
	LEFT OUTER JOIN TA_Tbl_Employee R ON R.Employee_Id = E.Reporting_To
	LEFT OUTER JOIN TA_Tbl_Employee S ON S.Employee_Id = E.Leave_Sanc_Authority
	WHERE E.Employee_Id = @Applicant_Id
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveYearSettingDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetActiveYearSettingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetActiveYearSettingDetails
Description	:	Get year settings details
Tables Included	:	TA_Tbl_YearSetting
Created By	:	Prabakaran
Created On	:	30-Jul-07
Modified By	:
Modified On	:
*/
CREATE Procedure [dbo].[Proc_TA_GetActiveYearSettingDetails]
@IsActive bit
as
Select * from TA_Tbl_YearSetting where IsActive=@IsActive
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetActiveLanguageDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetActiveLanguageDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetActiveLanguageDetails
Description	:	Get Active Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	27-Jul-07
Modified By	:	
Modified On	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetActiveLanguageDetails] 
as
select * from TA_Tbl_MultiLingual where IsActive=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAccessDeniedSettingEntries]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAccessDeniedSettingEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Author                  : Kumuthini.L
-- Procedure Name  : Proc_TA_GetAccessDeniedSettingEntries
-- Tables Used         :TA_Tbl_AccessDeniedSettings
-- Created On           : 12-Mar-2008
CREATE PROCEDURE [dbo].[Proc_TA_GetAccessDeniedSettingEntries]
AS
BEGIN
    SELECT A.AccessDenied_Id,A.Terminal_ReaderID,(ISNULL(E.Employee_FirstName,'''') + '' '' + ISNULL(E.Employee_LastName,'''')) AS Employee_Name,A.AccessDeniedKey FROM TA_Tbl_AccessDeniedSettings A,TA_Tbl_Employee E WHERE A.Employee_Code_Id = E.Employee_Code_Id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_get_Total_Level]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_get_Total_Level]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_Ta_get_Total_Level] 	
AS
BEGIN	
	--SELECT count(*) as tot from ta_tbl_level where parentLevelid<>0 group by parentLevelId
	select count(*)  as tot from ta_tbl_level where isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Get_SanctioningEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 16-9-2011
-- Description:	To Get the Sanctioning EmployeeDetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Get_SanctioningEmployeeDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select employee_id,Employee_FirstName + '' '' + Employee_LastName as Name from ta_tbl_employee where employee_id in (select distinct Leave_Sanc_Authority from ta_tbl_employee where reporting_to is not null and reporting_to<>0)	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Get_ReportingToEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		R.MANIKANDAN
-- Create date: 16-9-2011
-- Description:	To Get the ReportingTo Employee Names
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_Get_ReportingToEmployeeDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select employee_id,Employee_FirstName + '' '' + Employee_LastName as Name from ta_tbl_employee where employee_id in (select distinct reporting_to from ta_tbl_employee where reporting_to is not null and reporting_to<>0)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDevices]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDevices]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <24_Aug_2019>
-- Description:	<This Procedure takes device ids from rawdata table for rawdata report for Filter dropdown>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDevices] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Select distinct CLK_DEVICEID as DeviceId from TA_Tbl_Clk_RawData order by CLK_DEVICEID asc

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDeviceLogTableDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDeviceLogTableDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <01-Jan-2020 15:43 PM>
-- Description:	<Get the Device Log Table Details with LastLog ID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDeviceLogTableDetails]
	@DeviceLog_TableName nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT tblAutoID,DeviceLog_TableName,LastLogID from Ta_Tbl_DeviceLogTableDetails where DeviceLog_TableName=rtrim(ltrim(@DeviceLog_TableName))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetDuplicatePunches]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetDuplicatePunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_Ta_GetDuplicatePunches]
(
   @PunchInterval AS INT,
   @Type AS TINYINT
)
AS
BEGIN
IF (@Type = 0) -- IN
BEGIN
	SELECT DISTINCT a.Clk_id, a.Clk_empid, a.clk_date,(a.clk_InDate + a.clk_Intime) as InDateTime,(a.clk_OutDate+a.clk_OutTime) AS OutDateTime
	FROM ta_tbl_clockdetails a
	INNER JOIN ta_tbl_clockdetails b ON b.Clk_EmpId = a.Clk_EmpId AND b.Clk_Date = a.Clk_Date
	INNER JOIN Ta_Tbl_CollectRawDataCompanyLevelTemp crdTemp ON crdTemp.LevelId = a.Clk_CompId
	WHERE  
	((DATEDIFF(s,(a.Clk_InDate+a.Clk_InTime), (b.Clk_InDate+b.Clk_InTime)) <= @PunchInterval AND DATEDIFF(s,(a.Clk_InDate+a.Clk_InTime), (b.Clk_InDate+b.Clk_InTime)) > 0) OR
	(DATEDIFF(s,(b.Clk_InDate+b.Clk_InTime),(a.Clk_InDate+a.Clk_InTime) ) <= @PunchInterval AND DATEDIFF(s,(b.Clk_InDate+b.Clk_InTime),(a.Clk_InDate+a.Clk_InTime)) > 0) ) 
	AND a.IsVoid = 0 AND b.IsVoid = 0 AND a.clk_date between DateAdd(Month,-1,getdate()) and getdate()
	ORDER BY (a.clk_InDate + a.clk_Intime)
END
ELSE 
BEGIN 
	SELECT DISTINCT a.Clk_id, a.Clk_empid, a.clk_date,(a.clk_OutDate+a.clk_OutTime) AS OutDateTime, (a.clk_InDate + a.clk_Intime) as InDateTime
	FROM ta_tbl_clockdetails a
	INNER JOIN ta_tbl_clockdetails b ON b.Clk_EmpId = a.Clk_EmpId AND b.Clk_Date = a.Clk_Date
	INNER JOIN Ta_Tbl_CollectRawDataCompanyLevelTemp crdTemp ON crdTemp.LevelId = a.Clk_CompId
	WHERE 
	((DATEDIFF(s,(a.Clk_OutDate+a.Clk_OutTime), (b.Clk_OutDate+b.Clk_OutTime)) <= @PunchInterval AND DATEDIFF(s,(a.Clk_OutDate+a.Clk_OutTime), (b.Clk_OutDate+b.Clk_OutTime)) > 0) OR
	(DATEDIFF(s,(b.Clk_OutDate+b.Clk_OutTime),(a.Clk_OutDate+a.Clk_OutTime) ) <= @PunchInterval AND DATEDIFF(s,(b.Clk_OutDate+b.Clk_OutTime),(a.Clk_OutDate+a.Clk_OutTime)) > 0) ) 
	AND a.IsVoid = 0 AND b.IsVoid = 0 AND a.clk_date between DateAdd(Month,-1,getdate()) and getdate()
	ORDER BY (a.clk_OutDate + a.clk_Outtime)
	DELETE FROM Ta_Tbl_CollectRawDataCompanyLevelTemp
END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCurrentDateProgressDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCurrentDateProgressDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetCurrentDateProgressDetails ''2020/06/12'',4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCurrentDateProgressDetails]
	@ShiftDate datetime,
	@EmployeeID bigint
AS
BEGIN
	SET NOCOUNT ON;	
	SELECT 	
	Project_Name,
	TaskName,		
	TaskDescription,
	PT.TaskHours,
	SpentHours,
	TaskSubmittedDate,
	TaskSubmittedBy,
	TaskModifiedDate,
	TaskModifiedBy,
	ModificationReason,
	ApprovedHours,
	ApprovedBy1,
	ApprovedDate1,
	ApprovedBy2,
	ApprovedDate2,
	TaskDetailID,
	ShiftDate,
	Status,
	Project_Code,
	PT.ProjectId,
	Client_Name,
	Project_Description,
	Project_StartTime,
	Project_EndTime,
	Project_Status,
	IsDeleted,
	Created_By,
	Created_On,
	Modified_By,
	Modified_On,
	LevelID,
	Mandays,
	ManHours,	
	isSubmitted_Completely,
	SpentMinuts=dbo.ConvertHoursToMinites(spenthours),
	PT.TaskID from TA_Tbl_Project P 
	Inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
	Inner join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and PT.taskID=TPD.TaskID)
	where TPD.TaskSubmittedBy=@EmployeeID and TPD.ShiftDate=@ShiftDate and isnull(isSubmitted_Completely,0)=0	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDatesWithFormat]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDatesWithFormat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetDatesWithFormat ''2015-04-01'',''2015-04-01''
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetDatesWithFormat]
	-- Add the parameters for the stored procedure here
	@From varchar(20),
	@To varchar(20)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
    -- Insert statements for procedure here
	SELECT case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR,CONVERT(datetime,@From),@dateFormat),'' '',''-'') 
	else CONVERT(VARCHAR,CONVERT(datetime,@From), @dateFormat) end AS
	Date,case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR,CONVERT(datetime,@To),@dateFormat),'' '',''-'') 
	else CONVERT(VARCHAR,CONVERT(datetime,@To), @dateFormat) end AS
	Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDateOfJoining]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDateOfJoining]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_GetDateOfJoining 
--	Modified By		:	Manjula.P
--	Modified On		:	26-Apr-2014
--	Descriptions	:	Modified this procedure from PRODUCT for ANGER migration
CREATE PROCEDURE [dbo].[Proc_TA_GetDateOfJoining]
(
   @Employee_Code_Id NVARCHAR(10),
   @xml xml,
   @ManualEntryDate varchar(20),
   @Parameter varchar(1)
)
AS
BEGIN 
  if(@Parameter = ''S'')
	BEGIN
	  SELECT DateOfJoining FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id AND IsDeleted = 0
	END
  else if(@Parameter = ''G'')
	BEGIN
	  Declare @Index int
	  Set @Index = 0;
	   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  select E.Employee_Id as EmployeeAutoId
		  from OpenXML(@Index, ''/NewDataSet/Table'')
		  With (EmployeeId VARCHAR(250) ''EmployeeId'') as xm 
		  inner join TA_Tbl_Employee E on E.Employee_Code_Id = xm.EmployeeId
		  where E.DateOfJoining > @ManualEntryDate
	  Exec sp_xml_removedocument @Index
	END  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCountFlexibleTimings]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCountFlexibleTimings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_GetCountFlexibleTimings 4
CREATE   PROCEDURE [dbo].[Proc_TA_GetCountFlexibleTimings]
(
    @Org_LevelID int
)
AS
begin
select count(*) as FlexibleCount from ta_tbl_shiftsettings Where CompanyId=@Org_LevelID and IsFlexible=1 and FlexibleFlag=2
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays_Angler]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompOffDays_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetCompOffDays 210
Description		:	Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	Prabakaran
Modified On		:	03-Nov-09
*/
Create   PROCEDURE [dbo].[Proc_TA_GetCompOffDays_Angler] 
@EmployeeId bigint
AS
Declare @FromDate as datetime
Declare @ToDate as datetime
Declare @CompOffDays as bigint
Declare @NumberOfDays as bigint
Declare @OtMinHrs as nvarchar(20)
Declare @OtHrs as bigint
Declare @OtMin as bigint
Declare @TotalOtMin as bigint
Declare @Employee_code_Id as nvarchar(50)
BEGIN
declare @intCompEligible as int
set @intCompEligible=(select isnull(CompOff_Eligible,0) as CompOff_Eligible from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
--set @intCompEligible=1
if(@intCompEligible>0)
begin
	-- Get Employee code Id based on Employee Id
	set @Employee_code_Id=(select SwipeCardNo from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
	-- Get From Date from Active year
	set @FromDate=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
	-- Get To Date from Active year
	set @ToDate=(select ToDate from TA_Tbl_YearSetting where IsActive=1)
/*
	-- Get OtMinHrs (Over Time Minimum Hours)
	set @OtMinHrs=(select isnull(OtMinHrs,''00:00'') as OtMinHrs from TA_Tbl_LeavePolicy lp
	inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lp.Policy_Id
	where elp.EmployeeId=@EmployeeId 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
	--and (getdate() between elp.FromDate and elp.ToDate))
	-- Get Overtime Hours
	set @OtHrs=(select left(@OtMinHrs,2))
	-- Get Overtime Minutes
	set @OtMin=(select right(@OtMinHrs,2))
	-- Get Total Over Time Minutes from Over Time Hours and Over Time Minutes
	set @TotalOtMin=(@OtHrs*60) + @OtMin
	-- Get CompOff (Compensation Off) days
	set @CompOffDays=(select sum(OtMins) from TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id=@Employee_code_Id AND OvertimeStatus=''Approved'')
*/
	-- Get Number of CompOff days from Leave Application
	-- Get CompOff (Compensation Off) days using Weekly Off Days and Global Holidays
	set @CompOffDays=(select count(*) from TA_Tbl_ProcessedData 
	where ((FNAttendanceCode=''Weekly Off'' 
	and Attendance=''Present'') or (FNAttendanceCode=''Holiday'' 
	and Attendance=''Present'')) and Employee_Code_Id=@Employee_code_Id and ([Date] BETWEEN @FromDate AND @ToDate))
--select @CompOffDays
	set @NumberOfDays=(select sum(isnull(NumberOfDays,0)) as NumberOfDays from TA_tbl_LeaveApplication 
	WHERE ((Leave_FromDate BETWEEN  @FromDate AND @ToDate) AND (Leave_ToDate BETWEEN  @FromDate AND @ToDate))
	AND Employee_Id=@EmployeeId and Type=''Comp Off'' and Status NOT IN (''Rejected'') and IsDeleted=0)
--select @NumberOfDays
	-- Check Number of Days applied Empty or null
	if(@NumberOfDays is null or @NumberOfDays='''')
		BEGIN
		set @NumberOfDays=0
		END
set @CompOffDays=@CompOffDays-@NumberOfDays
/*
	IF(@TotalOtMin > 0)
		BEGIN
			-- Find Remaining CompOff days
			set @CompOffDays=(@CompOffDays/@TotalOtMin)-@NumberOfDays
		END
	ELSE
		BEGIN
			set @CompOffDays=0
		END
*/
end
else
begin
set @CompOffDays=0
end
	IF(@CompOffDays<=0)
		BEGIN
			select 0 as CompOffDays
		END
	ELSE
		BEGIN
			select isnull(@CompOffDays,0) as CompOffDays
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetChildMenu]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetChildMenu]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <08-06-2016>
-- Description:	<Getting child menus for usergroup>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetChildMenu]
	-- Add the parameters for the stored procedure here
	@pageid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	create table #temppage(id int identity(1,1),pageid int,displayName varchar(200),parentid int)
	create table #tempResult(id int identity(1,1),pageid int,displayName varchar(200),parentid int)
	insert into #temppage 
	select pageId,displayname+''_Title'',parentId from TA_Tbl_Page where parentId=@pageid	order by orderBy
	Declare @Count int
	Declare @i int
	Declare @parentid int
	set @Count=(select COUNT(*)from #temppage)
	set @i=1
	while @i<=@Count
	begin
		insert into #tempResult
		select pageId,displayName,parentId from #temppage where id=@i
		set @parentid=(select pageid from #temppage where id=@i)
		insert into #tempResult
		select pageId,displayname+''_Title'',parentId from TA_Tbl_Page where parentId=@parentid order by orderBy
		set @i=@i+1
	end	
	select *,case when pageId IN(205,42,84,192,144,145,147,118,41,30,40,45,39,105,180,183,127,37,34,43,79,160,171,232,233,234,36,175,219,70,71,208,44,32,
	211,89,117,35,213,33,92,103,116) then 1 else 0 end ''ReportMenus'' from #tempResult order by id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Details]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroup_Details]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Fetches the Organization,Designation and UserGroup details for CC mail group.
-- =============================================
--exec Proc_TA_GetCCGroup_Details
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroup_Details] 
@UserGroupName varchar(250),
@LevelRights varchar(8000)
AS
BEGIN
	SET NOCOUNT ON;
    --Added by Gopinath on 9th MAy 2014 for loading organization details and session Level issues
    SELECT @LevelRights=COALESCE(@LevelRights+'','','''')+LevelId FROM TA_Tbl_LevelRights L
	inner join TA_Tbl_Usergroup U on L.GroupId=U.groupId
	where U.groupName=@UserGroupName
    declare @Script varchar(8000)
    set @Script=''''
    set @Script=@Script + ''select Id as CompanyId,name as CompanyName from TA_tbl_LevelDetails 
    where IsDeleted=0 and Id in (select distinct LevelId from TA_Tbl_EmployeeLevel where LevelId in (''+@LevelRights+'')) order by name''
    exec(@Script)
    --select TitleId as DesignationId,TitleName as DesignationName from TA_Tbl_title where TitleId in (select distinct DesignationId from TA_Tbl_EmployeeDesignation)
    select groupId as UserGroupId,groupname as UserGroupName from Ta_tbl_Usergroup where isDeleted=0 order by groupname
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getAllNews]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getAllNews]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		SENTHIL
-- ALTER  date: 15-Aug-07
-- Description:	Selecting News
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getAllNews]
   @userGroupName nvarchar(50)
AS	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END	
if(@userGroupName=''SuperAdmin'')
	begin  
		select NewsEvent_Id, 
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventFromDate,@dateFormat),'' '',''-'') 
		else CONVERT(VARCHAR, NewsEventFromDate, @dateFormat) end	
		as NewsEventFromDate,
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventToDate,@dateFormat),'' '',''-'') 
		else CONVERT(VARCHAR, NewsEventToDate, @dateFormat) end	
		as NewsEventToDate,
		NewsEventTitle	= (Case NewsEventTitle When '''' then ''Banner'' When NULL then ''Banner'' else NewsEventTitle End),NewsEventDescription, IsDeleted from ta_tbl_newsEvents order by TimeStamp desc
	END
else
	begin  
        select NewsEvent_Id,case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventFromDate,@dateFormat),'' '',''-'') 
		else CONVERT(VARCHAR, NewsEventFromDate, @dateFormat) end	
		as NewsEventFromDate,
		case when cast(@dateFormat as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, NewsEventToDate,@dateFormat),'' '',''-'') 
		else CONVERT(VARCHAR, NewsEventToDate, @dateFormat) end	as NewsEventToDate,
        NewsEventTitle	= (Case NewsEventTitle When '''' then ''Banner'' When NULL then ''Banner'' else NewsEventTitle End),
		NewsEventDescription, IsDeleted from ta_tbl_newsEvents where isdeleted=0 order by TimeStamp desc
  END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <23-Jan-2019 03:28 PM>
-- Description:	<Get Reporting to and Leave Sanctioning Person details of particular employee and which employees he is also the samething>
-- Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetAllandParticularEmployeeReportingTo_LeaveSanc]
	@EmpAutoID varchar(50)=null
AS
BEGIN	
	SET NOCOUNT ON;
	Declare @EmployeeAutoID int
	set @EmployeeAutoID=@EmpAutoID;
	--Each person, whose is the reportingTo and Leave Sanctioning.
	--Particular employee whose is reproting To and leave sacntioning
	;with cte
	as
	(
		select AutoId=Employee_Id,Employee_Code_Id,Employee_FirstName as empName,Reporting_To as reportingToID,Leave_Sanc_Authority as leaveSanc 
		from TA_Tbl_Employee where (@EmployeeAutoID	IS NULL OR Employee_Id=@EmployeeAutoID)
	)
	select	EmployeeID=C.Employee_Code_Id,
			EmployeeName=C.empName,
			E1.Employee_Code_Id +'' - ''+ E1.Employee_FirstName 
			+ case when E1.EmailId IS not null and E1.EmailId<>'''' then '' (''+ E1.EmailId +'')'' else '''' end as ReportingTo_EmpName,
			E2.Employee_Code_Id +'' - ''+ E2.Employee_FirstName + case when E2.EmailId IS not null and E2.EmailId<>'''' then '' (''+ E2.EmailId +'')'' else '''' end as LeaveSanc_EmpName from cte C
	inner join TA_Tbl_Employee E1 on C.reportingToID=E1.Employee_Id
	inner join TA_Tbl_Employee E2 on C.leaveSanc=E2.Employee_Id

	--Which persons,this employee is reproting To and leave sacntioning
	--Declare @EmployeeAutoID int
	set @EmployeeAutoID=@EmpAutoID;
	;with cte
	as
	(
		select AutoId=Employee_Id,Employee_Code_Id,Employee_FirstName as empName,Reporting_To as reportingToID,Leave_Sanc_Authority as leaveSanc 
		from TA_Tbl_Employee where (@EmployeeAutoID	IS not NULL and Employee_Id=@EmployeeAutoID)
	)
	select ReportingTo=E1.Employee_Code_Id+'' - ''+ E1.Employee_FirstName+ case when E1.EmailId IS not null and E1.EmailId<>'''' then '' (''+ E1.EmailId +'')'' else '''' end,Sanctioning='''' from cte C
	Left outer join TA_Tbl_Employee E1 on E1.Reporting_To=C.AutoId
	where E1.Employee_Id is not null
	union all
	select '''',Sanctioning=E2.Employee_Code_Id+'' - ''+E2.Employee_FirstName + case when E2.EmailId IS not null and E2.EmailId<>'''' then '' (''+ E2.EmailId +'')'' else '''' end from cte C
	Left outer join TA_Tbl_Employee E2 on E2.Leave_Sanc_Authority=C.AutoId
	where E2.Employee_Id is not null
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCityDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCityDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCityDetails]
	@ID int,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if @Type=''C''
		Begin
			SELECT L.Title AS city,L.Parent AS stateID	FROM TA_Tbl_Lookup L
			INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent INNER JOIN TA_Tbl_Lookup LK1 ON LK1.ID=LK.Parent WHERE L.Type=3 and l.ID =@ID
		end
	Else if @Type=''N''
		begin			
			SELECT L.Title AS country FROM TA_Tbl_Lookup L WHERE L.Type=1 and l.ID =@ID	
		end
	Else if @Type=''S''
		begin			
			SELECT L.Title AS state,L.Parent AS countryID FROM TA_Tbl_Lookup L INNER JOIN TA_Tbl_Lookup LK ON LK.ID=L.Parent
			WHERE L.Type=2 and l.ID =@ID	
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCommaSeparatedValues]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCommaSeparatedValues]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 03-May-2011
-- Description:	To get comma separated values by passing the data table as xml and also passing the column name
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCommaSeparatedValues]
(
	@xml xml
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @String varchar(max)
   Declare @Index int
   Set @Index = 0;
   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	set @String = (select E.Employee_Code_Id  + '','' 
	from OpenXML(@Index, ''/DocumentElement/Table'') 
	With (EmployeeAutoId Bigint ''EmployeeAutoId'') as xm 
	inner join TA_Tbl_Employee E on xm.EmployeeAutoId = E.Employee_Id
	for xml path(''''))
   Exec sp_xml_removedocument @Index
   --select @String
   SET @String = LEFT(@String, LEN(@String) - 1)
SELECT @String
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetClockID_FirstData]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetClockID_FirstData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016 14.46,,>
-- Description:	<Proc_Ta_GetClockID_FirstData>
-- Proc_Ta_GetClockID_FirstData 5,''07/23/2020 03:57:00 PM'',''07/23/2020'',''T''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetClockID_FirstData]
	@inClk_EmpId varchar(50),
	@strInDateTime varchar(30),
	@gstrClockDate varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''R'')
	begin
		select Clk_Id from TA_Tbl_Clockdetails 
		where clk_empid = @inClk_EmpId and (Clk_InDate+Clk_InTime) = 
		(SELECT Min(Clk_InDate+Clk_InTime) FROM TA_Tbl_Clockdetails 
		where clk_empid = @inClk_EmpId AND (Clk_InDate+Clk_InTime) > Cast(@strInDateTime as DateTime) 
		AND Clk_Date = Cast(@gstrClockDate as DateTime)  AND IsVoid = 0)
	end
	else if(@Type=''U'')
	begin
		SELECT Clk_Id FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND Clk_Date =  Cast(@gstrClockDate as DateTime)
		AND (Clk_InDate = '''' OR Clk_InDate IS NULL) AND Clk_OutDate <> '''' AND Clk_OutDate IS NOT NULL 
		AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND IsVoid = 0
	end
	else if(@Type=''T'')
	begin
		SELECT TOP 1 Clk_Id,Clk_Date,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails 
		WHERE Clk_EmpId = @inClk_EmpId AND Clk_Date = Cast(@gstrClockDate as DateTime)
		AND (Clk_OutDate = '''' OR Clk_OutDate IS NULL) AND Clk_InDate <> '''' AND Clk_InDate IS NOT NULL AND IsVoid = 0
		AND (Clk_InDate+Clk_InTime) <= Cast(@strInDateTime as DateTime) ORDER BY (Clk_InDate+Clk_InTime) DESC
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevelDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
create PROCEDURE [dbo].[Proc_TA_getLevelDetails]
(
	@levelId int
)
as
Begin
	--select a.levelID,a.levelName,b.* from ta_tbl_level a, ta_tbl_leveldetails b where a.levelId=b.levelID and a.levelID=@levelid
--SELECT     a.levelID , a.levelName , b.*
--FROM         TA_Tbl_Level a LEFT OUTER JOIN
 --                     Ta_Tbl_levelDetails b ON a.levelID = b.levelId
--WHERE     (a.levelID = @levelid)
select a.levelid,a.levelname,b.levelname as childLevelName,b.parentLevelId,b.levelid as childId from ta_tbl_level a left outer join ta_tbl_level b  on a.levelid=b.parentlevelid where b.isdeleted=0 and a.levelid=@levelId
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevelName]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevelName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_getLevelName]
(
	@levelId int='''',
	@UserGroupName nVarchar(250)='''',
	@UserLevelId nvarchar(4000)=''''
)
as
Begin
	select LevelName from ta_tbl_level where levelId=@levelId
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTakenInMonth]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTakenInMonth]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_GetLeaveTakenInMonth 32,1,''01/20/2010'',''01/20/2010'',0 
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveTakenInMonth]
@EmployeeId int,
@leaveTypeId int, 
@dtFromDate datetime, 
@dtTodate datetime,
@LeaveApplicationId int
as
BEGIN
	SET NOCOUNT ON;
declare @LeaveDays as float
if(@LeaveApplicationId=0)
BEGIN
set @LeaveDays=(
select isnull(sum(NumberOfDays),0.0) from TA_Tbl_LeaveApplication
inner join TA_Tbl_LeaveType on TA_Tbl_LeaveType.LeaveType_Id=TA_Tbl_LeaveApplication.LeaveType_Id
where Employee_Id=@EmployeeId and TA_Tbl_LeaveApplication.LeaveType_Id=@leaveTypeId
and TA_Tbl_LeaveApplication.Status!=''Rejected'' 
--and TA_Tbl_LeaveApplication.LeaveApplication_Id<>@LeaveApplicationId
and TA_Tbl_LeaveApplication.IsDeleted=0 
and TA_Tbl_LeaveApplication.Type=''Leave'' and
(
(
month(Leave_FromDate)=month(@dtFromDate) 
and year(Leave_FromDate)=year(@dtFromDate)
) 
or 
(month(Leave_ToDate)=month(@dtTodate) 
and year(Leave_ToDate)=year(@dtTodate)
)
)
and TA_Tbl_LeaveType.LeaveType=''CL''
)
END
else
BEGIN
set @LeaveDays=(
select isnull(sum(NumberOfDays),0.0) from TA_Tbl_LeaveApplication
inner join TA_Tbl_LeaveType on TA_Tbl_LeaveType.LeaveType_Id=TA_Tbl_LeaveApplication.LeaveType_Id
where Employee_Id=@EmployeeId and TA_Tbl_LeaveApplication.LeaveType_Id=@leaveTypeId
and TA_Tbl_LeaveApplication.Status!=''Rejected'' 
and TA_Tbl_LeaveApplication.LeaveApplication_Id<>@LeaveApplicationId
and TA_Tbl_LeaveApplication.IsDeleted=0 
and TA_Tbl_LeaveApplication.Type=''Leave'' and
(
(
month(Leave_FromDate)=month(@dtFromDate) 
and year(Leave_FromDate)=year(@dtFromDate)
) 
or 
(month(Leave_ToDate)=month(@dtTodate) 
and year(Leave_ToDate)=year(@dtTodate)
)
)
and TA_Tbl_LeaveType.LeaveType=''CL''
)
END
select @LeaveDays as LeaveDaysCount
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSummary]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Created By	:	Prabakaran.P
Created On	:	16-Dec-09
--Proc_TA_GetLeaveSummary ''12/01/2009'',''12/31/2009'',31
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSummary]
@LeaveFromDate datetime,
@LeaveToDate datetime,
@EmployeeId int
as
BEGIN
SET NOCOUNT ON;
select isnull(Sum(NumberOfDays),0.0) as NumberOfDays from TA_Tbl_LeaveApplication 
where Status=''Approved'' and IsDeleted=0 and IsBorrow=0 and Type<>''Comp Off''
and 
(
(Leave_FromDate between @LeaveFromDate and @LeaveToDate)
or
(Leave_ToDate between @LeaveFromDate and @LeaveToDate)
or
(@LeaveFromDate between Leave_FromDate and Leave_ToDate)
or
(@LeaveToDate between Leave_FromDate and Leave_ToDate)
) and Employee_Id=@EmployeeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSettingsByComId]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSettingsByComId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ======================================================
-- Author		:  Kumuthini.L
-- Create date		: 19-Apr-08
-- Description		: Get Leave Setting Details by Company Id
-- Procedure Name	: Proc_TA_GetLeaveSettingsByComId 
-- ======================================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSettingsByComId]		
(
	@CompanyId INT
)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Approval,FirstLevelIntimation,SecondLevelIntimation,ApprovalCC,ToMail_DailyReport,CCMail_DailyReport FROM TA_Tbl_LeaveSettings Where CompanyId=@CompanyId	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[Proc_TA_GetLeaveTypes_LeaveMaster]
AS  
begin
SET NOCOUNT ON;
SELECT LeaveType_Id,LeaveType FROM TA_Tbl_LeaveType Where IsDeleted=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeName]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveTypeName] 
	-- Add the parameters for the stored procedure here
	@leaveTypeId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LeaveType FROM TA_Tbl_LeaveType WHERE LeaveType_Id = @leaveTypeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLeaveTypeForservice]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLeaveTypeForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_Ta_GetLeaveTypeForservice]
	@INLEAVETYPEID INT
AS
BEGIN
	SET NOCOUNT ON;
    SELECT LEAVETYPE FROM TA_TBL_LEAVETYPE WHERE LEAVETYPE_ID = @INLEAVETYPEID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetailsById]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetLeaveTypeDetailsById]      
(      
 @LeaveId int,    
 @UserGroupName nVarchar(250)      
)      
AS      
Begin   
  SET NOCOUNT ON;   
  IF(@UserGroupName = ''SuperAdmin'')    
    BEGIN    
       SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,       
       (select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategory,EmployeeCategory as EmployeeCategorys,
              (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeType,EmployeeType as EmployeeTypes,
              Gender,(select Name from TA_Tbl_Religion where ID=Religion)as Religion,Religion as Religions
       FROM TA_Tbl_LeaveType Where LeaveType_Id=@LeaveId
    END    
 ELSE    
   BEGIN    
       SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategory,EmployeeCategory as EmployeeCategorys,
       (select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeType,EmployeeType as EmployeeTypes,
       Gender,(select Name from TA_Tbl_Religion where ID=Religion)as Religion
       ,Religion as Religions
        FROM TA_Tbl_LeaveType 
       Where IsDeleted=0 AND LeaveType_Id=@LeaveId      
   END  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[Proc_TA_GetLeaveDescription_LeaveMaster]
( @LeavetypeId INT )
AS  
Begin
  SET NOCOUNT ON;
	SELECT LeaveDescription FROM TA_Tbl_LeaveType Where LeaveType_Id=@LeavetypeId 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveConversation]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetLeaveConversation 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveConversation] 
	-- Add the parameters for the stored procedure here	
	@leaveApplicationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_LeaveConversation WHERE LeaveApplicationId = @leaveApplicationId Order By OrderBY Desc
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCommentsById]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveCommentsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_GetLeaveCommentsById 10 
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveCommentsById]
@LeaveApplicationId int
as
BEGIN
SET NOCOUNT ON;
declare @intOrderBy as int
declare @intCommentsBy as int
set @intOrderBy = (SELECT max(OrderBy) from TA_Tbl_LeaveConversation where LeaveApplicationId=@LeaveApplicationId)
set @intCommentsBy=(SELECT CommentsBy from TA_Tbl_LeaveConversation where OrderBy=@intOrderBy and LeaveApplicationId=@LeaveApplicationId)
select isnull(@intCommentsBy,0) as CommentsBy
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutForServiceDataProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Last punch(Max Punch) details
-- [Proc_Ta_GetLastOutForServiceDataProcess] 787,''04/05/2017'',1,2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLastOutForServiceDataProcess]
	-- Add the parameters for the stored procedure here
	@Employeecode varchar(50),
	@Date datetime,
	@CompanyId int,
	@intShiftId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @strLastOutDateTime datetime
	Declare @strLastInDateTime datetime
	Declare @strLastIn_DeviceID varchar(20)
	Declare @strFinalLastOut varchar(30)
	Declare @ShiftType bit
	Declare @EMPLOYEEAUTOID int
	Declare @InAndOut_Same int
	select @EMPLOYEEAUTOID=Employee_Id from TA_Tbl_Employee where SwipeCardNo=@Employeecode and Isdeleted=0
	SELECT @strLastOutDateTime=MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @Date AND Clk_OutDate IS NOT NULL AND IsVoid = 0	
	/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--if(@intShiftId=-1)
	--BEGIN
	--	CREATE TABLE #TEMPFreescan (SHIFTID INT)
	--	WHILE @intShiftId=-1
	--	BEGIN			
	--		set @DATE=DATEADD(d,-1,@DATE)
	--		DECLARE @QUERY VARCHAR(2000)   
	--		DECLARE @SHIFTID INT
	--		SET @SHIFTID=0
	--		DECLARE @ISDELETED INT				
	--		DECLARE @YEAR VARCHAR(5)
	--		DECLARE @MONTH VARCHAR(5)
	--		SET @YEAR=DATEPART(YEAR,@DATE)
	--		SET @MONTH=DATEPART(MONTH,@DATE)	
	--		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	--		SET @QUERY = ''	SELECT (TSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
	--						WHERE TSA.[YEAR]= '' + @YEAR + ''  AND  TSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = ''''''+ CONVERT(VARCHAR(10),@EMPLOYEEAUTOID) +'''''' ''	
	--		INSERT INTO #TEMPFreescan EXEC(@QUERY)
	--		SET @SHIFTID = (SELECT SHIFTID FROM #TEMPFreescan)
	--		SET @SHIFTID = ISNULL(@SHIFTID,0) 
	--		DELETE FROM #TEMPFreescan
	--		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	--		IF(@SHIFTID = 0)
	--			BEGIN
	--				SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
	--								WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' +  CONVERT(VARCHAR(10),@EMPLOYEEAUTOID) +''''''''
	--				INSERT INTO #TEMPFreescan EXEC(@QUERY)
	--				SET @SHIFTID = (SELECT SHIFTID FROM #TEMPFreescan)
	--				SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--				DELETE FROM #TEMPFreescan
	--			END
	--		IF(@SHIFTID != 0)
	--			BEGIN			
	--				IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
	--					BEGIN
	--						SET @SHIFTID = ISNULL(@SHIFTID,0)			
	--					END
	--			END		
	--		-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	--		IF(@SHIFTID = 0)
	--			BEGIN
	--				SET @SHIFTID = (SELECT @SHIFTID FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID)
	--				SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--				IF(@SHIFTID = 0)
	--					BEGIN					
	--						SET @SHIFTID = (SELECT SHIFT_ID FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0)
	--						SET @SHIFTID = ISNULL(@SHIFTID ,0)
	--					END
	--			END
	--		IF(@SHIFTID > 0)
	--			BEGIN
	--				SELECT @intShiftId=ISNULL(@SHIFTID,0) FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
	--			END
	--		ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
	--			BEGIN
	--				SELECT @intShiftId=@SHIFTID
	--			END		
	--	end
	--	DROP TABLE #TEMPFreescan
	--end
	--Getting the shift Type for checking whether the type is freescan or function key
	/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--select @ShiftType=ShiftType from TA_Tbl_Shift where Shift_Id=@intShiftId and Isdeleted=0
	set @strFinalLastOut=''''
	--select @ShiftType
    -- Insert statements for procedure here
    /**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
	--First and last punch concept should be worked for function key logic too*/
	--if(@ShiftType=1)
	--begin
		IF((SELECT ISNULL(FIRSTANDLAST,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID=@COMPANYID)=1)
		BEGIN
			--select ''entered''
			/**Below line is added by Manikandan.R on 28-May-2019 06:12 PM
			--First and last punch concept should be worked for function key logic too*/
			IF((SELECT COUNT(*) FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @EMPLOYEECODE AND CLK_DATE = @DATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0)>1)
			BEGIN
				SELECT @strLastInDateTime=MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_InTime),13,21)))
				FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @Date AND Clk_InDate IS NOT NULL AND IsVoid = 0			
			END
			/**Below line is commented by Manikandan.R on 28-May-2019 06:12 PM
			--First and last punch concept should be worked for function key logic too*/
			--SELECT @strLastIn_DeviceID=Clk_InDeviceId
			--FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @Date AND Clk_InDate IS NOT NULL AND IsVoid = 0
			--and Clk_InDate+Clk_InTime=@strLastInDateTime
			--select @InAndOut_Same=count(TYPE) from ta_tbl_entrance_inoutdetails EIO 
			--inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
			--where T.Terminal_ReaderID=@strLastIn_DeviceID
			--if @InAndOut_Same=1
			--begin
			--	set @strLastInDateTime=null
			--end			
		END
	--end
	--select @strLastOutDateTime,@strLastInDateTime
	IF (@strLastOutDateTime is not null and @strLastInDateTime is not null and @strLastOutDateTime!=''1900-01-01 00:00:00.000'' and  @strLastInDateTime!=''1900-01-01 00:00:00.000'')
	BEGIN
		IF (CONVERT(DATETIME,@strLastOutDateTime) > Convert(datetime,@strLastInDateTime))
        BEGIN
			SET @strFinalLastOut = @strLastOutDateTime;
		END
        ELSE
        BEGIN
			SET @strFinalLastOut = @strLastInDateTime;
		END
	END
    ELSE IF (@strLastOutDateTime != '''' and @strLastOutDateTime!=''1900-01-01 00:00:00.000'')
	BEGIN
		SET @strFinalLastOut = @strLastOutDateTime;
	END
	ELSE IF (@strLastInDateTime != '''' and @strLastInDateTime!=''1900-01-01 00:00:00.000'')
	BEGIN
		SET @strFinalLastOut = @strLastInDateTime;
	END
	SELECT LastOut=@strFinalLastOut	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Last punch(Max Punch) details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLastOutForService]
	-- Add the parameters for the stored procedure here
	@Employeecode varchar(50),
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	AS LastOut FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Employeecode AND Clk_Date = @Date AND Clk_OutDate IS NOT NULL AND IsVoid = 0	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLastOutDetailsForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLastOutDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetLastOutDetailsForService]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo VARCHAR(50),
	@inDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) AS LastOut 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @inDate AND Clk_OutDate IS NOT NULL AND IsVoid = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastOutDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLastOutDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLastOutDetails]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50), 
	@inDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MAX(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_OutTime),13,21))) 
	AS LastOut FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @inDate AND Clk_OutDate IS NOT NULL AND IsVoid = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLastLogin]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLastLogin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetLastLogin]
(
	@UserName VARCHAR(15)
)
AS
begin
	SELECT LastLoginTime,LastLogoutTime FROM TA_Tbl_Login WHERE UserName=@UserName
end
SET QUOTED_IDENTIFIER OFF' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLanguageDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLanguageDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetLanguageDetails
Description	:	Get All Language details
Tables Included	:	 TA_Tbl_MultiLingual
Created By	:	Prabakaran
Created On	:	17-Nov-07
Modified By	:	
Modified On	:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetLanguageDetails] 
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM TA_Tbl_MultiLingual order by Language_Name
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInformToEmployee]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetInformToEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	14-May-2014
-- Description	:	Get The All Active Employee List For Leave Application Inform To Field Value
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetInformToEmployee]
AS
BEGIN
	SELECT Employee_FirstName + (CASE WHEN ISNULL(Employee_MiddleName, '''') <> '''' THEN '' '' + Employee_MiddleName ELSE '''' END) + (CASE WHEN ISNULL(Employee_LastName, '''') <> '''' THEN '' '' + Employee_LastName ELSE '''' END) [EmployeeName] FROM TA_Tbl_Employee
		WHERE IsDeleted = 0 AND Employee_Status = 1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetInAndOutPunchDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetInAndOutPunchDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 12.45PM>
-- Description:	<Get in and Out Punch Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetInAndOutPunchDetails]
	@inClk_Id bigint,
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''O'')
	begin
		SELECT Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_Id = @inClk_Id
	end
	else if(@Type=''I'')
	begin
		SELECT Clk_Date,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_Id = @inClk_Id
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidaySettings]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHolidaySettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetHolidaySettings]  
AS  
BEGIN  
	SELECT hs.Global_Maxdays,hs.Yearly_Maxdays,hs.YearSettingId FROM TA_Tbl_HolidaySettings hs
	inner join TA_TBL_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId   
	where ys.IsActive=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeOTEligible]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeOTEligible]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_GetEmployeeOTEligible
Description		:	Get whether the OT is Eligible for the particular Employee
Tables Included          	:	TA_Tbl_Employee
Created By		:	Kumuthini.L
Created On		:	19-Feb-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeOTEligible] 
(
   @Employee_Code_Id nVarchar(25)
)
AS
SELECT OT_Eligible FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeName]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeName] 
	-- Add the parameters for the stored procedure here	
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Employee_FirstName + Space(1) + Employee_LastName as EmployeeName FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeID 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeLingual]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeLingual]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		S.Christopher
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeLingual]
	@EmployeeId int
AS
BEGIN
	SET NOCOUNT ON;
	 if exists(SELECT LanguageId FROM TA_Tbl_EmployeeLingual WHERE EmployeeId = @EmployeeId)
	 begin
		SELECT Resource_File_Name,ML.Language_Id FROM TA_Tbl_MultiLingual ML
		inner join TA_Tbl_EmployeeLingual EL on ML.Language_Id=EL.LanguageId
		WHERE EmployeeId=@EmployeeId
	 end
	 else
	 begin
		select Resource_File_Name,Language_Id from TA_Tbl_MultiLingual where Language_Id=1
	 end
END
---------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeFromCMITechDevice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		< Velumani P>
-- Create date: < 25-Jan-2020 >
-- Description:	<Get Employee Data and save into its table>
/*
Proc_TA_GetEmployeeFromCMITechDevice
''<DocumentElement>
  <MyDt>
    <EmployeeName>Anandaprasad</EmployeeName>
    <EmployeeId>2</EmployeeId>
  </MyDt>
  <MyDt>
    <EmployeeName>RENJUKUMAR</EmployeeName>
    <EmployeeId>3</EmployeeId>
  </MyDt>
</DocumentElement>''
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeFromCMITechDevice]
	-- Add the parameters for the stored procedure here
	@Xml XML

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Index INT 
	set @Index= 0
	declare @Error nvarchar(Max)
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	create table #ImportMaster 
	(
		id bigint identity(1,1),
		Emp_FirstName nvarchar(max),
		Emp_id nvarchar(max)
	)
	insert into  #ImportMaster
	select 
		rtrim(ltrim(EmployeeName)),
		rtrim(ltrim(EmployeeId))
		from OPENXML(@Index, ''/DocumentElement/MyDt'',2)
	WITH(
			EmployeeName  nvarchar(max),
			EmployeeId   nvarchar(max)			
		  ) AS OT 
		  
	delete from TA_Tbl_CMITechSyncEmployeeInfo
	
	INSERT INTO TA_Tbl_CMITechSyncEmployeeInfo
	select Emp_FirstName, Emp_id from #ImportMaster

	drop table #ImportMaster	
		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailSchedule]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailSchedule]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--select * from TA_tbl_EmailScheduleStatus
--Proc_TA_GetEmailSchedule ''Weekly''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailSchedule]
(
 @Frequency varchar(20)
)
AS
BEGIN
	create table #TempEmailSchedule(ScheduleId int)
	if(@Frequency = ''Daily'')
	BEGIN
			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = ''Daily'' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			
			select ScheduleId from TA_Tbl_EmailSchedule
			where Frequency = ''Daily''
			and cast((CONVERT(varchar(10),getdate(),101) + '' ''  + TimeToSend) as datetime) <= GETDATE()
			and ScheduleId not in (select scheduleId from #TempEmailSchedule)
			and IsDeleted = 0 and Enabled = 1
	END	
	else if(@Frequency = ''Weekly'')
	BEGIN
			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = ''Weekly'' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			declare @WeekDay varchar(10)
			set @WeekDay = (select DATEname(DW,GETDATE()))
			select ScheduleId from TA_Tbl_EmailSchedule
			where Frequency = ''Weekly''
			and DayToSend = @WeekDay
			and cast((CONVERT(varchar(10),getdate(),101) + '' ''  + TimeToSend) as datetime) <= GETDATE()
			and ScheduleId not in (select scheduleId from #TempEmailSchedule)
			and IsDeleted = 0 and Enabled = 1
	END
	else if(@Frequency = ''Monthly'')
	BEGIN
			insert into #TempEmailSchedule select ES.ScheduleId from TA_tbl_EmailScheduleStatus ESS
			inner join TA_Tbl_EmailSchedule ES on ES.ScheduleId = ESS.ScheduleId 
			where ES.Frequency = ''Monthly'' and Status=1
			and cast(Convert(varchar(10),SentDate,101) as datetime) = cast(Convert(varchar(10),GETDATE(),101) as datetime) 
			declare @CurrentDate int
			set @CurrentDate = (select DATEPART(D,GETDATE()))
			declare @LastDateOfCurrentMonth int
			set @LastDateOfCurrentMonth = (SELECT DATEPART ( D , DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),
            DATEADD(MONTH, 1, GETDATE()))))
			if(@CurrentDate = @LastDateOfCurrentMonth)
			BEGIN
				select ScheduleId from TA_Tbl_EmailSchedule
				where Frequency = ''Monthly''
				and DateToSend >= @CurrentDate
				and cast((CONVERT(varchar(10),getdate(),101) + '' ''  + TimeToSend) as datetime) <= GETDATE()
				and ScheduleId not in (select scheduleId from #TempEmailSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
			ELSE
			BEGIN
				select ScheduleId from TA_Tbl_EmailSchedule
				where Frequency = ''Monthly''
				and DateToSend = @CurrentDate
				and cast((CONVERT(varchar(10),getdate(),101) + '' ''  + TimeToSend) as datetime) <= GETDATE()
				and ScheduleId not in (select scheduleId from #TempEmailSchedule)
				and IsDeleted = 0 and Enabled = 1
			END
	END
	drop table #TempEmailSchedule
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailReportNotSendedDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailReportNotSendedDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-02-2013
-- Description:	Get the Rescheduling Email Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailReportNotSendedDetails]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ReScheduleid,id,FromMailId ,ToEmailIds ,CCEmailIds,EmailSubject ,Content ,Attachment from Ta_tbl_EmailReportNotSendedDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.MANIKANDAN>
-- Create date: <01-APRIL-2019 04:39 PM>
-- Description:	<GET THE EMPLOYEE DETAILS FOR EMAIL TRIGGERING BASED ON THE SELECTION AND ACTIVE STATUS>
-- Proc_TA_GetEmployeeDetails_EmailTriggering 1,1,''01:00''
-- Proc_TA_GetEmployeeDetails_EmailTriggering 2,''01:00''
-- Proc_TA_GetEmployeeDetails_EmailTriggering 3,''01:00''
-- Proc_TA_GetEmployeeDetails_EmailTriggering 4,''01:00''
-- Proc_TA_GetEmployeeDetails_EmailTriggering 5,''01:00''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails_EmailTriggering]
	@Scheduleid INT,
	@Option int,
	@Time varchar(5)
AS
BEGIN
	SET NOCOUNT ON;
	Create table #TempEmployeeDetails(Autoid int identity(1,1),Employee_Code_Id varchar(50),EmailId varchar(200))
	Declare @ScheculeName varchar(max)
	select @ScheculeName =ScheduleName from TA_Tbl_EmailSchedule where ScheduleId=@Scheduleid
	if(@ScheculeName=''Warning Letter Late Entry'' or @ScheculeName=''Warning Letter Early Exit'')
	BEGIN
		Declare @monthStartDate datetime
		Declare @monthEndDate datetime
		select @monthStartDate=DATEADD(month,DATEDIFF(month,0,getdate()),0),@monthEndDate=dateadd(d,-1,DATEADD(month,DATEDIFF(month,0,getdate())+1,0))
		Insert into #TempEmployeeDetails
		SELECT E.Employee_Code_Id,EmailId FROM TA_Tbl_EmailScheduled_Employees ESE
		INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
		where ScheduleId=@Scheduleid
		and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'''')
		and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
		and (CONVERT(datetime,convert(varchar(11),SentDate)) between @monthStartDate and @monthEndDate) and Status=1)
	END
	ELSE
	BEGIN	
		Insert into #TempEmployeeDetails
		SELECT E.Employee_Code_Id,EmailId FROM TA_Tbl_EmailScheduled_Employees ESE
		INNER JOIN TA_Tbl_Employee E on ESE.Employee_id=E.Employee_Id	
		where ScheduleId=@Scheduleid
		and E.Employee_Status=1 and E.Isdeleted=0 and (EmailId is not null and EmailId<>'''')
		and E.Employee_Code_Id not in(select to_mail from TA_tbl_EmailScheduleStatus where ScheduleId=@Scheduleid
		and CONVERT(datetime,convert(varchar(11),SentDate))=CONVERT(datetime,convert(varchar(11),getdate())) and Status=1)
	END
	DECLARE @START INT
	SET @START=1
	DECLARE @TOTAL INT
	SELECT @TOTAL=COUNT(EMPLOYEE_CODE_ID) FROM #TEMPEMPLOYEEDETAILS
	WHILE @START<=@TOTAL
	BEGIN
		Declare @Employee_Code_id varchar(50)
		Declare @Shift_Id int
		select @Employee_Code_id=Employee_Code_Id from #TEMPEMPLOYEEDETAILS Where Autoid=@START
		SELECT @Shift_Id=Shift_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@Employee_Code_id
		and Date=CONVERT(datetime,CONVERT(varchar(11),GETDATE())) and ProcessFlag=1
		IF (@Shift_Id is not null and @Shift_Id<>'''' and @Shift_Id<>0)
		BEGIN
			DECLARE @Shift_StartTime DATETIME
			DECLARE @Shift_EndTime DATETIME
			DECLARE @addAndSubtractvalue INT
			DECLARE @finalTimings DATETIME
			SELECT @Shift_StartTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_StartTime,@Shift_EndTime=CONVERT(datetime,CONVERT(varchar(11),GETDATE()))+Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@Shift_Id AND Isdeleted=0
			set @addAndSubtractvalue=CONVERT(int,SUBSTRING(@Time,0,charindex('':'',@time)))*60+CONVERT(int,SUBSTRING(@Time,charindex('':'',@time)+1,LEN(@time)))
			--AFTER SHIFT START TIME
			IF (@Option=1 OR @Option=2)
			BEGIN
				IF(@Option=2)
				BEGIN
					SET @addAndSubtractvalue=-1*@addAndSubtractvalue
				END			
				set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_StartTime)
			END		
			--AFTER SHIFT END TIME
			ELSE IF (@Option=3 OR @Option=4)
			BEGIN
				IF(@Option=4)
				BEGIN
					SET @addAndSubtractvalue=-1*@addAndSubtractvalue
				END	
				set @finalTimings=DATEADD(minute,@addAndSubtractvalue,@Shift_EndTime)			
			END
			--CUSTOM TIMINGS
			ELSE IF @Option=5
			BEGIN		
				--SELECT DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
				set @finalTimings=DATEADD(minute,@addAndSubtractvalue,CONVERT(datetime,CONVERT(varchar(11),GETDATE())))
			END
			--SELECT @Shift_StartTime
			if(@finalTimings<=GETDATE())
			BEGIN
				set @START=@START+1
				continue;
			END
			ELSE
			BEGIN
				Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
			END
		END
		ELSE
		BEGIN
			Delete from #TEMPEMPLOYEEDETAILS Where Autoid=@START
		END		
		set @START=@START+1
	END
	select * from #TEMPEMPLOYEEDETAILS
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeDetails]       
-- Proc_GetEmployeeDetails ''EIT02'',1.2,1.2      
 -- Add the parameters for the stored procedure here      
 @CardNo VARCHAR(50)=NULL,
 @EmployeeName VARCHAR(100)=NULL,
 @EmployeeId VARCHAR(50)=NULL,
 @EmpCategory VARCHAR(100)=NULL,
 @EmployeeType VARCHAR(100)=NULL,
 @Designation VARCHAR(100)=NULL,
 @Gender VARCHAR(50)=NULL,
 @Month varchar(100)=NULL,
 @Year varchar(50)=NULL,
 @UserGroupName VARCHAR(250)=NULL,
 @GradeLevel VARCHAR(100)=NULL,
 @parentLevelId INT =NULL,
 @EmpId VARCHAR(50)=NULL,
 @PresentDays NUMERIC(18,1)=NULL,
 @Difference_Days NUMERIC(18,1)=NULL,
 @Status varchar(50)
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
    -- Insert statements for procedure here      
 IF @Status=''Update''     
  BEGIN      
    UPDATE TA_Tbl_AttendenceData SET PresentDays=@PresentDays,Difference_Days=@Difference_Days      
    WHERE EmpId=@EmpId 
    SELECT 0     
   END      
  ELSE IF @Status=''Select''  
  BEGIN     
 SELECT EmpId,PresentDays,OD,EL,CL,SL,LOP_Absent,Difference_Days FROM TA_Tbl_AttendenceData      
 END  
END ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 31-07-2014
-- Description:	To get the employee id from temporary shift allocation table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeDetailFromTempShiftAllocation]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT EmployeeId FROM TA_Tbl_TempShiftAllocation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeCodeID]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeCodeID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeCodeID]
@Employee_ID as int
AS
BEGIN
	select Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where Employee_ID=@Employee_ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoIdForImport]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeAutoIdForImport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoIdForImport]
@Employee_Code_Id as nvarchar(30)
AS
BEGIN
	select Employee_Id,Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where isdeleted=0 and employee_status=1 and Employee_Code_Id=@Employee_Code_Id 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeAutoId]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeAutoId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <ALTER  Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeAutoId]
@Employee_Code_Id as nvarchar(30)
AS
BEGIN
	select Employee_Id,Employee_code_Id,SwipeCardNo,DateOfJoining from ta_tbl_employee where Employee_Code_Id=@Employee_Code_Id
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmpforShift]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmpforShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  procedure [dbo].[Proc_TA_GetEmpforShift]    
(    
@EmpID INT    
)    
AS    
Begin
	SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + '''' + Employee_LastName AS ''Employee Name'' FROM TA_Tbl_Employee WHERE Employee_Id=@EmpID and 
	Isdeleted=0 and Employee_Firstname<>''Administrator'' 
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailScripts]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailScripts]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_GetEmailScripts  
Description		: Get ScriptText Based on the ScriptType  
Tables Included : TA_TBL_EmailScripts  
Created By		: Prabakaran  
Created On		: 20-Sep-07  
Modified By		:  
Modified On		:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailScripts]  
@ScriptType nvarchar(100)  
as  
BEGIN
	Select * from TA_TBL_EmailScripts where ScriptType=@ScriptType  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInPunchTypeForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetFirstInPunchTypeForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GetFirstInPunchTypeForService] ''1002'',''2015-04-06''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetFirstInPunchTypeForService]
	-- Add the parameters for the stored procedure here
	@INSWIPECARDNO VARCHAR(50),
	@INDATE DATETIME
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
	SELECT Clk_InPunchType AS FirstIn 
	FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @INSWIPECARDNO AND CLK_DATE = @INDATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0
	order by Clk_InTime
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetFirstInDetailsForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetFirstInDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	Getting First In punch details for processing
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetFirstInDetailsForService]
	-- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
	@INSWIPECARDNO VARCHAR(50),
	@INDATE DATETIME
AS
BEGIN
	-- SET NOCOUNT ON ADDED TO PREVENT EXTRA RESULT SETS FROM
	-- INTERFERING WITH SELECT STATEMENTS.
	SET NOCOUNT ON;
    -- INSERT STATEMENTS FOR PROCEDURE HERE
	SELECT MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),CLK_INDATE,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,CLK_INTIME),13,21))) AS FIRSTIN 
	FROM TA_TBL_CLOCKDETAILS WHERE CLK_EMPID = @INSWIPECARDNO AND CLK_DATE = @INDATE AND CLK_INDATE IS NOT NULL AND ISVOID = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetFirstInDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetFirstInDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetFirstInDetails]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50), 
	@inDate varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + SUBSTRING(CONVERT(VARCHAR,Clk_InTime),13,21))) 
	AS FirstIn FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date =  @inDate AND Clk_InDate IS NOT NULL AND IsVoid = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetExpInfo]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetExpInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetExpInfo]
AS
BEGIN
	select InstalledDate,DemoExpiryDate from TA_Tbl_Demo
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeesDetailsForDuplicationChecking]
	@EmployeeIDs int
AS
BEGIN	
	SET NOCOUNT ON;	
	Select Employee_Status,Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmployeeIDs	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeSpecificDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeSpecificDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <17-07-2019>
-- Description:	<Getting Employee details for reporting to>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmployeeSpecificDetails]
AS
BEGIN
	SET NOCOUNT ON;

    SELECT e.Employee_Id,(e.Employee_FirstName + '' - '' +(e.Employee_Code_Id)) as Employee_FirstName FROM TA_Tbl_Employee e 
	where e.Isdeleted=0 and e.Employee_Firstname<>''Administrator'' and ISNULL(e.InActive_Status,0)=0   ORDER BY e.Employee_FirstName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHelpContent]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHelpContent]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetHelpContent]	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT Header,Paragraph from ta_tbl_HelpContent
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetGroupNameForEmployee]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetGroupNameForEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_GetGroupNameForEmployee]
(
   @EmployeeId int
)
AS
select ug.groupName from TA_Tbl_Employee emp,TA_Tbl_Usergroup ug where emp.UserGroup_Id = ug.groupId and ug.isDeleted = 0 and emp.Employee_Id = @EmployeeId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getGroupNameById]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getGroupNameById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- Create date: 13-Aug-07
-- Description:	getting usergroup by id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getGroupNameById]
	(
		@groupId int		
	)
AS
BEGIN
	select * from ta_tbl_userGroup where groupId= @groupId
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetVehicleDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetVehicleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetVehicleDetails] as      
 SELECT VehicleId,VehicleNo FROM TA_Tbl_Transportation_Vehicle Where IsDeleted=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserRights]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetUserRights]
(
	@groupId int
)
AS
BEGIN
	select * from ta_tbl_userrights where groupID=@groupId  and isdeleted=0 and pageid in (select pageID from ta_tbl_page where parentID!=999)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenus]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserMenus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'  
-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <26/jul/07>    
-- Description: Getting Left Menu>    
-- =============================================    
--Proc_TA_GetUserMenus 2,1,''''
CREATE PROCEDURE [dbo].[Proc_TA_GetUserMenus]
(    
 @parentId int,    
 @groupId int,  
 @strType varchar(20)     
)    
AS    
BEGIN    
if(@strType!=''Standard'')  
	BEGIN
		if (@parentId=0)    
			Begin    			
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex(''/'',ta.path))+''/''+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID in (select						pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1))order by				orderby
			End    
		Else    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex(''/'',ta.path))+''/''+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page	ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID in (select pageID from					ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby
			End  
		END  
else   
	BEGIN  
		if (@parentId=0)    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex(''/'',ta.path))+''/''+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID not in (20,24,25,				69,96,97,98,108,110)and ts.pageID in (select pageGroupID from	ta_tbl_userRights where groupId=@groupId and (addPrv=1 or					modifyPrv=1 or deletePrv=1 or viewPrv=1))order by orderby
			End    
		Else    
			Begin    
				select ts.pageId,ts.displayName,substring(ta.path,0,charindex(''/'',ta.path))+''/''+ts.path as path,ts.parentid,ts.orderBy  from				ta_tbl_page ta inner join ta_tbl_page ts on ts.parentid=ta.pageid where ts.parentid=@parentid and ts.pageID not in (20,24,25,				69,96,97,98,108,110)and ts.pageID in (select pageID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=				1 or deletePrv=1 or viewPrv=1))order by orderby
			End  
	END      
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUserMenu]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUserMenu]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <26/jul/07>    
-- Description: Getting Left Menu>    
-- [dbo].[Proc_TA_GetUserMenu]  0,1,''''  
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_GetUserMenu]   
(    
	@parentId int,    
	@groupId int,  
	@strType varchar(20)     
)    
AS    
BEGIN 
	SET NOCOUNT ON; 
	declare @Express varchar(800)  
	declare @values varchar(800)  
	if(@strType=''Express'')   
	begin  
		if (@parentId=0)    
		begin  
			set @values='' and pageID not in(20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,36,37,38,39,43,45,48,49,53,60,65,67,72,75,77,78,79,80,93,99,100,102,103,105,107,106,108,116,118,127,127,130,12,117,172,173,174,175,171) ''  
			set @Express=''select * from ta_tbl_page where parentID=''+ CONVERT(varchar(20), @parentId)  
			set @Express=@Express + '' and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=''+convert(varchar(20),@groupId)+'' and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) ''  
			if((select COUNT(*) from TA_Tbl_LIC_Details)>0)  
			begin  
				exec(@Express)  
			end  
			else
			begin  
				set @Express= @Express + @values +'' order by orderby''  
				exec(@Express)
			end  
		end  
		else  
		begin  
			set @values='' and pageID not in(20,24,25,69,96,97,98,108,110,133,39,45,37,38,65,105,36,37,38,39,43,45,48,49,53,60,65,67,72,75,77,78,79,80,93,99,100,102,103,105,107,106,108,116,118,127,127,130,12,117,172,173,174,175,171) ''  
			set @Express=''select * from ta_tbl_page where parentID=''+ CONVERT(varchar(20), @parentId)  
			set @Express=@Express + '' and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=''+ CONVERT(varchar(20), @groupId ) +'' and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) ''  
			if((select COUNT(*) from TA_Tbl_LIC_Details)>0)  
			begin  
				set @Express= @Express +'' order by orderby''  
				exec(@Express)  
			end  
			else  
			begin  
				set @Express= @Express + @values +'' order by orderby''  
				exec(@Express)  
			end  
		end  
	End  
	else if(@strType!=''Standard'')  
	BEGIN  
		if (@parentId=0)    
		Begin    
			select * from ta_tbl_page where parentID=0 and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby 
		End    
		Else    
		Begin    
			select * from ta_tbl_page where parentID=@parentId and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby    
		End  
	END  
	else  
	BEGIN
		if (@parentId=0)    
		Begin
			select * from ta_tbl_page where parentID=0 and pageID not in (20,24,25,69,96,97,98,110,133,93,116,127,130,179,228,174)   
			and pageID in (select pageGroupID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby    
		End   
		Else   
		Begin
			select * from ta_tbl_page where parentID=@parentId and pageID not in (20,24,25,69,96,97,98,110,133,93,116,127,130,179,228,174)    
			and  pageID in (select pageID from ta_tbl_userRights where ParentIdForSubMenu is null and groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby    
		End
	END
END ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroups]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getUserGroups]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- Create date: 13-Aug-07
-- Description:	Getting User groups
-- =============================================
--Proc_TA_getUserGroups ''User''s''
CREATE PROCEDURE [dbo].[Proc_TA_getUserGroups]
(
@GroupName nvarchar(50) 
)
AS
if(@GroupName = '''' or @GroupName is null)
BEGIN
	select * from ta_tbl_usergroup where isdeleted=0 order by groupName
END
else
BEGIN
 select * from ta_tbl_usergroup where groupName like cast(''%''+@GroupName+''%'' as nvarchar(50)) and isdeleted=0 order by groupName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getUserGroupName]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getUserGroupName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
-- =============================================  
-- Author:  sashma  
-- Create date: 30-Jul-2010  
-- Description: Getting User group name  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_getUserGroupName]  
(  
@GroupId int   
)  
AS  
select groupName from ta_tbl_usergroup where groupId=@GroupId  
  ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUsergroupDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUsergroupDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetUsergroupDetails]
AS
BEGIN
	SET NOCOUNT ON
	SELECT groupId,groupName FROM ta_tbl_usergroup WHERE IsDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingIdForWin]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearSettingIdForWin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetYearSettingIdForWin]
	-- Add the parameters for the stored procedure here
	@ShiftDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @YearSettingsId int
	SELECT @YearSettingsId=YearSettings_Id FROM TA_Tbl_YearSetting WHERE FromDate <= @ShiftDate AND ToDate >= @ShiftDate
	if @YearSettingsId=''''
		begin
			set @YearSettingsId=0
		end
	select @YearSettingsId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetYearSettingIdForService]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetYearSettingIdForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GetYearSettingIdForService]
	-- Add the parameters for the stored procedure here
	@date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT YearSettings_Id FROM TA_Tbl_YearSetting WHERE FromDate <=@date and ToDate>= @date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearSettingId]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearSettingId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--select * from ta_tbl_yearSetting
-- Proc_TA_GetYearSettingId ''2011/03/30'',''2011/03/31'' 
CREATE PROCEDURE [dbo].[Proc_TA_GetYearSettingId] 
	-- Add the parameters for the stored procedure here
	@FromDate datetime,
	@ToDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	if exists(select yearsettings_Id from ta_tbl_yearSetting where ToDate = @FromDate)
		begin
			if exists(select yearsettings_Id from ta_tbl_yearSetting where FromDate=@ToDate)
				begin
					select ''Apply Induvial records''
				end
			else
				begin
					select YearSettings_Id from ta_tbl_yearSetting where (@FromDate between FromDate and ToDate) AND
					(@ToDate between FromDate and ToDate)
				end
		end
	else
		begin
			select YearSettings_Id from ta_tbl_yearSetting where (@FromDate between FromDate and ToDate) AND
					(@ToDate between FromDate and ToDate)
		end
 --   if not exists((select yearsettings_Id from ta_tbl_yearSetting where ToDate = ''2011/03/30'') union all (select yearsettings_Id from ta_tbl_yearSetting where FromDate = ''2011/03/30''))
 --   --where dateadd(day,(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=1),ToDate) = @FromDate and 
 -- -- dateadd(day,(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=1),FromDate) = @ToDate)
	--	begin
	--	end
	--else
	--	begin
	--	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetYearAvailedLeaveDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetYearAvailedLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_employee where employee_Code_id=''787''
-- =============================================
-- Author:		Manikandan
-- Create date: 25-07-2017
-- Description:	Getting Current Year Leave Details
-- [dbo].[Proc_TA_GetYearAvailedLeaveDetails] 48,787787
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetYearAvailedLeaveDetails]
	@EmployeeId INT = NULL,
	@EmployeeCode VARCHAR(60) = NULL
AS
BEGIN
	SET NOCOUNT ON;
	Declare @CurrentYearAvailedLeaves decimal(18,1)
	Declare @CurrentMonthAvailedLeaves decimal(18,1)
	Declare @CurrentYearPendingLeaves decimal(18,1)
	set @CurrentYearPendingLeaves =0
	set @CurrentMonthAvailedLeaves =0
	set @CurrentYearAvailedLeaves =0
	SELECT @CurrentYearAvailedLeaves=isnull(sum(LA.NumberOfDays),0) FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '''') OR E.Employee_Code_Id = @EmployeeCode) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN (''Rejected'', ''Canceled'')
	SELECT @CurrentMonthAvailedLeaves=isnull(sum(LA.NumberOfDays),0)FROM TA_Tbl_LeaveApplication LA
		LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
		INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
	WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
		((@EmployeeCode IS NULL OR @EmployeeCode = '''') OR E.Employee_Code_Id = @EmployeeCode) AND
		DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
		LA.IsDeleted = 0 AND LA.[Status] NOT IN (''Rejected'', ''Canceled'')
	SELECT @CurrentYearPendingLeaves=isnull(sum(LA.NumberOfDays),0)FROM TA_Tbl_LeaveApplication LA
		LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
		INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
		INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
	WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
		((@EmployeeCode IS NULL OR @EmployeeCode = '''') OR E.Employee_Code_Id = @EmployeeCode) AND
		DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
		LA.IsDeleted = 0 AND LA.[Status] IN (''Pending'')
	select @CurrentYearAvailedLeaves as currentYear,@CurrentMonthAvailedLeaves as currentMonthAvailed,@CurrentYearPendingLeaves as currentmonthPending
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationVehicleDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified by	:	P.prabakaran
Modified on	:	07-Feb-08
*/
CREATE   Procedure [dbo].[Proc_TA_GetTransportationVehicleDetailsById]
(	
	@VehicleId int
) 
As
	DECLARE @Isdel int
	--SET @Isdel=0
BEGIN
	--SELECT VehicleId,VehicleNo,VehicleDescription FROM TA_Tbl_Transportation_Vehicle WHERE IsDeleted=@Isdel AND VehicleId=@VehicleId
	SELECT VehicleId,VehicleNo,VehicleDescription,IsDeleted FROM TA_Tbl_Transportation_Vehicle WHERE VehicleId=@VehicleId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedData]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_GetUnProcessedData
Description : This Procedure is to get the Unprocesseddata from the ProcessedData Table
Tables Included : TA_Tbl_ProcessedData, TA_Tbl_Employee  
Created By : Kumuthini.L
Created On : 16-Sep-2008
Modified By :
Modified On :
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetUnProcessedData] 
(
	@Type nVarchar(5),
	@Employee_Code_Id nVarchar(25),
	@FromDate nVarchar(12),
	@ToDate nVarchar(12)
)
 AS
IF(@Type = ''All'')
BEGIN
	SELECT P.Process_Rec_ID,P.[Date],P.InTime,P.OutTime,P.Attendance,E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.OT_Eligible 
	FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id 
	WHERE P.ProcessFlag = 0 AND P.[Date] BETWEEN @FromDate AND @ToDate
END
IF(@Type = ''P'')
BEGIN
	SELECT P.Process_Rec_ID,P.[Date],P.InTime,P.OutTime,P.Attendance,E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.OT_Eligible 
	FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id 
	WHERE P.ProcessFlag = 0 AND E.Employee_Code_Id = @Employee_Code_Id AND P.[Date] BETWEEN @FromDate AND @ToDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationMappingDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_GetTransportationMappingDetailsById]
(	
	@id int
) 
As
	DECLARE @Isdel int
	SET @Isdel=1
BEGIN
	SELECT VehicleId,RouteId,Company_Id,Region_Id,Branch_Id FROM TA_Tbl_Transportation_Mapping WHERE IsDeleted=@Isdel AND id=@id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationMappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationMappingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Proc [dbo].[Proc_TA_GetTransportationMappingDetails] as
SELECT id,VehicleId,RouteId,Company_Id,Region_Id,Branch_Id FROM TA_Tbl_Transportation_Mapping Where IsDeleted=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Proc [dbo].[Proc_TA_GetTransportationDetailsById] (@id int) as
SELECT A.[id],A.VehicleNo,A.RouteName, B.Company_Name, C.Region_Name , D.Branch_Name
FROM TA_Tbl_Transportation A, TA_Tbl_CompanyDetails B, TA_Tbl_Region C ,TA_Tbl_Branch D
Where A.IsDeleted=1 AND A.Company_Id = B.Company_Id AND A.Region_Id = C.Region_Id AND A.Branch_Id = D.Branch_Id
And A.[id]=@id
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Proc [dbo].[Proc_TA_GetTransportationDetails] as
SELECT id,VehicleNo,RouteName FROM TA_Tbl_Transportation Where IsDeleted=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Manikandan
-- Create date: 25-07-2017
-- Description:	Getting Present and Leave days for current month
-- [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays] 787,''05/01/2018'',''05/01/2018''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetTotalPresentAndLeaveDays]
	@EmployeeCodeID VARCHAR(50),
	@selectedDate VARCHAR(30),
	@selectedtodate VARCHAR(30)
AS
BEGIN
	DECLARE @fromDate DATETIME
	DECLARE @toDate DATETIME
	DECLARE @CurrentDate DATETIME
	DECLARE @ClockInTime VARCHAR(30)
	DECLARE @ClockOutTime VARCHAR(30)
	DECLARE @previousDayShift INT	
	DECLARE @Shift_StartTime VARCHAR(10)
	DECLARE @Shift_EndTime VARCHAR(10)
	DECLARE @previousDate DATETIME
	DECLARE @Final_LocationName varchar(500)
	Declare @isNightshift bit
	set @isNightshift=0
	
	SET @CurrentDate=DATEADD(d,0,DATEDIFF(d,0,GETDATE()))
	SET @fromDate=DATEADD(d,-DATEPART(d,CAST(CONVERT(VARCHAR(11),@selectedDate)as DATETIME))+1,CAST(CONVERT(VARCHAR(11),@selectedDate)as DATETIME))
	IF(@selectedtodate='''' OR @selectedtodate IS NULL)
	BEGIN
		SET @todate=DATEADD(d,-DATEPART(d,@selectedDate),DATEADD(MONTH,1,@selectedDate))
	END
	ELSE 
	BEGIN
		SET @todate=CONVERT(DATETIME,@selectedtodate)
	END
	
	SELECT	@ClockInTime=	CASE WHEN (InTime IS not null and InTime<>''00:00'' and InTime!='''')	THEN @CurrentDate+InTime	END,
			@ClockOutTime=	CASE WHEN (OutTime IS not null and OutTime<>''00:00'' and OutTime!='''')THEN @CurrentDate+OutTime	END,
			@Final_LocationName=''''
	FROM TA_Tbl_ProcessedData WHERE  Employee_Code_Id=@EmployeeCodeID and (Date=@CurrentDate)
	
	
	IF((@ClockInTime IS NULL OR @ClockInTime='''' OR @ClockInTime=''00:00'') and (@ClockOutTime IS NULL OR @ClockOutTime='''' OR @ClockOutTime=''00:00''))
	BEGIN
		SET @previousDate=DATEADD(d,-1,@CurrentDate)
		SELECT @previousDayShift=Shift_Id FROM TA_Tbl_ProcessedData WHERE Date=@previousDate
		SELECT @Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime FROM TA_Tbl_Shift WHERE Shift_Id=@previousDayShift and Isdeleted=0
		IF(RIGHT(@Shift_StartTime,2)=''PM'' and RIGHT(@Shift_EndTime,2)=''AM'')
		BEGIN
			SELECT @ClockInTime=@previousDate+InTime,@ClockOutTime=@previousDate+OutTime FROM TA_Tbl_ProcessedData WHERE  Employee_Code_Id=@EmployeeCodeID and 
			(Date=@previousDate)
			set @CurrentDate=@previousDate
			set @isNightshift=1
		END
	END	
	DECLARE @Manual_ClockInTime VARCHAR(30)
	DECLARE @Manual_ClockOutTime VARCHAR(30)
	DECLARE @Manual_InLocationName varchar(500)
	DECLARE @InLatitude_value varchar(20)
	DECLARE @InLongitude_value varchar(20)
	
	DECLARE @Manual_OutLocationName varchar(500)
	DECLARE @OutLatitude_value varchar(20)
	DECLARE @OutLongitude_value varchar(20)
	
	
	SELECT @Manual_ClockInTime=MIN(ManualTimeEntry_InDate+'' '' + ManualTimeEntry_InTime) ,
		   @Manual_InLocationName=Clock_Address,
		   @InLatitude_value=Latitude_value,
		   @InLongitude_value=Longitude_value 
	FROM TA_Tbl_ManualTimeEntry 
	WHERE ManualTimeEntry_Employee_Id=@EmployeeCodeID and (ManualTimeEntry_InDate=@CurrentDate) 
	and ManualTimeEntry_InPunchType=''Shift In'' and IsImported=2
	group by Latitude_value,Longitude_value,Clock_Address
	
	if(@isNightshift=1)
	begin
		set @CurrentDate=DATEADD(d,-1,@CurrentDate)
	end
	
	SELECT @Manual_ClockOutTime=max(ManualTimeEntry_OutDate+'' ''+ManualTimeEntry_OutTime) ,
			@Manual_OutLocationName =case when max(ManualTimeEntry_OutDate+'' ''+ManualTimeEntry_OutTime) Is not null then Clock_Address else '''' end,
		   @OutLatitude_value=Latitude_value,
		   @OutLongitude_value=Longitude_value 
	FROM TA_Tbl_ManualTimeEntry 
	WHERE ManualTimeEntry_Employee_Id=@EmployeeCodeID and (ManualTimeEntry_OutDate=@CurrentDate)
	and ManualTimeEntry_OutPunchType=''Shift Out'' and IsImported=2
	group by Latitude_value,Longitude_value,Clock_Address
	
	IF(@ClockInTime is not null and @ClockInTime<>'''' and @ClockInTime!=''00:00'')
	BEGIN
		IF(@Manual_ClockInTime is not null and @Manual_ClockInTime<>'''' and @Manual_ClockInTime!=''00:00'')
		BEGIN
			IF(CONVERT(DATETIME,@Manual_ClockInTime)<CONVERT(DATETIME,@ClockInTime))
			BEGIN
				SET @ClockInTime=@Manual_ClockInTime
			END
		END
	END
	IF(@ClockOutTime is not null and @ClockOutTime<>'''' and @ClockOutTime!=''00:00'')
	BEGIN
		IF(@Manual_ClockOutTime is not null and @Manual_ClockOutTime<>'''' and @Manual_ClockOutTime!=''00:00'')
		BEGIN
			IF(CONVERT(DATETIME,@Manual_ClockOutTime)>CONVERT(DATETIME,@ClockOutTime))
			BEGIN
				SET @ClockOutTime=@Manual_ClockOutTime
			END
		END
	END
	
	if(@ClockInTime is null or @ClockInTime='''')
	begin
		SET @ClockInTime=@Manual_ClockInTime
	end
	
	if(@ClockOutTime is null or @ClockOutTime='''')
	begin
		SET @ClockOutTime=@Manual_ClockOutTime
	end
	
	
	SELECT PresentDays=ISNULL(SUM(CASE WHEN FNAttendanceCode=''Present'' THEN 0.5 ELSE 0 END),0)+
		   ISNULL(SUM(CASE WHEN ANAttendanceCode=''Present'' THEN 0.5 ELSE 0 END),0),
		   leaveDays=ISNULL(SUM(CASE WHEN FNAttendanceCode in(''Present'',''Absent'',''Holiday'',''RH'',''Weekly Off'') THEN 0 ELSE 0.5 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode in(''Present'',''Absent'',''Holiday'',''RH'',''Weekly Off'') THEN 0 ELSE 0.5 END),0),
		   AbsentDays=ISNULL(SUM(CASE WHEN FNAttendanceCode=''Absent'' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode=''Absent'' THEN 0.5 ELSE 0 END),0),
		   OffDays=ISNULL(SUM(CASE WHEN FNAttendanceCode=''Weekly Off'' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode=''Weekly Off'' THEN 0.5 ELSE 0 END),0),
		   HolidayDays=ISNULL(SUM(CASE WHEN FNAttendanceCode=''Holiday'' THEN 0.5 WHEN FNAttendanceCode=''RH'' THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode=''Holiday'' THEN 0.5 WHEN ANAttendanceCode=''RH'' THEN 0.5 ELSE 0 END),0) ,
		   TotalWorkingDays=ISNULL(SUM(CASE WHEN FNAttendanceCode not in(''Holiday'',''Weekly Off'',''RH'') THEN 0.5 ELSE 0 END),0) +
		   ISNULL(SUM(CASE WHEN ANAttendanceCode not in(''Holiday'',''Weekly Off'',''RH'') THEN 0.5 ELSE 0 END),0),	   
		   ClockInTime=CASE WHEN @ClockInTime IS null THEN ''-'' ELSE ISNULL(SUBSTRING(@ClockInTime,13,5),''-'')+ '' '' +ISNULL(SUBSTRING(@ClockInTime,18,2),'''') END,
		   ClockOutTime=CASE WHEN @ClockOutTime IS null THEN ''-'' ELSE ISNULL(SUBSTRING(@ClockOutTime,13,5),''-'')+ '' '' +ISNULL(SUBSTRING(@ClockOutTime,18,2),'''') END,
		   ClkInLocName=@Manual_InLocationName,
		   ClkOutLocName=@Manual_OutLocationName,
		   ClkInLatValue=@InLatitude_value,
		   ClkInLongValue=@InLongitude_value,
		   ClkOutLatValue=@OutLatitude_value,
		   ClkOutLongValue=@OutLongitude_value
	FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id=@EmployeeCodeID and (Date>=@fromDate and Date<=@toDate)and ProcessFlag=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingVersionNumber]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingVersionNumber]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		Manikandan.R
-- Create date: 14-03-2014
-- Description:	For Online licensing, To get the version number
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingVersionNumber]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select substring(RIGHT(ApplicationVersionName,charindex(''_'',reverse(ApplicationVersionName))-1),1,LEN(ApplicationVersionName))as versionNumber from TA_Tbl_Version 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedDataForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingUnProcessedDataForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Un processed data details
-- drop procedure [dbo].[Proc_Ta_GettingUnProcessedData]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedDataForService]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT P.Process_Rec_ID,P.Employee_Code_Id,
	convert(varchar(25), P.Date,120) as Date,P.InTime,P.OutTime,P.Attendance,P.Status,E.Employee_Id,E.OT_Eligible,
	E.CompOff_Eligible,E.IsFlexible,EL.LevelId FROM TA_Tbl_ProcessedData P 
	INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId=E.Employee_Id 
	INNER JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId 
	WHERE P.ProcessFlag = 0 and E.IsDeleted = 0 and P.Date<getdate()
	ORDER BY P.Employee_Code_Id,P.Date
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingUnProcessedData]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingUnProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingUnProcessedData]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT P.Process_Rec_ID,P.Employee_Code_Id,P.Date,P.InTime,P.OutTime,P.Attendance,P.Status,E.Employee_Id,E.OT_Eligible,
	E.CompOff_Eligible,E.IsFlexible,EL.LevelId FROM TA_Tbl_ProcessedData P  INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = P.Employee_Code_Id  
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId=E.Employee_Id INNER JOIN Ta_Tbl_DataProcessCompanyLevelTemp DPC on DPC.LevelId=EL.LevelId  
	WHERE P.ProcessFlag = 0 and E.IsDeleted = 0 and P.Date<getdate() ORDER BY P.Employee_Code_Id,P.Date 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting Terminal Data type database details
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GettingTerminalDataTypeDatabaseDetailsForService]
	-- Add the parameters for the stored procedure here
	@FileType varchar(30),
	@TerminalDatatypeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select	ConnectionString,TableName,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_DateTime,DateTimeFormat,RDBMS_Date,DateFormat,
			RDBMS_Time,TimeFormat,RDBMS_Type,RDBMS_MDB_Flag,RDBMS_TransactionIdentifier,TransactionIdentifierBit,TransactionIdentifierValue,
			IsEncrypted from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDatatypeID 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Shift Setting Details of All companies>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingShiftSettingDetailsOfAllCompanies]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT	SHIFTSETTINGID,COMPANYID,MAXHOURSBEFORESHIFT,MAXHOURSAFTERSHIFT,SHIFTBREAK,SHIFTMAXBREAKHOURS,
			MONTHLYWORKINGHOURS,WEEKLYWORKINGHOURS,EMPID,HOLIDAYOT,WEEKOFFOT,OTOPTION,
			CONVERT(VARCHAR(25),DEFAULTMONTHCLOSUREDATE,120) AS MONTHCLOSURE_ENDDATE,ISFLEXIBLE,FLEXIBLEFLAG,
			OTROUNDOFFENABLE,FULLDAYATTENDANCEHRS,HALFDAYATTENDANCEHRS,HALFDAYATTENDANCE,FULLDAYATTENDANCE, WEEKLYOFFSTARTHOURS, 
			IGNOREDUPLICATEPUNCH,PUNCHINTERVAL,AFTERSHIFTTIME,BEFORESHIFTTIME,DEFINEDWORKHRS,NOOFSUCCESSIVEDAYSINYEAR,
			COMPENSATIONVALITITYDAYS,VAILDITYCOMPOFFDAYS,HALFDAYCOMPOFF, FULLDAYCOMPOFF,LATEENTRY,EARLYENTRY, 
			EARLYEXIT,LATEEXIT, TIMESTAMP,TIMESTAMP1,ISLUNCHDEDUCTION,LUNCHDEDUCTIONHOURS,FLEXI_AFTERSHIFTTIME,
			FLEXI_BEFORESHIFTTIME,FLEXI_DEFINEDWORKHRS,DefaultLunchHours, MaxLunchHours, MaxWorkPlaceInHours, 
			MaxHoursBeforeShift_24HrsShift, WeeklyOffStartHours_24HrsShift, CumulativeWeekStartDay, CumulativeWeekEndDay, MonthStartDay, MonthEndDay
	FROM TA_TBL_SHIFTSETTINGS
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftSettingDetailsForservice]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_ShiftSettings where CompanyId=-1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForSMS]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsForSMS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForSMS]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select * from TA_Tbl_Shift where Isdeleted=0 and (Shift_Name!=''No Shift'' or Shift_ShortName!=''NOS'')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting all companies shift details
-- =============================================
Create PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsForService]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Shift_Id,Level_Id,Shift_StartTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_GraceInTime,Shift_EndTime,Shift_GraceOutTime,DefaultShift,ShiftType,[24HrsShift] FROM TA_Tbl_Shift WHERE IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingResponseStatus]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingResponseStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Manikandan.R
-- Create date: 14-03-2014
-- Description:	GettingResponseStatus
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingResponseStatus]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select * from TA_Tbl_LicenseRequestDetail 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPermissionDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPermissionDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:        R.Manikandan
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:   To check Employee applied the permission or not 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPermissionDetailsForService]
      -- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
      @INEMPLOYEE_CODE_ID VARCHAR(50),
      @DTMDATE DATETIME
AS
BEGIN
      SET NOCOUNT ON;
      SELECT      P.PERMISSION_FROMTIME,P.PERMISSION_TOTIME,P.NO_OF_HOURS
                  PERMISSION_ID, P.EMPLOYEE_ID, PERMISSION_APPLIEDDATE, PERMISSION_DATE, 
                  PERMISSION_TYPE,PERMISSION_REASON, 
                  PERMISSION_STATUS, EMP_ID_SANCTION, REMARKS, P.ISDELETED, TIMESTAMP,P.EMP_ID,
                  YEARSETTINGS_ID,P.No_Of_Hours
      FROM TA_TBL_PERMISSION P INNER JOIN TA_TBL_EMPLOYEE E ON E.EMPLOYEE_ID = P.EMPLOYEE_ID
      WHERE E.SWIPECARDNO=@INEMPLOYEE_CODE_ID AND P.PERMISSION_DATE =@DTMDATE AND P.PERMISSION_STATUS=''APPROVED'' AND P.ISDELETED=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOverTimeParametersForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingOverTimeParametersForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingOverTimeParametersForService]
	-- Add the parameters for the stored procedure here
	@intCompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if((SELECT COUNT(*) FROM TA_Tbl_ShiftSettings where CompanyId=@intCompanyId)>0)
		begin
			SELECT AfterShiftTime,BeforeShiftTime,MaxHoursBeforeShift,DefinedWorkhrs FROM 
			TA_Tbl_ShiftSettings where CompanyId=@intCompanyId
		end
	else
		begin
			SELECT AfterShiftTime,BeforeShiftTime,MaxHoursBeforeShift,DefinedWorkhrs FROM 
			TA_Tbl_ShiftSettings where CompanyId=-1
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingOTRoundOffValuesForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GettingOTRoundOffValuesForService] 7,214,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingOTRoundOffValuesForService]
	-- Add the parameters for the stored procedure here
	@inShiftSettingId int,
	@inOvertimeMins int,
	@inIsOTRoundOff bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--insert into roundOffOT values(@inShiftSettingId,@inOvertimeMins,@inIsOTRoundOff)
	if(@inIsOTRoundOff=1)
		begin
			-- Insert statements for procedure here
			Declare @StartMins float
			Declare @EndMins float
			Declare @RoundedAs nvarchar(5)
			Declare @Total int
			Declare @Start int
			Declare @dblModValue float
			Declare @dblRoundedOverTimeMins float
			Create table #Temp_TA_Tbl_OTRoundoffSettings(id int identity(1,1),StartMins float,EndMins float,RoundedAs nvarchar(5))
			insert into #Temp_TA_Tbl_OTRoundoffSettings
			SELECT StartMins,EndMins,RoundedAs FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId =@inShiftSettingId
			set @Start=1
			select @Total=COUNT(*) from #Temp_TA_Tbl_OTRoundoffSettings
			set @dblRoundedOverTimeMins=0	
			while @Start<=@Total
				begin
					SELECT @StartMins=StartMins,@EndMins=EndMins,@RoundedAs=RoundedAs FROM #Temp_TA_Tbl_OTRoundoffSettings WHERE id =@Start
					set @dblModValue = @inOvertimeMins % 60;
						
					if (@StartMins <= @dblModValue and @dblModValue <= @EndMins)
						begin
							set @dblRoundedOverTimeMins =CONVERT(float,@inOvertimeMins) + (dbo.ConvertHoursToMinites(@RoundedAs) - @dblModValue);
						end
						set @Start=@Start+1
				end
			if(@dblRoundedOverTimeMins=0)
				begin
					set @dblRoundedOverTimeMins=@inOvertimeMins		
				end					
		end
	else
		begin
			set @dblRoundedOverTimeMins=@inOvertimeMins
		end
	select @dblRoundedOverTimeMins as RoundedOff
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingNonProcessedRawDataRecords]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <24-10-2016>
-- Description:	<Getting Non Processed Raw data details for process>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingNonProcessedRawDataRecords]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT top 1000 Clk_Id,Clk_CardId,Clk_DeviceId,Clk_Date,Clk_Time,Clk_Type FROM TA_Tbl_Clk_RawData
	WHERE Clk_Flag = 0 AND Clk_Process = 0 and ReasonId!=6 ORDER BY Clk_Date+CLK_TIME
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingRawDatasForservice]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingRawDatasForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Get the Raw Data from the TimeCheck Raw Data Table where Clk_Flag = 0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingRawDatasForservice]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Clk_Id,Clk_CardId,Clk_DeviceId,Clk_Date,Clk_Time,Clk_Type FROM TA_Tbl_Clk_RawData WHERE Clk_Flag = 0 AND Clk_Process = 0 ORDER BY Clk_Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeRemarks]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeRemarks]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeRemarks]
	@Clk_Type nvarchar(10),
	@PunchType nvarchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Punchtype_Remarks from ta_tbl_PunchtypeRemarks 
	where Clk_Type=@Clk_Type and PunchType=@PunchType
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLunchDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingLunchDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <27-02-2016>
-- Description:	<Getting Lunch in and Out punch details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingLunchDetails]
	-- Add the parameters for the stored procedure here
	@Employee_Code_id varchar(50),
	@clk_date datetime	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Clk_InTime datetime
	Declare @Clk_OutTime datetime
	Declare @Clk_InDate datetime
	Declare @Clk_OutDate datetime
    -- Insert statements for procedure here
	Select @Clk_InTime=MAX(Clk_InTime),@Clk_InDate= Clk_InDate from ta_tbl_clockdetails
	where clk_empid= @Employee_Code_id and clk_date=@clk_date and Clk_InPunchType=''Lunch In''
	and IsVoid=0 group by Clk_InDate
	Select @Clk_OutTime=MIN(Clk_OutTime),@Clk_OutDate=Clk_OutDate from ta_tbl_clockdetails
	where clk_empid=@Employee_Code_id and clk_date=@clk_date and Clk_OutPunchType=''Lunch Out''
	and IsVoid=0 group by Clk_OutDate
	select @Clk_InTime as Clk_InTime,@Clk_OutTime as Clk_OutTime,@Clk_InDate,@Clk_OutDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingLeaveTypeDetailsForservice]
	@inLeaveTypeId int
AS
BEGIN
	SET NOCOUNT ON;
	select LeaveType from TA_Tbl_LeaveType where LeaveType_Id = @inLeaveTypeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingLeaveDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingLeaveDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingLeaveDetailsForService]
	-- Add the parameters for the stored procedure here
	@inEmployee_Code_Id varchar(max),
	@Date datetime
AS
BEGIN
	SET NOCOUNT ON;
	select la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate,la.Leave_SessionFrom,la.Leave_SessionTo from TA_Tbl_LeaveApplication la,TA_Tbl_Employee emp where la.Employee_Id = emp.Employee_Id and emp.SwipeCardNo = @inEmployee_Code_Id and la.Leave_FromDate <=@Date and la.Leave_ToDate >=@Date and la.Status = ''Approved'' and la.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingIsAutoShiftEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <21-Aug-2019 10:37 AM>
-- Description:	<Verifying this employee is auto shift employee or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingIsAutoShiftEmployee]
	@SwipeCardNo nvarchar(40)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @EmployeeAutoId int
	select @EmployeeAutoId = isnull(Employee_Id,0) FROM TA_Tbl_Employee WHERE SwipeCardNo = @SwipeCardNo
	--print @EmployeeAutoId
	IF(@EmployeeAutoId != 0)
	BEGIN
		IF Exists(SELECT AutoShiftConfigId FROM TA_Tbl_AutoShiftConfiguration WHERE EmployeeId = @EmployeeAutoId and (ShiftId1!=0 or ShiftId2!=0 or ShiftId3!=0 or ShiftId4!=0 or ShiftId5!=0))
		BEGIN
			SELECT ''YES'' as IsAutoShiftEmployee
		END
		ELSE
		BEGIN
			SELECT ''NO'' as IsAutoShiftEmployee
		END
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDeviceDataBaseDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingDeviceDataBaseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Termainl raw details using file type and terminal id>
-- [Proc_TA_GettingDeviceDataBaseDetails] ''MariaDB'',1
-- [Proc_TA_GettingDeviceDataBaseDetails] ''PostgreSQL'',13
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingDeviceDataBaseDetails]
	@FileType varchar(30),
	@TerminalDataTypeId int
AS
BEGIN

	SET NOCOUNT ON;
	DECLARE @TableName varchar(max)
	DECLARE @RDBMS_ReaderNo varchar(max)
	DECLARE @RDBMS_CardNo varchar(max)
	DECLARE @RDBMS_DateTimeBit varchar(max)
	DECLARE @RDBMS_DateTime varchar(max)
	DECLARE @DateTimeFormat varchar(max)
	DECLARE @RDBMS_Date varchar(max)
	DECLARE @DateFormat varchar(max)
	DECLARE @RDBMS_Time varchar(max)
	DECLARE @TimeFormat varchar(max)
	DECLARE @RDBMS_Type varchar(max)
	DECLARE @RDBMS_MDB_Flag varchar(max)
	DECLARE @RDBMS_TransactionIdentifier varchar(max)
	DECLARE @TransactionIdentifierValue varchar(max)
	DECLARE @TransactionIdentifierBit varchar(max)
	DECLARE @IsEncrypted varchar(max)
	Declare @ConnectionString varchar(max)
	Declare @DynamicSQL_Select varchar(max)
	Declare @IsEmployeeId varchar(max)
	Declare @strSQLUpdate varchar(max)
	Declare @autoID varchar(max)
	Declare @brandID int
	set @DynamicSQL_Select=''''
	if(@FileType=''RDBMS'')
	begin		
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=RDBMS_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=RDBMS_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
		
		---Forming Dyanmic Query
		--Suprema
		IF(@brandID=3)
		BEGIN		
			--SELECT DEVDT=dateadd(SS,t1.DEVDT+14400,''01/01/1970''),DEVUID,USRID,EVT,TNAKEY,EVTLGUID FROM T_LG201709 t1  
			--WHERE TNAKEY IN (''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'',''15'',''16'',''255'') 
			--AND T1.USRID IS NOT NULL AND T1.USRID <> '''' AND T1.EVT IN(55,4865,4098) and EVTLGUID>0			
			SET @DynamicSQL_Select =@DynamicSQL_Select+ ''SELECT '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+''nDateTime=dateadd(SS,''+ @RDBMS_DateTime + '',''''01/01/1970 00:00:00''''),''
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + '','' + @RDBMS_Time + '','';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + '','' + @RDBMS_TransactionIdentifier + +'',''+@RDBMS_MDB_Flag+ '' FROM ''+@TableName+'' WHERE '' + @RDBMS_MDB_Flag + '' > #log_Number '';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + '' AND '' + @RDBMS_TransactionIdentifier + '' in( '' + @TransactionIdentifierValue + '')'';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_Type +'' in (''''0'''',''''1'''',''''2'''',''''3'''',''''4'''',''''5'''',''''6'''',''''7'''',''''8'''',''''9'''',''''10'''',''''11'''',''''12'''',''''13'''',''''14'''',''''15'''',''''16'''',''''255'''')''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_CardNo + '' is not null and '' + @RDBMS_CardNo +''<>''''''''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
		END
		--Suprema Biostar 2
		ELSE IF(@brandID=4)
		BEGIN		
			--SELECT DEVDT=dateadd(SS,t1.DEVDT+14400,''01/01/1970''),DEVUID,USRID,EVT,TNAKEY,EVTLGUID FROM T_LG201709 t1  
			--WHERE TNAKEY IN (''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'',''15'',''16'',''255'') 
			--AND T1.USRID IS NOT NULL AND T1.USRID <> '''' AND T1.EVT IN(55,4865,4098) and EVTLGUID>0
			SET @DynamicSQL_Select = @DynamicSQL_Select+''SELECT '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+''DEVDT=dateadd(SS,''+ @RDBMS_DateTime + ''+14400,''''01/01/1970''''),''
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + '','' + @RDBMS_Time + '','';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + '','' + @RDBMS_TransactionIdentifier + +'',''+@RDBMS_MDB_Flag+ '' FROM #Table_Name WHERE '' + @RDBMS_MDB_Flag + '' > #log_Number '';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + '' AND '' + @RDBMS_TransactionIdentifier + '' in( '' + @TransactionIdentifierValue + '')'';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_Type +'' in (''''0'''',''''1'''',''''2'''',''''3'''',''''4'''',''''5'''',''''6'''',''''7'''',''''8'''',''''9'''',''''10'''',''''11'''',''''12'''',''''13'''',''''14'''',''''15'''',''''16'''',''''255'''')''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_CardNo + '' is not null and '' + @RDBMS_CardNo +''<>''''''''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
		END
		--ESSL - Dynamic Table
		Else IF(@brandID=5)
		BEGIN
			--select t1.LogDate,t1.DeviceId,t1.UserId,'' '',DeviceLogId FROM " + Convert.ToString(strFinaltableName) + " t1 ";
			--dataCollectionQuery += " WHERE T1.UserId IS NOT NULL AND T1.UserId <> ''''
			SET @DynamicSQL_Select = @DynamicSQL_Select+''SELECT top 1000 '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_TransactionIdentifier +'',''+@RDBMS_MDB_Flag+ '' FROM #Table_Name WHERE '' + @RDBMS_MDB_Flag + '' > #log_Number '';
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_CardNo + '' is not null and '' + @RDBMS_CardNo +''<>''''''''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
		END
		-- Others
		ELSE IF(@brandID=2)
		BEGIN			
			--Scufe client
			--		SELECT OFFICEPUNCH,Null as date, Null as time,
			--		MC_NO as DevicceId,
			--		55 as nEvent,
			--		a.CARDNO,
			--		NULL as Susername,NULL  as nSource, NULL as bAdminCheck,
			--		MC_NO as nTNAEvent,
			--		0 as strUniquekey
			--		FROM MachineRawPunch a
			--		left outer join tb_reportslist b on b.dtDateTime = a.OFFICEPUNCH and b.nuserid = a.CARDNO 
			--		where (a.MC_NO is not null) and (b.dtDateTime is null) and (a.OFFICEPUNCH > ''20191001'')
			--		order by OFFICEPUNCH asc		
			
			--	NOTE: IF ANY FLAG FIELD IS NOT AVAILABLE IN DEVICE DATABASE TABLE, REMOVE #LOG_NUMBER IN WHERE CONDITION
			
			SET @DynamicSQL_Select = ''SELECT top 1000 '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + '',''+ @RDBMS_TransactionIdentifier 
			if(@RDBMS_MDB_Flag!=''NoFlag'')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select +'',''+@RDBMS_MDB_Flag 
			end
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' FROM ''+ @TableName + '' WHERE '' 
			if(@RDBMS_MDB_Flag!=''NoFlag'')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_MDB_Flag + '' > #log_Number And '';
			end
			else
			begin
				--IF(@RDBMS_DateTimeBit= 1)
				--BEGIN
					Declare @CurrentMonthStartDate datetime
					Declare @CurrentDate datetime
					set @CurrentDate=GETDATE()
					--Two months data it will pick from device database on every day and minutes.
					set @CurrentMonthStartDate=DATEADD(MONTH,DATEDIFF(month,0,DATEADD(month,-1,getdate())),0)				
					SET @DynamicSQL_Select = @DynamicSQL_Select+''(''+ @RDBMS_DateTime + ''>=convert(datetime,'''''' + CONVERT(varchar(20),@CurrentMonthStartDate) +'''''') and '' + @RDBMS_DateTime +''<=convert(datetime,''''''+CONVERT(varchar(20),@CurrentDate)+'')'''') And ''
				--END
			end
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_CardNo + '' is not null and '' + @RDBMS_CardNo +''<>''''''''''
			if(@RDBMS_MDB_Flag!=''NoFlag'')
			begin
				SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
			end
		END
		else if(@brandID=7)
		begin
			SET @DynamicSQL_Select =@DynamicSQL_Select+ ''SELECT '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+''''+ @RDBMS_DateTime + '',''
			END
			ELSE IF(@RDBMS_DateTimeBit= 0)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + '','' + @RDBMS_Time + '','';
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select +  @RDBMS_Type + '','' + @RDBMS_TransactionIdentifier + +'',''+@RDBMS_MDB_Flag+ '' FROM ''+@TableName+'' WHERE '' + @RDBMS_MDB_Flag + '' is null '';
			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + '' AND '' + @RDBMS_TransactionIdentifier + '' in( '' + @TransactionIdentifierValue + '')'';
				END
			END
			
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_CardNo + '' is not null and '' + @RDBMS_CardNo +''<>''''''''''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
		end
		select	brandid=@brandID,
				strSQL=@DynamicSQL_Select,
				ConnectionString=@ConnectionString,
				TableName=@TableName,
				RDBMS_ReaderNo=@RDBMS_ReaderNo,
				RDBMS_CardNo=@RDBMS_CardNo,
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then ''True'' else ''False'' end,
				RDBMS_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				RDBMS_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				RDBMS_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted				
	end
	else if(@FileType=''Delimiter'' or @FileType=''Fixed Length'')
	begin
		select File_SourcePath,File_BackupPath,File_BackupType from TA_Tbl_TerminalDataType 
		where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
	end
	else if(@FileType=''Delimiter'')
	begin
		select ConnectionString,TableName,MDB_ReaderNo,MDB_CardNo,MDB_DateTimeBit,MDB_DateTime,DateTimeFormat,MDB_Date,DateFormat,
		MDB_Time,TimeFormat,MDB_Type,RDBMS_MDB_Flag,MDB_TransactionIdentifier,IsEmployeeId,TransactionIdentifierBit,TransactionIdentifierValue,IsEncrypted 
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
	end
	else if(@FileType=''MDB'')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=MDB_ReaderNo,
				@RDBMS_CardNo=MDB_CardNo,
				@RDBMS_DateTimeBit=MDB_DateTimeBit,
				@RDBMS_DateTime=MDB_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=MDB_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=MDB_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=MDB_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=MDB_TransactionIdentifier,
				@IsEmployeeId=IsEmployeeId,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted=IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId
		--Two columns are need to be created into mdb database file -susername and nindex column. 
		SET @DynamicSQL_Select = ''SELECT Top 1000 nIndex,'' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
		IF(@RDBMS_DateTimeBit= 1)
		BEGIN
			--SET @DynamicSQL_Select = @DynamicSQL_Select + Format(@RDBMS_DateTime, ''mm/dd/yyyy hh:mm:ss tt'') + '',''
			SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime + '',''
		END
		ELSE IF(@RDBMS_DateTimeBit= 0)
		BEGIN
			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Date + '','' + @RDBMS_Time + '','';
		END
		SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + '','' + @RDBMS_MDB_Flag + '' FROM '' + @TableName + '' WHERE '' + @RDBMS_MDB_Flag + '' IS NULL'';
		IF(@TransactionIdentifierBit is not null)
		BEGIN
			IF(@TransactionIdentifierBit = 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select + '' AND '' + @RDBMS_TransactionIdentifier + '' in( '' + @TransactionIdentifierValue + '')'';
            END
		END
		set @strSQLUpdate = ''UPDATE '' + @TableName + '' SET '' + @RDBMS_MDB_Flag + '' = ''''1'''' WHERE UserId =  '';
		
		select	ConnectionString=@ConnectionString,
				TableName=@TableName,
				MDB_ReaderNo=@RDBMS_ReaderNo,
				MDB_CardNo=@RDBMS_CardNo,
				MDB_DateTimeBit=case when @RDBMS_DateTimeBit=1 then ''True'' else ''False'' end,
				MDB_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				MDB_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				MDB_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				MDB_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				MDB_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted,
				strSQL=@DynamicSQL_Select,
				strSQLUpdate=@strSQLUpdate,
				@brandID as brandID

	end

	else if(@FileType=''PostgreSQL'')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId

			from TA_Tbl_TerminalDataType where FileType = ''PostgreSQL'' and TerminalDatatype_ID = 13

			SET @DynamicSQL_Select='''';

			SET @DynamicSQL_Select = @DynamicSQL_Select+''SELECT '' + @RDBMS_ReaderNo + '','' + @RDBMS_CardNo + '',''
			IF(@RDBMS_DateTimeBit= 1)
			BEGIN
				SET @DynamicSQL_Select = @DynamicSQL_Select+ @RDBMS_DateTime + '','' 
			END

			SET @DynamicSQL_Select = @DynamicSQL_Select + @RDBMS_Type + '','' + @RDBMS_TransactionIdentifier + +'',''+@RDBMS_MDB_Flag+ '' FROM ''+@TableName+'' WHERE '' + @RDBMS_MDB_Flag + '' > #log_Number '';

			IF(@TransactionIdentifierBit is not null)
			BEGIN
				IF(@TransactionIdentifierBit = 1)
				BEGIN
					SET @DynamicSQL_Select = @DynamicSQL_Select + '' AND '' + @RDBMS_TransactionIdentifier + '' in( '' + @TransactionIdentifierValue + '')'';
				END
			END
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' And '' + @RDBMS_CardNo + '' is not null ''
			SET @DynamicSQL_Select = @DynamicSQL_Select + '' order by ''+@RDBMS_MDB_Flag
			
			select	brandid=@brandID,
				strSQL=@DynamicSQL_Select,
				ConnectionString=@ConnectionString,
				TableName=@TableName,
				RDBMS_ReaderNo=@RDBMS_ReaderNo,
				RDBMS_CardNo=@RDBMS_CardNo,
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then ''True'' else ''False'' end,
				RDBMS_DateTime=@RDBMS_DateTime,
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Type=@RDBMS_Type,
				RDBMS_MDB_Flag=@RDBMS_MDB_Flag,
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=@TransactionIdentifierValue,
				IsEncrypted =@IsEncrypted	

	end
	else if(@FileType=''MariaDB'')
	begin
		select	@ConnectionString=ConnectionString,
				@TableName=TableName,
				@RDBMS_ReaderNo=RDBMS_ReaderNo,
				@RDBMS_CardNo=RDBMS_CardNo,
				@RDBMS_DateTimeBit=RDBMS_DateTimeBit,
				@RDBMS_DateTime=RDBMS_DateTime,
				@DateTimeFormat=DateTimeFormat,
				@RDBMS_Date=RDBMS_Date,
				@DateFormat=DateFormat,
				@RDBMS_Time=RDBMS_Time,
				@TimeFormat=TimeFormat,
				@RDBMS_Type=RDBMS_Type,
				@RDBMS_MDB_Flag=RDBMS_MDB_Flag,
				@RDBMS_TransactionIdentifier=RDBMS_TransactionIdentifier,
				@TransactionIdentifierBit=TransactionIdentifierBit,
				@TransactionIdentifierValue=TransactionIdentifierValue,
				@IsEncrypted =IsEncrypted,
				@brandID=BrandId
		from TA_Tbl_TerminalDataType where FileType = @FileType and TerminalDatatype_ID = @TerminalDataTypeId

		select	brandid=@brandID,
				strSQL=''select * from tbl_event WHERE ET_GRANTED=''''Y'''' AND EE_IDX>=#log_Number'',
				ConnectionString=@ConnectionString,
				TableName=''tbl_event'',
				RDBMS_ReaderNo=''Dv_IDX'',
				RDBMS_CardNo=''EP_NO'',
				RDBMS_DateTimeBit=case when @RDBMS_DateTimeBit=1 then ''True'' else ''False'' end,
				RDBMS_DateTime=''ET_DTM'',
				DateTimeFormat=@DateTimeFormat,
				RDBMS_Date=@RDBMS_Date,
				DateFormat=@DateFormat,
				RDBMS_Time=@RDBMS_Time,
				TimeFormat=@TimeFormat,
				RDBMS_Type=''ET_Granded'',
				RDBMS_MDB_Flag=''EE_IDX'',
				RDBMS_TransactionIdentifier=@RDBMS_TransactionIdentifier,
				TransactionIdentifierBit=@TransactionIdentifierBit,
				TransactionIdentifierValue=''y'',
				IsEncrypted =@IsEncrypted
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingDataFromClockDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingDataFromClockDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Getting Data From  Clock Details>
-- [Proc_TA_GettingDataFromClockDetails]''100102'',''787,546838471,538109926,538100001,538100002'',''09/02/2018 12:10 PM'',''O''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingDataFromClockDetails]
@inClk_EmpId varchar(50),
@strOutDeviceId varchar(max),
@strInDateTime varchar(20),
@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type=''I'')
    begin
		Select Clk_Id,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType from TA_Tbl_ClockDetails 
		where Clk_EmpId = @inClk_EmpId and Clk_OutDeviceId IN (@strOutDeviceId) AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <  convert(datetime,@strInDateTime)) AND 
		(CAST(Clk_OutDate+Clk_OutTime AS DateTime) > convert(datetime,@strInDateTime)) AND IsVoid=0
    end
    else
    begin
		Select Clk_Id,Clk_Date,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,PunchType_Remarks,Clk_Remarks from TA_Tbl_ClockDetails 
		where Clk_EmpId =  @inClk_EmpId and Clk_InDeviceId IN (@strOutDeviceId) 
		AND 
		(CAST(Clk_InDate+Clk_InTime AS DateTime) <convert(datetime,@strInDateTime)) AND 
		(CAST(Clk_OutDate+Clk_OutTime AS DateTime) > convert(datetime,@strInDateTime)) AND IsVoid=0
    end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingBLCountForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingBLCountForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingBLCountForService]
	-- Add the parameters for the stored procedure here
	@SwipeCardNo varchar(50),
	@FromDate datetime,
	@Todate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
	select Count(Process_Rec_Id) as BLCount from  Ta_Tbl_ProcessedData  WHERE Employee_Code_Id=@SwipeCardNo
	AND (Date BETWEEN @FromDate AND @Todate) AND Status=''BL''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GettingAttendanceDetailsForSelectedDuration 787,''5/3/2017''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingAttendanceDetailsForSelectedDuration]
@EmpCodeID varchar(50),
@Date datetime
AS
BEGIN
	SET NOCOUNT ON;
	SELECT InTime,OutTime,HrsWork,LateIn,EarlyOut,HrsExtra from TA_Tbl_ProcessedData where Employee_Code_Id=@EmpCodeID and Date=@Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 13-08-2015
-- Description:	Getting Terminal data type details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingAllTerminalDataTypeDetails]
AS
BEGIN
	SET NOCOUNT ON;
	select TD.TerminalDatatype_ID,TD.FileType,TB.KeyValue from TA_Tbl_TerminalDatatype TD inner join TA_Tbl_TerminalBrand TB on TD.BrandID=TB.BrandID where TD.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTaskDetails_ParticularProject]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTaskDetails_ParticularProject]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetTaskDetails_ParticularProject 6,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetTaskDetails_ParticularProject]
	@ProjectID bigint,
	@TaskID bigInt
AS
BEGIN
	SET NOCOUNT ON;
    if(@TaskID!=0)
    begin
		SELECT * from TA_Tbl_Project P 
		Inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
		left outer join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and PT.taskID=TPD.TaskID)
		where Project_Id=@ProjectID and PT.TaskID=@TaskID
	end
	else
	begin		
		SELECT * from TA_Tbl_Project P
		inner join ta_tbl_projectTasklist PT on P.Project_Id=pt.projectid
		where Project_Id=@ProjectID	
		--left outer join Ta_tbl_TaskProgressDetails TPD on (TPD.projectID=P.Project_Id and TPD.TaskID=PT.TaskID)
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetTaskDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetTaskDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetTaskDetails 100
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetTaskDetails]
@ProjectID bigint
AS
BEGIN
	SET NOCOUNT ON;
	select ''Iffco customization'' as Project_Name,''Testing'' as TaskList,''16'' as definedHours,'''' as TaskDescription,'''' as SpentHours,'''' as TaskName,''''as TaskID from TA_Tbl_Project P
	inner join Ta_tbl_TaskProgressDetails TP on P.Project_Id=TP.ProjectID 
	where Project_Id=@ProjectID	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSubMenus]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSubMenus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <26/jul/07>  
-- Description: Getting Left Menu>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_GetSubMenus]
(  
 @parentId int,  
 @groupId int,
 @strType varchar(20)   
)  
AS  
BEGIN  
if(@strType!=''Standard'')
	BEGIN
		if (@parentId=0)  
			Begin  
				select * from ta_tbl_page where parentID=0 and pageID in (select pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby  
			End  
		Else  
			Begin  
				select * from ta_tbl_page where parentID=@parentId
			End
	END
else
	BEGIN
		if (@parentId=0)  
			Begin  
				select * from ta_tbl_page where parentID=0 
				and pageID not in (20,24,25,69,96,97,98,108,110) 
				and pageID in (select pageGroupID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1) group by pageGroupID) order by orderby  
			End  
		Else  
			Begin  
				select * from ta_tbl_page where parentID=@parentId 
				and pageID not in (20,24,25,69,96,97,98,108,110)  
				and  pageID in (select pageID from ta_tbl_userRights where groupId=@groupId and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)) order by orderby  
			End		
	END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSTemplateStatus]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSMSTemplateStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <26-09-2016>
-- Description:	<Checking Template Status using Template Name>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSMSTemplateStatus]
	@TemplateName varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Status,ToEmployee from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftUsingID]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftUsingID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,Karthikeyan.R>
-- Create date: <Create Date,28-Oct-2015>
-- Description:	<Description,Get Shift name based on the terminal ID>
-- Proc_TA_GetShiftUsingID 1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftUsingID]
       -- Add the parameters for the stored procedure here
       @ShiftID as int
AS
BEGIN
       SET NOCOUNT ON;
       if @ShiftID!=-1
		   begin
				  select case when Shift_Name=''No Shift''  then ''Fales'' else ''True'' end as Val
				  from TA_Tbl_Shift where Shift_Id=@ShiftID
		   end 
       else
		   begin
				  select ''True'' as val
		   end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortNameWithOutTime]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftShortNameWithOutTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	: Proc_TA_GetShiftShortNameWithOutTime
Description	: Get Shift Id and Short Name for display in Shift allocation Report
Tables		: TA_Tbl_Shift
Created By	: Karthikeyan R
Created on	: 09-Sep-2015
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftShortNameWithOutTime]
AS
Begin
	Select Shift_Id,Shift_ShortName from TA_Tbl_shift
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftShortName]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftShortName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	: Proc_TA_GetShiftShortName
Description	: Get Shift Id and Short Name for display in Shift allocation Report
Tables		: TA_Tbl_Shift
Created By	: Prabakaran
Created on	: 3-Aug-07		
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftShortName]
AS
DECLARE @timeformat   varchar(10)
SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat=''hh:mm tt'')
		begin
			Select Shift_Id,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName from TA_Tbl_shift
		end
	else
		begin
			Select Shift_Id,Shift_ShortName + '' ( '' +convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName from TA_Tbl_shift
		end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================
-- Author:		Karthikeyan.R
-- Create date: 03-Apr-2017
-- Description:	Get the Shift Settings Details by Company Id for compoff request
-- Descriptions		:	selecting lunch deduction hours columns for shift settings page
-- ================================================
-- Proc_TA_GetShiftSettingsByComId 1
Create PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComIdForCompOff] 
(
	@CompanyId int
)
AS
BEGIN
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@CompanyId
	if(@isRequestCompOff is null or @isRequestCompOff='''')
		BEGIN
			select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		END
	select @isRequestCompOff
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftSettingsByComId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftSettingsByComId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================
-- Author:		Kumuthini
-- Create date: 15-Jan-09
-- Description:	Get the Shift Settings Details by Company Id
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	19-July-2013
-- Description		:	Added Select Query Column.
-- Modified By		:	Manjula.P
-- Modified On		:	18-Jan-2014
-- Descriptions		:	selecting lunch deduction hours columns for shift settings page
-- ================================================
-- Proc_TA_GetShiftSettingsByComId 1
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftSettingsByComId] 
(
	@CompanyId int
)
AS
BEGIN
		SELECT ShiftSettingId,
		CompanyId,
		MaxHoursBeforeShift,
		MaxHoursAfterShift,
		ShiftBreak,
		ShiftMaxBreakHours,
		MonthlyWorkingHours,
		WeeklyWorkingHours,
		EmpID,
		HolidayOT,
		WeekOffOT,
		otOption,
		DefaultMonthClosureDate,
		IsFlexible,
		FlexibleFlag,
		OTRoundoffEnable,
		FullDayAttendanceHrs,
		HalfDayAttendanceHrs,
		HalfDayAttendance,
		FullDayAttendance,
		WeeklyOffStartHours,
		IgnoreDuplicatePunch,
		PunchInterval,
		AfterShiftTime,
		BeforeShiftTime,
		DefinedWorkhrs,
		NoOfSuccessiveDaysInYear,
		CompensationValitityDays,
		VaildityCompOffDays,
		CAST(HalfDayCompOff AS VARCHAR(5)) AS HalfDayCompOff,
		CAST(FullDayCompOff AS VARCHAR(5)) AS FullDayCompOff,
		lateentry,earlyentry,earlyexit,lateexit,
		--Added by MAnjula.P on 18-Jan-2014
		isnull(IsLunchDeduction,0) as IsLunchDeduction, ISNULL(LunchDeductionHours,''00:00'') as LunchDeductionHours,
		Flexi_AfterShiftTime,Flexi_BeforeShiftTime,Flexi_DefinedWorkhrs,
		MaxHoursBeforeShift_24HrsShift,
		WeeklyOffStartHours_24HrsShift,
		CumulativeWeekStartDay,
		CumulativeWeekEndDay,
		[DefaultLunchHours],
		[MaxLunchHours],
		[MaxWorkPlaceInHours],Carry_Forward_COff_Year,isRequestingforCompOff,
		isnull(FirstAndLast,0)as FirstAndLast,
		SpecialOverTime1,SpecialOverTime2
		,isnull(LATEMINSPERDAY,0) as LATEMINSPERDAY,isnull(LATEDAYSPERMONTH,0) as LATEDAYSPERMONTH,isnull(EarlyExitMinsPerDay,0) as EarlyExitMinsPerDay, isnull(EarlyExitDaysPerMonth,0) as EarlyExitDaysPerMonth
		,isnull(EnableAbsent,0) as EnableAbsent
		FROM TA_Tbl_shiftSettings WHERE CompanyId = @CompanyId
		Declare @SuccessiveyearId int
		set @SuccessiveyearId = (select top 1 yearsettings_Id from ta_tbl_yearSetting where yearsettings_id> (select yearsettings_id from ta_tbl_yearSetting where isactive=1) order by yearsettings_id)
		select count(*) as RecordCount from ta_tbl_leaveApplication LA inner join ta_tbl_yearSetting YS on LA.YearSettings_Id=YS.YearSettings_Id 
		where LA.yearsettings_id=@SuccessiveyearId and LA.companyId=@CompanyId and LA.Successiveyear=1 and LA.isdeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftSettings]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getShiftSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getShiftSettings] 
AS
BEGIN
	Select * from TA_Tbl_shiftSettings
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIDForParticularDate]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIDForParticularDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11:00 AM>
-- Description:	<Get Shift ID For Particular Date>
--Proc_TA_GetShiftIDForParticularDate ''124'',''2019-07-08 00:00:00.000'',1,''08:30:20''
--Proc_TA_GetShiftIDForParticularDate ''788'',''2019-07-08 00:00:00.000'',1,''11:47:20''
--Proc_TA_GetShiftIDForParticularDate ''8967661'',''2019-08-14 00:00:00.000'',25,''22:30:20''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftIDForParticularDate]
	@Clk_EmpId VARCHAR(50),
	@DATE datetime,
	@COMPANYID INT
	,@Clk_time VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @QUERY VARCHAR(2000)   
	DECLARE @SHIFTID INT
	SET @SHIFTID=0
	DECLARE @ISDELETED INT
	CREATE TABLE #TEMP (SHIFTID INT)	
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)
	SET @YEAR=DATEPART(YEAR,@DATE)
	SET @MONTH=DATEPART(MONTH,@DATE)
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	SELECT  @EMPLOYEEAUTOID =Employee_Id FROM TA_Tbl_Employee WHERE SwipeCardNo=@Clk_EmpId and Isdeleted=0
	-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
	SET @QUERY = ''	SELECT (TSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
					WHERE TSA.[YEAR]= '' + @YEAR + ''  AND  TSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = ''''''+ @EMPLOYEEAUTOID +'''''' ''	
	INSERT INTO #TEMP EXEC(@QUERY)
	SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
	SET @SHIFTID = ISNULL(@SHIFTID,0) 
	DELETE FROM #TEMP
	-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
	IF(@SHIFTID = 0)
		BEGIN
			SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(d,@DATE)) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)			
			DELETE FROM #TEMP
		END
	IF(@SHIFTID != 0)
		BEGIN			
			IF((SELECT ISDELETED  FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID)=1)
				BEGIN
					SET @SHIFTID = ISNULL(@SHIFTID,0)	
						--print @SHIFTID
				END
		END
	-- TAKE THE DEFAULT SHIFT FROM THE SHIFT MASTER
	IF(@SHIFTID = 0)
		BEGIN
			SET @SHIFTID = (SELECT Shift_Id FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@COMPANYID)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)
			IF(@SHIFTID = 0)
				BEGIN					
					SET @SHIFTID = (SELECT SHIFT_ID FROM TA_TBL_SHIFT WHERE LEVEL_ID = 0 AND ISDELETED = 0)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
							--print @SHIFTID
				END
		END
	IF(@SHIFTID > 0)
		BEGIN
			SELECT ISNULL(SHIFT_ID,0)AS SHIFTID FROM TA_TBL_SHIFT WHERE SHIFT_ID = @SHIFTID
		END
	ELSE IF (@SHIFTID = -1 OR @SHIFTID = 0)
		BEGIN
			SELECT @SHIFTID AS SHIFTID
		END		
	DROP TABLE #TEMP	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdBeforeWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetShiftIdBeforeWeekOff
Description	:	Get ShiftId for a Given From Date
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By	:	Prabakaran
Created On	:	15-Aug-07
Modified By	:
Modified On	:
Proc_TA_GetShiftIdBeforeWeekOff 104,''02/16/2011''
select Employee_Id from TA_tbl_Employee
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeWeekOff]
@EmployeeId int,
@FromDate datetime
as
begin
	declare @SearchDate as datetime
	declare @query as Varchar(3000)
	Declare @TempShiftId as int
	create table #Temp(ShiftTemp int)
	create table #Temp1(ShiftTemp int)
	set @SearchDate=DateAdd(day,-1,@FromDate)
	set @query = (''select Day'' + Cast(Day(@SearchDate) as Varchar(25)) + ''Shift from  TA_Tbl_TemporaryShiftAllocation where Year = year('''''' + cast(@SearchDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@SearchDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
	insert into #Temp EXEC(@query)
	set @TempShiftId=(select * from #Temp)
	drop table #Temp
	if @TempShiftId=-1 or @TempShiftId>0
	begin
	select @TempShiftId as ShiftId
	end
	else if @TempShiftId=0 or @TempShiftId is null
	begin
	set @query = (''select Day'' + Cast(Day(@SearchDate) as Varchar(25)) + ''Shift from  TA_Tbl_PermanentShiftAllocation where Year = year('''''' + cast(@SearchDate as Varchar(25)) + '''''') and Month = month(''''''+ cast(@SearchDate as varchar(25)) +'''''') and EmployeeId ='' + cast(@EmployeeId as varchar(20)))
	insert into #Temp1 EXEC(@query)
	set @TempShiftId=(select * from #Temp1)
	drop table #Temp1
	if(@TempShiftId='''' or @TempShiftId is null)
	BEGIN
	set @TempShiftId=(select Shift_Id from TA_tbl_shift where Shift_Name=''No Shift'')
	END
	select @TempShiftId as ShiftId
	end
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetShiftIdBeforeAfterWeekOff 
Description		:	Get ShiftId for a Given From Date
Tables Included	:	TA_Tbl_TemporaryShiftAllocation and TA_Tbl_PermanentShiftAllocation
Created By		:	Prabakaran
Created On		:	15-Aug-07
Modified By		:
Modified On		:
[Proc_TA_GetShiftIdBeforeAfterWeekOff] 104,''02/16/2011'',''02/16/2011'',''A''
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftIdBeforeAfterWeekOff]
@EMPLOYEEID INT,
@FROMDATE DATETIME,
@TODATE DATETIME,
@TYPE VARCHAR(10)
as
BEGIN
	DECLARE @SEARCHDATE AS DATETIME
	DECLARE @QUERY AS VARCHAR(3000)
	DECLARE @TEMPSHIFTID AS INT
	CREATE TABLE #TEMP(SHIFTTEMP INT)
	CREATE TABLE #TEMP1(SHIFTTEMP INT)
	IF @TYPE=''A''
		BEGIN
			SET @SEARCHDATE=DATEADD(DAY,-1,@FROMDATE)
		END
	ELSE IF @TYPE=''B''
		BEGIN
			SET @SEARCHDATE=DATEADD(DAY,1,@TODATE)
		END
	SET @QUERY = (''SELECT DAY'' + CAST(DAY(@SEARCHDATE) AS VARCHAR(25)) + ''SHIFT FROM  TA_TBL_TEMPORARYSHIFTALLOCATION WHERE YEAR = YEAR('''''' + CAST(@SEARCHDATE AS VARCHAR(25)) + '''''') AND MONTH = MONTH(''''''+ CAST(@SEARCHDATE AS VARCHAR(25)) +'''''') AND EMPLOYEEID ='' + CAST(@EMPLOYEEID AS VARCHAR(20)))
	INSERT INTO #TEMP EXEC(@QUERY)
	SELECT @TEMPSHIFTID=SHIFTTEMP FROM #TEMP
	DELETE FROM #TEMP
	IF @TEMPSHIFTID=-1 OR @TEMPSHIFTID>0
		BEGIN
			SELECT @TEMPSHIFTID AS SHIFTID
		END
	ELSE IF @TEMPSHIFTID=0 OR @TEMPSHIFTID IS NULL
		BEGIN
			SET @QUERY = (''SELECT DAY'' + CAST(DAY(@SEARCHDATE) AS VARCHAR(25)) + ''SHIFT FROM  TA_TBL_PERMANENTSHIFTALLOCATION WHERE YEAR = YEAR('''''' + CAST(@SEARCHDATE AS VARCHAR(25)) + '''''') AND MONTH = MONTH(''''''+ CAST(@SEARCHDATE AS VARCHAR(25)) +'''''') AND EMPLOYEEID ='' + CAST(@EMPLOYEEID AS VARCHAR(20)))
			INSERT INTO #TEMP EXEC(@QUERY)
			SELECT @TEMPSHIFTID=SHIFTTEMP FROM #TEMP
			DELETE FROM #TEMP
			IF(@TEMPSHIFTID='''' OR @TEMPSHIFTID IS NULL)
			BEGIN
				SELECT @TEMPSHIFTID=SHIFT_ID FROM TA_TBL_SHIFT WHERE SHIFT_NAME=''NO SHIFT''
			END
			SELECT @TEMPSHIFTID AS SHIFTID
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetShiftId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetShiftId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Proc_Ta_GetShiftId] 4,''06/14/2020'',787,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetShiftId]
	-- Add the parameters for the stored procedure here
	@EmployeeAutoId int, 
	@ShiftDate datetime, 
	@Employee_Code_Id varchar(50),
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @query VARCHAR(2000)   
	DECLARE @ShiftId INT 
	set @ShiftId=1
	CREATE Table #Temp (ShiftId INT)
	Declare @Date int
	Declare @year int
	declare @month int
	set @Date=datepart(d,@shiftDate)
	set @month=datepart(M,@shiftDate)
	set @year=datepart(y,@shiftDate)
	--select @date 
	-- Check Shift in Temporary Shift Allocation
	SET @query = ''SELECT (tsa.Day''+ CONVERT(varchar(10),@date) + ''Shift) AS ShiftId from 
				TA_Tbl_TemporaryShiftAllocation tsa 
				where tsa.[Year]= '' + CONVERT(varchar(10),@year) + ''  and  tsa.[Month]= '' + CONVERT(varchar(10),@month) + '' and   
				tsa.EmployeeId = ''+ CONVERT(varchar(10),@EmployeeAutoId) +''''  
	INSERT INTO #Temp EXEC(@query)
	SET @ShiftId = (SELECT ShiftId FROM #Temp)
	SET @ShiftId = ISNULL(@ShiftId,-2)	
	--DELETE FROM #Temp
	-- Check Shift in Permanent Shift Allocation if not in Temporary
	IF(@ShiftId = -2 OR @ShiftId = 0)
		BEGIN
			SET @query = ''SELECT (psa.Day''+ CONVERT(varchar(10),@date) + ''Shift) AS ShiftId from TA_Tbl_PermanentShiftAllocation psa
			
			where psa.[Year]= '' + CONVERT(varchar(10),@year) + ''  and  psa.[Month]= '' + CONVERT(varchar(10),@month) + '' and   
			psa.EmployeeId = ''+ CONVERT(varchar(10),@EmployeeAutoId) +''''  
			INSERT INTO #Temp EXEC(@query)
			SET @ShiftId = (SELECT ShiftId FROM #Temp)
			SET @ShiftId = ISNULL(@ShiftId,-2)			
			DELETE FROM #Temp
		END
	-- Take the Default Shift from the Shift Master
	
	IF(@ShiftId = -2 OR @ShiftId = 0 or @ShiftId='''')
		BEGIN
			SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE DefaultShift = 1 AND IsDeleted = 0 and Level_Id=@CompanyId)			
			SET @ShiftId = ISNULL(@ShiftId,-2)
			IF(@ShiftId = -2)
				BEGIN			
					SET @ShiftId = (SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName =''Nos'' AND IsDeleted = 0)
				END
		END	
	Select @ShiftId
	DROP Table #Temp	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Getting Shift Details of all companies>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftDetailsOfAllCompanies]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT	Shift_Id, Level_Id, Shift_Name, Shift_ShortName, Shift_Description, Shift_StartTime, Shift_EndTime, Shift_FirstHalf_StartTime, Shift_FirstHalf_EndTime, 
	Shift_SecondHalf_StartTime, Shift_SecondHalf_EndTime, Shift_GraceInTime, Shift_GraceOutTime, Shift_BreakStartTime1, Shift_BreakEndTime1, Shift_BreakStartTime2, 
	Shift_BreakEndTime2, Shift_BreakStartTime3, Shift_BreakEndTime3, Shift_MinTimeOT, Shift_MaxTimeOT, Shift_WorkingDay_OverTime, Shift_TotalWorkingHours, 
	Shift_LunchOutTimeGrace, Shift_LunchInTimeGrace, Shift_LunchOutTimeGraceBefore, Shift_LunchOutTimeGraceAfter, Shift_LunchInTimeGraceBefore, 
	Shift_LunchInTimeGraceAfter, Shift_LunchOutTimeGraceBeforeChk, Shift_LunchOutTimeGraceAfterChk, Shift_LunchInTimeGraceBeforeChk, Shift_LunchInTimeGraceAfterChk, 
	Isdeleted, Emp_ID, Shift_FirstHalfWorkingHours, Shift_SecondHalfWorkingHours, IsBreakDeducted, DefaultShift, ShiftType, CreatedDate, ModifiedDate, [24HrsShift]	
	,MaxShiftWorkHours as MaxExtraShiftWorkHours
	FROM TA_Tbl_Shift WHERE IsDeleted = 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousNextLeave]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPreviousNextLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
					Proc_TA_GetPreviousNextLeave 61,''03/27/2013'', ''03/29/2013''
					Proc_TA_GetPreviousNextLeave 68,''04/01/2013 12:00:00 AM'',''04/04/2013 12:00:00 AM''
Created By		:	Manjula.P
Created Date	:	23-May-2013
Descriptions	:	To restrict the combined leave of both CL and SL/Comp Off as per the new leave policy
*/
CREATE proc [dbo].[Proc_TA_GetPreviousNextLeave]
(
@Employee_Id int,
@LeavePrevious datetime,
@LeaveNext datetime
)
as 
begin
	SET NOCOUNT ON;
	select LA.LeaveApplication_Id,LT.LeaveType,LA.Leave_FromDate,LA.Leave_ToDate,Employee_Id,LA.Type, LA.NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
	where (LA.Employee_Id=@Employee_Id) 
	and
	(
	(LA.Leave_ToDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_ToDate=CONVERT(varchar(12), @LeaveNext,111)) 
	or
	(LA.Leave_FromDate=convert(varchar(12),@LeavePrevious,111) or LA.Leave_FromDate=CONVERT(varchar(12), @LeaveNext,111))
	or           
	(LA.Leave_FromDate >= convert(varchar(12),@LeavePrevious,111) and LA.Leave_ToDate <=CONVERT(varchar(12), @LeaveNext,111))
	)
	and LA.IsDeleted=0 and LA.Status<>''Rejected''
end
--SELECT CURRENT_TIMESTAMP
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPreviousLeaveDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPreviousLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_GetPreviousLeaveDetails
Description		: Get Previous Leave Details
Created By		: A.K.T.MOORTHI
Created On		: 03-JUNE-2013
Modified By		: A.K.T.MOORTHI
Modified On		: 10-JULY-2013
Description		: Change the Table header for ''Leave Availed Details'' to ''Leave Status''
EXEC [Proc_TA_GetPreviousLeaveDetails] 545, '''', ''M''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetPreviousLeaveDetails]
	@EmployeeId INT = NULL,
	@EmployeeCode VARCHAR(60) = NULL,
	@Type VARCHAR(1)
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @EmpFYLeave TABLE(EmployeeId INT, LeaveType VARCHAR(100), NumberOfDays DECIMAL(18,1), LeaveStatus VARCHAR(20))
	DECLARE @EmpCMLeave TABLE(EmployeeId INT, LeaveType VARCHAR(100), NumberOfDays DECIMAL(18,1), LeaveStatus VARCHAR(20))
	DECLARE @FYResult VARCHAR(MAX), @CMResult VARCHAR(MAX)
	INSERT INTO @EmpFYLeave
		SELECT LA.Employee_Id, CASE WHEN LA.[Type] = ''Leave'' THEN LT.LeaveType ELSE LA.[Type] END, LA.NumberOfDays, LA.[Status] FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '''') OR E.Employee_Code_Id = @EmployeeCode) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN (''Rejected'', ''Canceled'')
	INSERT INTO @EmpCMLeave
		SELECT LA.Employee_Id, CASE WHEN LA.[Type] = ''Leave'' THEN LT.LeaveType ELSE LA.[Type] END, LA.NumberOfDays, LA.[Status] FROM TA_Tbl_LeaveApplication LA
			LEFT JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id = LA.LeaveType_id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id AND YS.IsActive = 1
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = LA.Employee_Id
		WHERE ((@EmployeeId IS NULL OR @EmployeeId = 0) OR LA.Employee_Id = @EmployeeId) AND 
			((@EmployeeCode IS NULL OR @EmployeeCode = '''') OR E.Employee_Code_Id = @EmployeeCode) AND
			DATEPART(M,LA.Leave_FromDate) = DATEPART(M,GETDATE()) AND DATEPART(M,LA.Leave_ToDate) = DATEPART(M,GETDATE()) AND
			LA.IsDeleted = 0 AND LA.[Status] NOT IN (''Rejected'', ''Canceled'')
	IF @Type = ''P'' 
	BEGIN
		SELECT 
			LeaveStatus,
			ISNULL(CL, 0) AS CL,
			ISNULL(LOP, 0) AS LOP,
			ISNULL(SL, 0) AS SL,
			ISNULL([Comp Off], 0) AS [Comp Off]
		FROM 
		(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpFYLeave) Tbl
		PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
		SELECT 
			LeaveStatus,
			ISNULL(CL, 0) AS CL,
			ISNULL(LOP, 0) AS LOP,
			ISNULL(SL, 0) AS SL,
			ISNULL([Comp Off], 0) AS [Comp Off]
		FROM 
		(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpCMLeave) Tbl
		PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
	END
	ELSE
	BEGIN
		SET @FYResult = ''<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr><tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">No Record Found</font></b></td></tr></table>''
		SET @CMResult = ''<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr><tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">No Record Found</font></b></td></tr></table>''
		IF EXISTS(SELECT EmployeeId FROM @EmpFYLeave)
		BEGIN
			SET @FYResult = ''<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr>''
			SELECT 
				@FYResult = @FYResult + ''<tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">'' + CAST(LeaveStatus AS VARCHAR) + ''</font></b></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(CL, 0) AS VARCHAR) + ''</font></td>'' + 
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(LOP, 0) AS VARCHAR) + ''</font></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(SL, 0) AS VARCHAR) + ''</font></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL([Comp Off], 0) AS VARCHAR) + ''</font></td></tr>''
			FROM 
			(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpFYLeave) Tbl
			PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
			SET @FYResult = @FYResult + ''</table>''
		END
		IF EXISTS(SELECT EmployeeId FROM @EmpCMLeave)
		BEGIN
			SET @CMResult = ''<table border="1" cellpadding="2" style="border-collapse: collapse; width:100%;" bordercolor="#666666"><tr bgColor="#003466"><td height="25"><span class="Header">Leave Status</span></td><td height="25"><span class="Header">CL</td><td height="25"><span class="Header">LOP</td><td height="25"><span class="Header">SL</td><td height="25"><span class="Header">Comp Off</td></tr>''
			SELECT 
				@CMResult = @CMResult + ''<tr><td height="19" bgcolor="AliceBlue"><b><font face="Arial" size="2">'' + CAST(LeaveStatus AS VARCHAR) + ''</font></b></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(CL, 0) AS VARCHAR) + ''</font></td>'' + 
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(LOP, 0) AS VARCHAR) + ''</font></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL(SL, 0) AS VARCHAR) + ''</font></td>'' +
					''<td height="19"><font face="Arial" size="2">'' + CAST(ISNULL([Comp Off], 0) AS VARCHAR) + ''</font></td></tr>''
			FROM 
			(SELECT LeaveType,LeaveStatus, NumberOfDays FROM @EmpCMLeave) Tbl
			PIVOT(SUM(NumberOfDays) FOR LeaveType IN(CL, LOP, SL, [Comp Off])) AS PVT
			SET @CMResult = @CMResult + ''</table>''
		END
		SELECT ''</br><table border="0" cellpadding="0" cellspacing="1" style="border-collapse: collapse" bordercolor="#111111" width="700"><tr bgColor="#003466"><td height="25" style="border-right: #FFFFFF 1px solid; text-align:center; width:45%;" class="Header">Leave Status - Current Year</td><td style="width:10%; background-color:#FFFFFF;"></td><td height="25" class="Header" style="border-right: #FFFFFF 1px solid; text-align:center; width:45%;">Leave Status - Current Month</td></tr><tr><td style="border-right:#FFFFFF 1px solid; width:45%; vertical-align:top;">'' + @FYResult + ''</td><td style="width:10%;"></td><td style="border-left:#FFFFFF 1px solid; width:45%; vertical-align:top;">'' + @CMResult + ''</td></tr></table>'' AS ''LeaveDetails''
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportToAndSanctionAuthority]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReportToAndSanctionAuthority]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetReportToAndSanctionAuthority]
(
    @Employee_Code_Id nVarchar(25)
)
AS
SELECT Reporting_To,Leave_Sanc_Authority FROM TA_Tbl_Employee WHERE Employee_Code_Id = @Employee_Code_Id
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReportsForEmailSchedule]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReportsForEmailSchedule]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:   <Description,,>
-- Modified By   : Thilakraj C
-- Modified date : 25-Feb-2013
-- Description   : make a Inner Join with TA_Tbl_Usergroup table.
-- [Proc_TA_GetReportsForEmailSchedule] ''Superadmin''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReportsForEmailSchedule]  
(
	@UserGroupName varchar(250)
)
AS
BEGIN
   SET NOCOUNT ON;
    -- Insert statements for procedure here
   select P.pageId,case when P.pageId IN(180,183,160) then P.displayName+''''+''_Title'' else P.displayName end displayName,''../'' + P.path as path
   ,case	when P.pageId=183	then	1		when P.pageId=41	then 2	when P.pageId=118	then 3	when P.pageId=40	then 4
					when P.pageId=180 then	5		when P.pageId=105 then 6	when P.pageId=30	then 7	when P.pageId=160 then 9					
					when P.pageId=175 then	8		when P.pageId=34	then 11	when P.pageId=37	then 10	when P.pageId=35	then 12
					when P.pageId=92	then	13	when P.pageId=39	then 14	when P.pageId=36	then 15	when P.pageId=89	then 16
					when P.pageId=127 then	17	when P.pageId=33	then 18	when P.pageId=32	then 19
				end
   from TA_Tbl_Page P
   Inner join TA_Tbl_Usergroup UG on UG.groupName=@UserGroupName
   inner join TA_Tbl_userRights UR on UR.groupId=UG.groupId and UR.pageId=P.pageId   
   where P.pageId in (30,32,33,34,35,36,37,39,40,41,89,92,105,118,127,160,175,180,183)
   and UG.groupName=@UserGroupName and UR.viewPrv=1  order by 4
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPageStandard]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountInPageStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountInPageStandard]
	@PageId as int
AS
BEGIN
	select Rows from Ta_tbl_PageRedirectStandard where PageId=@PageId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountInPage]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountInPage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountInPage]
	@PageId as int
AS
BEGIN
	select Rows from Ta_tbl_PageRedirect where PageId=@PageId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPageStandard]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountAllPageStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPageStandard]
AS
BEGIN
	select * from Ta_tbl_PageRedirectStandard where Active=1 order by ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRowsCountAllPage]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRowsCountAllPage]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRowsCountAllPage]
AS
BEGIN
	select * from Ta_tbl_PageRedirect where Active=1 order by ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRouteCountFromEmployee]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRouteCountFromEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  Procedure [dbo].[Proc_TA_GetRouteCountFromEmployee]         
(          
 @RouteId int          
)           
As          
DECLARE @Isdel INT          
SET @Isdel=0       
BEGIN          
   Select Count(bus_id)as RouteCount from ta_tbl_employee          
   where bus_id=@RouteId  AND Isdeleted=@Isdel           
END   
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  Procedure [dbo].[Proc_TA_GetRestrictedHolidaysCountLeaveApplication]         
As
BEGIN          
	SET NOCOUNT ON;
	select count(isnull(la.NumberOfDays,0)) as RHCount from ta_tbl_Leaveapplication la
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
	where ys.IsActive=1 and la.Type=''Restricted Holiday'' and la.Isdeleted=0 and la.Status <> ''Rejected'' 
	Group by la.Employee_Id  
	--order by count(la.Employee_Id) desc        
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getShiftByWeekDayId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getShiftByWeekDayId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	30-Dec-2013
Descriptions	:	Adding this procedure for selecting the tempweekday shifts values
Proc_TA_getShiftByWeekDayId 34
*/
CREATE proc [dbo].[Proc_TA_getShiftByWeekDayId]
(
@TempWeekDayId int
)
as
begin
	create table #temp(ShiftId nvarchar(max))
	declare  @TableShiftId nvarchar(max)
	set @TableShiftId=(SELECT TWD.ShiftId FROM TA_Tbl_TemWeekday TWD	
	WHERE TempWeekday_Id=@TempWeekDayId)
	insert into #temp
	select value from Split((Select * from (select @TableShiftId as ShiftId) A), '','')
	select * from #temp 
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetScheduleDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetScheduleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_GetScheduleDetails 1,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_GetScheduleDetails]	
(
 @EmployeeId int,
 @UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	if(@UserGroupName = ''SuperAdmin'')
	BEGIN
		select ES.ScheduleId,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + '' '' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then ''Enabled'' else ''Disabled'' end as Enabled,TimeToSend
		from TA_tbl_EmailSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Isdeleted=0 and E.Employee_Status=1 and ES.IsDeleted=0
		order by ScheduleId
	END
	else
	BEGIN
		select ES.ScheduleId,ES.ScheduleName,ES.ReportName as displayName,ES.Frequency,E.Employee_FirstName + '' '' + E.Employee_LastName as EmployeeName,
		case when ES.Enabled=1 then ''Enabled'' else ''Disabled'' end as Enabled,TimeToSend
		from TA_tbl_EmailSchedule ES
		inner join TA_Tbl_Page P on P.pageId = ES.ReportId
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeId
		where E.Employee_Id = @EmployeeId and ES.IsDeleted=0
		order by ScheduleId
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSaturday_WorkHrs]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSaturday_WorkHrs]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Proc_TA_GetSaturday_WorkHrs 62
Created By		: Manjula.P
Created Date	: 27-May-2013
Descriptions	: For getting saturday work hours per employee for gussing employee category
*/
CREATE proc [dbo].[Proc_TA_GetSaturday_WorkHrs]
(
 @EmployeeId int=0
)
as
begin
select Sat_WorkHrs from TA_Tbl_Employee E 
inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id
inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
where Employee_Id=@EmployeeId
order by EC.EffectiveDate  desc
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPageName]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPageName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetPageName]
@strType varchar(20)-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@strType!=''Standard'')
	begin
		-- Insert statements for procedure here
		SELECT pageId, displayname+''_Title'', path,
		case	when pageId=177 then 177 
				when pageId=179 then 179 
				when pageId=246 then 246 
				when pageId=249 then 249
				else parentId end as parentId, orderby from ta_tbl_page where parentId=0 
		order by orderBy 
		--where (path is not null and path<>'''') 
		--group by pageId,displayname,path,parentId,orderby 
		--order by parentId,orderby
	END
	else
	BEGIN
		-- Insert statements for procedure here
		SELECT	pageId, displayname+''_Title'', path,
				case	when pageId=177 then 177 
						when pageId=179 then 179 
						when pageId=246 then 246 
						when pageId=249 then 249
						else parentId end as parentId, orderby from ta_tbl_page 
		where pageId not in (20,24,25,69,96,97,98,108,110,174) and parentId=0 
		--and (path is not null and path<>'''') 
		group by pageId,displayname,path,parentId,orderby order by parentId,orderby
	END
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Overtime status
-- drop procedure Proc_Ta_GetOverTimeApprovalStatus
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatusForService]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	BEGIN TRY
		BEGIN TRANSACTION
		SELECT CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry FROM TA_Tbl_ApprovalSettings WHERE CompanyId = @CompanyId
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetOverTimeApprovalStatus]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetOverTimeApprovalStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetOverTimeApprovalStatus]
	-- Add the parameters for the stored procedure here
	@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    Declare @OTApproval varchar(20)
    Declare @status varchar(20)
    set @status=''''
    -- Insert statements for procedure here
	SELECT CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry FROM TA_Tbl_ApprovalSettings WHERE CompanyId = @CompanyId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetOTRoundoffByShiftSettingId]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_OTRoundoffSettings WHERE ShiftSettingId = @shiftSettingId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyConversation]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Gopinath.K
-- Create date: 17June2014
-- Description:For get the OD conversation details.
--Proc_TA_GetLeaveConversation 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetOnDutyConversation] 
	@OnDutyApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @OnDutyApplicationId Order By OrderBY Desc
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getNewsById]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getNewsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		SENTHIL
-- Create date: 11-Sep-07
-- Description:	Edit News
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getNewsById]
(
	@newsId as int
)
AS
BEGIN
	select convert(varchar(15),NewsEventFromDate,101) as NewsEventFromDate,convert(varchar(15),NewsEventToDate,101) as NewsEventToDate,
	NewsEventTitle,NewsEventDescription,NewsEventActive, NewsEventImage, LeftNewsEvent,RightNewsEvent from ta_tbl_newsEvents 
	where isdeleted=0 and newsEvent_Id=@newsId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionTypeDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReligionTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- ModifiedBy:		Manikandan.R
-- Modified date:	09-June-2012
-- Description:	to check the check boxes.
-- =============================================
CREATE  Proc [dbo].[Proc_TA_GetReligionTypeDetails]      
(    
	@UserGroupName nVarchar(250)    
)    
AS     
	Create table #TempReligion(ID int,Name nvarchar(100),Description nvarchar(500),IsDeleted bit,flag int)
	IF(@UserGroupName = ''SuperAdmin'')    
		BEGIN
			insert into #TempReligion
			SELECT ID,Name,Description,IsDeleted,0 FROM TA_Tbl_Religion order by Name        
		END    
	ELSE    
		BEGIN
			insert into #TempReligion
			SELECT ID,Name,Description,IsDeleted,0 FROM TA_Tbl_Religion Where IsDeleted=0 order by Name           
		END
	Update #TempReligion set flag =1 from #TempReligion TR inner join TA_Tbl_Employee TE on TE.Religion =  TR.ID 
	--where TE.IsDeleted=0
	Update #TempReligion set flag =1 from #TempReligion TR inner join TA_Tbl_leavetype LT on LT.Religion =  TR.ID 
	--where LT.IsDeleted=0
	select * from #TempReligion 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReligionDetailsById]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReligionDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetReligionDetailsById]      
(      
 @ID int,    
 @UserGroupName nVarchar(250)      
)      
AS      
  IF(@UserGroupName = ''SuperAdmin'')    
    BEGIN    
       SELECT ID,Name,Description,IsDeleted FROM TA_Tbl_Religion Where ID=@ID     
    END    
 ELSE    
   BEGIN    
       SELECT ID,Name,Description,IsDeleted FROM TA_Tbl_Religion Where IsDeleted=0 AND ID=@ID      
   END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveSanction]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRecordsCountLeaveSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_GetRecordsCountLeaveSanction
Description		:	Get Record count of Leave sanction authority details
Tables Included		:	 TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	27-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE     PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveSanction] 
@Employee_Id int
as
Begin
	SET NOCOUNT ON;
	select count(*) RecordsCount from TA_TBL_Employee l 
	inner join TA_TBL_Employee r 
	on l.Employee_Id=r.Leave_Sanc_Authority 
	where l.Employee_Id=@Employee_Id and l.Isdeleted=0 and r.Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRecordsCountLeaveReportingTo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_GetRecordsCountLeaveReportingTo
Description		:	Get Record count of Leave Reporting To details
Tables Included		:	TA_TBL_Employee
Created By		:	Prabakaran
Created On		:	25-11-2008
Modified By		:	
Modified On		:	
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetRecordsCountLeaveReportingTo] 
@Employee_Id int
as
begin
	SET NOCOUNT ON;
	select count(*) RecordsCount from TA_TBL_Employee l 
	inner join TA_TBL_Employee r 
	on l.Employee_Id=r.Reporting_To and l.Employee_Id<>r.Leave_Sanc_Authority
	where l.Employee_Id=@Employee_Id and l.Isdeleted=0 and r.Isdeleted=0
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetReaderDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetReaderDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 12.47PM>
-- Description:	<Get Reader Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetReaderDetails]
	@inTerminalId int
AS
BEGIN	
	SET NOCOUNT ON;
	SELECT Terminal_ReaderId FROM TA_Tbl_Terminal where Terminal_Id = @inTerminalId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRawDataFromManualEntry]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRawDataFromManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 15.13>
-- Description:	Get the Raw Data from the Manual Time Entry Table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRawDataFromManualEntry]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT M.ManualTimeEntry_Employee_Id,E.SwipeCardNo,M.ManualTimeEntry_Id,convert(varchar(25), M.ManualTimeEntry_InDate,120) as ManualTimeEntry_InDate,
	M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,M.ManualTimeEntry_InReaderID,convert(varchar(25), M.ManualTimeEntry_OutDate,120) as ManualTimeEntry_OutDate,
	M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_Reason,M.Emp_Id,0 as isOnduty,Clock_Address,Latitude_value,Longitude_value FROM TA_Tbl_ManualTimeEntry M 
	INNER JOIN TA_Tbl_Employee E ON M.ManualTimeEntry_Employee_Id = E.Employee_Code_Id 
	WHERE M.Clk_Process = ''N'' AND M.Isdeleted = 0  AND M.ManualTimeEntry_Status = ''Approved'' and E.Isdeleted=0 and IsOnDuty=0
	union all
	SELECT M.ManualTimeEntry_Employee_Id,E.SwipeCardNo,M.ManualTimeEntry_Id,convert(varchar(25), M.ManualTimeEntry_InDate,120) as ManualTimeEntry_InDate,
	M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,M.ManualTimeEntry_InReaderID,convert(varchar(25), M.ManualTimeEntry_OutDate,120) as ManualTimeEntry_OutDate,
	M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_Reason,M.Emp_Id,1 as isOnduty,Clock_Address,Latitude_value,Longitude_value FROM TA_Tbl_ManualTimeEntry M 
	INNER JOIN TA_Tbl_Employee E ON M.ManualTimeEntry_Employee_Id = E.Employee_Code_Id
	Inner join TA_Tbl_OndutyEntry OD on (M.OnDuty_ID=OD.Onduty_ID)
	WHERE M.Clk_Process = ''N'' AND M.Isdeleted = 0  AND M.ManualTimeEntry_Status = ''Approved'' and E.Isdeleted=0 and IsOnDuty=1
	AND OD.Onduty_Status = ''Approved'' and OD.Isdeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPenaltyPercentageDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPenaltyPercentageDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <18-06-2019 10:20 AM>
-- Description:	<Get the Penalty Percentage details for displaying>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPenaltyPercentageDetails]
	@CompanyID int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT CompanyId, categoryID, StartTime1, EndTime1, StartTime2, EndTime2, StartTime3, EndTime3,
	Day1=convert(int,Day1), 
	Day2=convert(int,Day2), 
	Day3=convert(int,Day3), 
	Day4=convert(int,Day4), 
	Day5=convert(int,Day5),
	Day6=convert(int,Day6),
	Day7=convert(int,Day7), 
	Day8=convert(int,Day8), 
	Day9=convert(int,Day9), 
	Day10=convert(int,Day10), 
	Day11=convert(int,Day11), 
	Day12=convert(int,Day12), StartTime1Mins, EndTime1Mins, StartTime2Mins, EndTime2Mins, StartTime3Mins, EndTime3Mins from ta_tbl_PenaltyPercentage where CompanyId=@CompanyID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : Proc_TA_GetPermissionHoursAlreadyTaken 5,''11/21/2016''
Description : Get Total No of Permisssion Hours Taken in minutes Based on their Employee_Id
Tables Included : TA_Tbl_Permission
Created By : Prabakaran
Created On : 21-Jul-07
Modified By :
Modified On :
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionHoursAlreadyTaken]
	@Employee_Id bigint,
	@permissionDate datetime
AS
begin
	set nocount on;
	Create table #tempPermission(HoursTakenInMinutes varchar(20), InstancesTaken int)
	insert into #tempPermission 
		Select SUM(
		convert(int,substring(No_Of_Hours,0,charindex('':'',No_Of_Hours)))*60+convert(int,substring(No_Of_Hours,charindex('':'',No_Of_Hours)+1,LEN(No_Of_Hours)))) as HoursTakenInMinutes ,isnull(count(*),0) as InstancesTaken from TA_Tbl_Permission
		inner join TA_Tbl_YearSetting ys on TA_Tbl_Permission.YearSettings_Id=ys.YearSettings_Id
		where ys.IsActive=1 and Employee_Id =@Employee_Id and IsDeleted = 0 
		and Permission_Status <>''Rejected'' 
		and month(Permission_Date)=month(@permissionDate) 
		and year(Permission_Date)=year(@permissionDate)
		select isnull(case when len(HoursTakenInMinutes/60)=1 then ''0''+CONVERT(varchar(20),HoursTakenInMinutes/60)
		else CONVERT(varchar(20),HoursTakenInMinutes/60) 
		end 
		+ '':'' + 
		case when len(HoursTakenInMinutes%60)=1 then ''0''+CONVERT(varchar(20),HoursTakenInMinutes%60)
		else CONVERT(varchar(20),HoursTakenInMinutes%60)
		end,''00:00'') as HoursTakenInMinutes,InstancesTaken from #tempPermission 
	drop table #tempPermission
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollConfigurationDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPayrollConfigurationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================
-- Author:		Gopinath
-- Create date: 23-Jul-15
-- Description:	Get the PayrollConfiguration Settings Details
-- ================================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPayrollConfigurationDetails] 
AS
BEGIN
select convert(char(5),dateadd(MINUTE,StartTime1,''''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_Lateentry
select  convert(char(5),dateadd(MINUTE,StartTime1,''''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_Armis
select  convert(char(5),dateadd(MINUTE,StartTime1,''''),114) as StartTime1,convert(char(5),dateadd(MINUTE,EndTime1,''''),114) as EndTime1,Day1,
convert(char(5),dateadd(MINUTE,StartTime2,''''),114) as StartTime2,convert(char(5),dateadd(MINUTE,EndTime2,''''),114) as EndTime2,Day2,
convert(char(5),dateadd(MINUTE,StartTime3,''''),114) as StartTime3,convert(char(5),dateadd(MINUTE,EndTime3,''''),114) as EndTime3,Day3,
convert(char(5),dateadd(MINUTE,StartTime4,''''),114) as StartTime4,convert(char(5),dateadd(MINUTE,EndTime4,''''),114) as EndTime4,Day4,
convert(char(5),dateadd(MINUTE,StartTime5,''''),114) as StartTime5,convert(char(5),dateadd(MINUTE,EndTime5,''''),114) as EndTime5,Day5,
convert(char(5),dateadd(MINUTE,StartTime6,''''),114) as StartTime6,convert(char(5),dateadd(MINUTE,EndTime6,''''),114) as EndTime6,Day6 from ta_tbl_NoOfDaysDeduction_WorkHrs
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedManualEntryId]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcessedManualEntryId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckProcessedManualEntryId  
Description : To check whether the manual time entry has already been processed by passing Manual Time Entry Id
Tables Included : TA_Tbl_ManualTimeEntry  
Created By :  Kumuthini 
Created On : 26-Jan-2008
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcessedManualEntryId]
(@ManualTimeEntryId int)
AS
BEGIN
	SELECT COUNT(*) AS Count FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Id = @ManualTimeEntryId AND Clk_Process = ''Y''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckProcessedData]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckProcessedData  
Description : check process data  
Tables Included : TA_Tbl_ProcessedData  
Created By : Kumuthini.L  
Created On : 05-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckProcessedData]
(
  @SwipeCardNo nvarchar(20),
  @Date DateTime
)
AS
SELECT [Date] FROM TA_Tbl_ProcessedData where Employee_Code_Id = @SwipeCardNo and [Date] = @Date
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckPermissionUpdate  
Description : For Checking the Permission Date already Exists
Tables Included : TA_Tbl_Permission  
Created By : Prabakaran.P  
Created On : 14-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckPermissionUpdate]
(
	@Employee_Id int,
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime
)
AS
begin
	set nocount on;
	select COUNT(*) as CS from TA_Tbl_Permission where Employee_Id =@Employee_Id And IsDeleted=0 And Permission_Date=@PermissionDate
	And (( Permission_FromTime  between @Permission_FromTime And @Permission_EndTime) or (Permission_ToTime between @Permission_FromTime And @Permission_EndTime))
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionHours]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckPermissionHours  
Description		: For Checking the Permission Date already Exists
Tables Included : TA_Tbl_Permission  
Created By		: Prabakaran.P  
Created On		: 14-Aug-2007 
Modified By		:  
Modified On		:  
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_CheckPermissionHours]
(
	@Employee_Id int,
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime
)
 AS
begin
	set nocount on;
	select COUNT(*) as CS from TA_Tbl_Permission 
	where Employee_Id =@Employee_Id And IsDeleted=0 And Permission_Date=@PermissionDate and Permission_Status !=''Rejected''
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForProcessing]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForProcessing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckPermissionForProcessing
Created By		:	Kumuthini.L
Created On		:	16-Sep-08
Description		:	Used to get approved permission details for particular Employee and Date
*/
CREATE   PROCEDURE [dbo].[Proc_TA_CheckPermissionForProcessing]
(
	@SwipeCardNo nvarchar(25),
	@Date nvarchar(15)
)
AS
begin
SET NOCOUNT ON;
	SELECT P.Permission_FromTime,P.Permission_ToTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo=@SwipeCardNo AND P.Permission_Date = @Date AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry_OD]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : 
Proc_TA_CheckPermissionForManualEntry_OD  ''595436'',''02/15/2014'',''12:15:00 AM'',''02/15/2014'',''02:31:00 AM'' 
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Kumuthini.L    
Created On : 02-Sep-2008  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_OD]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)    
AS  
	BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel int  
	DECLARE @InDateTime datetime
	DECLARE @OutDateTime datetime
	SET @Isdel=0 
	SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
	SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
	Declare @PermissionFromTime datetime
	Declare @PermissionToTime datetime
	
	SELECT @PermissionFromTime=Permission_FromTime,@PermissionToTime=Permission_ToTime FROM TA_Tbl_Permission P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE  P.IsDeleted = @Isdel AND E.Employee_Code_Id = @EmpCode and
	(((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) 
	AND Cast(@OutDateTime as DateTime))) and P.Permission_Status != ''Rejected''
	
	 if	(
			(@PermissionFromTime>=CONVERT(datetime,cast(@InDateTime as datetime),114) and @PermissionFromTime<=CONVERT(datetime,cast(@InDateTime as datetime),114)) 
			or 
			(@PermissionToTime>=CONVERT(datetime,cast(@OutDateTime as datetime),114) and @PermissionToTime<=CONVERT(datetime,cast(@OutDateTime as datetime),114))
		)
		begin
			select 1 as ManualEntry		
		end
	else if	(
			@PermissionFromTime=CONVERT(datetime,cast(@InDateTime as datetime),114) 
			or 
			@PermissionToTime=CONVERT(datetime,cast(@InDateTime as datetime),114)
		)
		begin
			select 0 as ManualEntry		
		end
	else if	(
			@PermissionFromTime=CONVERT(datetime,cast(@OutDateTime as datetime),114) 
			or 
			@PermissionToTime=CONVERT(datetime,cast(@OutDateTime as datetime),114)
		)
		begin
			select 0 as ManualEntry			
		end
	else
		begin
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
			WHERE  P.IsDeleted = @Isdel AND E.Employee_Code_Id = @EmpCode AND
			((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) 
			AND (P.Permission_ToTime)))) and P.Permission_Status != ''Rejected''
		end
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckPermissionForManualEntry_Group
Description : Checking whether the Permission is within the Manual Time Entry for a group of employees  
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Sashma.S    
Created On : 02-May-2011  
Modified By		:  Manjula.P  
Modified On		:  18-Feb-2014
Descriptinos	:	To avoid could not find prepared statement with handle 0  error : handle EXEC sp_xml_preparedocument @Index OUTPUT, @xml
				:	and  Exec sp_xml_removedocument @Index for all if constions
Proc_TA_CheckPermissionForManualEntry_Group ''2014/01/03'',''09:00 AM'',''2014/01/03'',''06:00 PM'' ,''<NewDataSet>
  <Table>
    <EmpID>46</EmpID>
    <EmployeeId>26</EmployeeId>
    <EmployeeName>Manjula P  Valparai Door No Fifty Five </EmployeeName>
    <LoginEmployeeId>1</LoginEmployeeId>
  </Table>
</NewDataSet>'' 
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry_Group]
(
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25),
	@xml xml
)  
AS  
	Begin
	SET NOCOUNT ON;
	DECLARE @Isdel int  
	DECLARE @InDateTime VARCHAR(50)  
	DECLARE @OutDateTime VARCHAR(50)  
	SET @Isdel=0  
	Declare @Index int
	Set @Index = 0;
		IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')  
		BEGIN  
		 SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		 SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_Permission P  
		 INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId Bigint ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmpID = P.Employee_Id  
		 WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = @Isdel AND   
		 ((P.Permission_FromTime) <= Cast(@InDateTime as DateTime) AND (P.Permission_ToTime) > Cast(@InDateTime as DateTime))  
		 Exec sp_xml_removedocument @Index
		END  
		ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')  
		   BEGIN  
		  SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
		  --Added by MAnjula.P on 18-Feb-2014   
		  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  --*************************************
		  SELECT xm.EmpID as EmployeeAutoId FROM TA_Tbl_Permission P  
		  INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId Bigint ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmpID = P.Employee_Id   
		  WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = @Isdel AND   
		  ((P.Permission_FromTime) < Cast(@OutDateTime as DateTime) AND (P.Permission_ToTime) >= Cast(@OutDateTime as DateTime))
		  --Added by MAnjula.P on 18-Feb-2014     
		  Exec sp_xml_removedocument @Index
		  --*************************
		   END  
		ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
		   BEGIN  
			  SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
			  SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime
			  --Added by MAnjula.P on 18-Feb-2014  
			  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
			  --************************************8
			  --select * from OpenXML(@Index, ''/NewDataSet/Table'')
			  SELECT ISNULL(xm.EmpID,0) as EmployeeAutoId FROM TA_Tbl_Permission P  
			  INNER JOIN  OpenXML(@Index, ''/NewDataSet/Table'') With (EmployeeId Bigint ''EmployeeId'',EmpID Bigint ''EmpID'') as xm on xm.EmpID = P.Employee_Id  			  WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = @Isdel AND  
			  ((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			  ((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND (P.Permission_ToTime))))   
			  --Added by MAnjula.P on 18-Feb-2014  
			  Exec sp_xml_removedocument @Index
			  --************************************
		   END  
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionForManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionForManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckPermissionForManualEntry  ''1001'',''9/03/2008'',''10:06:45 AM'','''',''''  
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Kumuthini.L    
Created On : 02-Sep-2008  
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionForManualEntry](
	@EmpCode varchar(10),
	@ManualInDate varchar(15),
	@ManualInTime varchar(25),
	@ManualOutDate varchar(15),
	@ManualOutTime varchar(25)
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @InDateTime VARCHAR(50)  
	DECLARE @OutDateTime VARCHAR(50)  
	IF(@ManualInDate <> '' ''  and @ManualInTime <> '' '' and @ManualOutDate = '' '' and @ManualOutTime = '' '')  
	   BEGIN  
		 SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
		 SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
		 INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
		 WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND   
		 ((P.Permission_FromTime) <= Cast(@InDateTime as DateTime) AND (P.Permission_ToTime) > Cast(@InDateTime as DateTime))  
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate = '' ''  and @ManualInTime = '' '')  
	   BEGIN  
		  SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
		  SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
		  INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
		  WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
		  ((P.Permission_FromTime) < Cast(@OutDateTime as DateTime) AND (P.Permission_ToTime) >= Cast(@OutDateTime as DateTime))   
	   END  
	ELSE IF (@ManualOutDate <> '' '' and @ManualOutTime <> '' '' and @ManualInDate <> '' '' and @ManualInTime <> '' '')  
	   BEGIN  
			SET @InDateTime = @ManualInDate + '' '' + @ManualInTime  
			SET @OutDateTime = @ManualOutDate + '' '' + @ManualOutTime  
			SELECT COUNT(*) as ManualEntry FROM TA_Tbl_Permission P  
			INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
			WHERE P.Permission_Status = ''Approved'' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
			((((P.Permission_FromTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime)) OR ((P.Permission_ToTime) BETWEEN Cast(@InDateTime as DateTime) AND Cast(@OutDateTime as DateTime))) OR   
			((Cast(@InDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND(P.Permission_ToTime)) Or (Cast(@OutDateTime as DateTime) BETWEEN (P.Permission_FromTime) AND (P.Permission_ToTime))))   
	   END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckPermissionBeforeAfterWithLeave ''02/19/2008'',''02/20/2008'',''PermissionOnLeave'',5
Description		:	Check Leave Count for Before or After Permission Dates
Tables Included	:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	14-Feb-08
Modified By		:	Thilakraj On : 14-Oct-2013
Modified On		:	
*/
/*
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] ''04/01/2008'',''04/01/2008'',''PermissionAfterLeave'',''1221''
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] ''04/01/2008'',''04/01/2008'',''PermissionBeforeLeave'',''1221''
Exec [Proc_TA_CheckPermissionBeforeAfterWithLeave] ''04/01/2013'',''04/01/2013'',''PermissionOnLeave'',''1221''
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermissionBeforeAfterWithLeave] 
	@PermissionFromDate datetime,
	@PermissionToDate datetime,
	@PermissionType nvarchar(50),
	@EmployeeId int,
	@ShiftDate datetime
as
BEGIN
	SET NOCOUNT ON;
	if(@PermissionType=''PermissionBeforeLeave'')
		BEGIN
			select * from ta_tbl_leaveApplication
			where Leave_FromDate=DATEADD( day ,1,@PermissionToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>''Rejected''
		END
	else if(@PermissionType=''PermissionAfterLeave'')
		BEGIN
			select * from ta_tbl_leaveApplication
			where Leave_ToDate=DATEADD( day ,-1,@PermissionFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>''Rejected''
		END 
	else if(@PermissionType=''PermissionOnLeave'')
		BEGIN
			select * from ta_tbl_leaveApplication
			where ((@ShiftDate between Leave_FromDate and Leave_ToDate) or (@ShiftDate between Leave_FromDate and Leave_ToDate)) 
			and Employee_Id=@EmployeeId and Isdeleted=0 and Status<>''Rejected''
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPassword]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPassword]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckPassword  
Description : check password validation  
Tables Included : TA_Tbl_Employee  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckPassword]
(
@username NVARCHAR(10),
@password NVARCHAR(50)
)
AS
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	SELECT Count(UserName)as UID FROM TA_Tbl_Employee WHERE Employee_Id=@username AND Emp_password=@password 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPageExistsInLicense]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPageExistsInLicense]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
/*
Modified By : Mani  and Thilak
Modified Date : 26-Nov-2013
Reason : Need to check the demo and Express Version
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPageExistsInLicense](@PageID int)
AS
BEGIN
	SET NOCOUNT ON;
    if exists( Select * from TA_Tbl_Demo Where DemoType in (''Standard'',''Express''))
		Begin
		   SELECT COUNT(*) as ExistCount from TA_Tbl_Page where pageId = @PageID and pageId not in (20,24,25,69,96,97,98,108,110,133,174,228) 
		End    
    Else
	    Begin
			SELECT COUNT(*) as ExistCount from TA_Tbl_Page where pageId = @PageID
		End   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckOtType]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_CheckOtType]
	@OtType as varchar(25),
	@OtValue as varchar(25),
	@CompanyID as int,
	@OtTypeID as int,
	@opr as varchar(1)
AS
BEGIN	
	if (@opr=''I'')
		Begin
			select count(*) as RecCount from TA_Tbl_OtType
				where (OtType=@OtType or
				OtValue=@OtValue) and 
				CompanyID = @CompanyID 
				--and isdeleted=0				
		End
	Else
		Begin
				select count(*) as RecCount from TA_Tbl_OtType
				where 
					(OtType=@OtType or
				OtValue=@OtValue) and
				CompanyID = @CompanyID and
				OtTypeID!=@OtTypeID --and
				--isdeleted=0
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveOnSameDay]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveOnSameDay]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveOnSameDay]
	-- Add the parameters for the stored procedure here
	@EmployeeId INT,
	@LeaveFromDate datetime,
	@LeaveToDate datetime
	AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_Permission where IsDeleted=0 and Permission_Status <> ''Rejected'' and Permission_Date between @LeaveFromDate and @LeaveToDate
	and Employee_Id=@EmployeeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType_LeaveApp]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveType_LeaveApp]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeaveType_LeaveApp  
Description : Check for  Leave type mapping in Leave application  
Tables Included : TA_Tbl_LeaveApplication  
Created By : Arun Vinoth.T  
Created On : 12 Aug 07  
Modified By :  
Modified On :
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveType_LeaveApp] 
@LeaveTypeId INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT COUNT(LeaveType_Id) as LType  FROM TA_Tbl_LeaveApplication WHERE LeaveType_Id=@LeaveTypeId and IsDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016>
-- Description:	<Checking whether permission applied during the shift start time>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingPermissionAvailedDuringShiftStartTime]
	@gintShiftId int,
	@Shift_StartTime varchar(50),
	@Permission_FromTime varchar(50),
	@Permission_ToTime varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_Id = @gintShiftId AND CONVERT(DATETIME,@Shift_StartTime) 
	BETWEEN @Permission_FromTime AND @Permission_ToTime
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData3]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) AS InDateTime,Clk_OutDate,''F'' as Type 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND (Clk_InDate+Clk_Intime) = (SELECT MAX(Clk_InDate+Clk_InTime) 
	FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId AND (clk_indate+Clk_intime) < CAST(@strDateTime AS DateTime) AND Clk_OutDate IS NULL and IsVoid = 0)
	UNION 
	SELECT Clk_id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) AS InDateTime,Clk_OutDate,''S'' as Type FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inClk_EmpId AND (Clk_Indate+Clk_Intime) = (SELECT MIN(Clk_InDate+Clk_InTime) FROM TA_Tbl_ClockDetails WHERE clk_empid = @inClk_EmpId and IsVoid = 0 
	AND (Clk_Indate+Clk_Intime) > CAST(@strDateTime AS DateTime))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData2]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Clk_Id,CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) as InDateTime from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) = 
	(select MIN(CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108))) from TA_Tbl_Clockdetails
	where Clk_EmpId = @inClk_EmpId 
	AND CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) > CAST(@strDateTime AS DateTime) 
	AND IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) and Clk_EmpId =@inClk_EmpId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData1]
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select Clk_Id,(Clk_OutDate+Clk_OutTime) as PunchDateTime,''Out'' as Type from TA_Tbl_Clockdetails where (Clk_OutDate+Clk_OutTime) = 
	(select MAX(Clk_OutDate+Clk_OutTime) from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) < Cast(@strDateTime as DateTime)
	and Clk_EmpId = @inClk_EmpId and IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) 
	and Clk_EmpId = @inClk_EmpId 
	UNION 
	select Clk_Id,(Clk_InDate+Clk_InTime) as PunchDateTime,''In'' as Type from TA_Tbl_Clockdetails where (Clk_InDate+Clk_InTime)=
	(select MIN(Clk_InDate+Clk_InTime) from TA_Tbl_Clockdetails 
	where CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) > Cast(@strDateTime as DateTime)
	and Clk_EmpId = @inClk_EmpId and IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)) and Clk_EmpId =@inClk_EmpId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking in and Out time Lies Between any Existing Data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingInAndOutTimeLiesBwAnyExistingData]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(50),
	@strDateTime varchar(50),
	@gstrClockDate varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_Id FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
	AND (CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_InDate,101),1,10) + '' '' + convert(char(10), Clk_InTime, 108)) <= Cast(@strDateTime as DateTime)) 
	AND (CONVERT(DATETIME,SUBSTRING(CONVERT(VARCHAR(10),Clk_OutDate,101),1,10) + '' '' + convert(char(10), Clk_OutTime, 108)) >= Cast(@strDateTime as DateTime)) 
	AND IsVoid = 0 AND Clk_Date = cast(@gstrClockDate as datetime)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingIgnorePunches]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingIgnorePunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	 Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for both IN & OUT Punches                          
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingIgnorePunches]
	-- Add the parameters for the stored procedure here
	@Clk_CardId varchar(50),
	@Clk_Date varchar(20),
	@Clk_Time varchar(10),
	@PunchInterval varchar(10),
	@ClockDate varchar(20),
	@DataFrom char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@DataFrom=''FS'')
	begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND ((@Clk_Time BETWEEN Clk_InTime AND Clk_InTime + @PunchInterval)
		OR (@Clk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @PunchInterval))
		AND Clk_Date=@ClockDate
    end
    else if(@DataFrom=''FKI'')
    begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND (@Clk_Time BETWEEN Clk_InTime AND Clk_InTime + @PunchInterval)
		AND Clk_Date=@ClockDate
	end
	else if(@DataFrom=''FKO'')
	begin
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @Clk_CardId
		AND Clk_InDate=@Clk_Date
		AND (@Clk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @PunchInterval)
		AND Clk_Date=@ClockDate                           
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<CheckingEmployeeRecordAvailedForParticularDate>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingEmployeeRecordAvailedForParticularDate]
	@inClk_EmpId varchar(50),
	@InReaderID varchar(50),
	@InDate varchar(20),
	@InTime varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''I'')
	begin
		Select Clk_EmpId from TA_Tbl_ClockDetails where Clk_EmpId = @inClk_EmpId
		and Clk_InDeviceId =(select Terminal_ReaderID from ta_tbl_terminal where Terminal_Id= @InReaderID) 
		and Clk_InDate = cast(@InDate as datetime) and clk_InTime = cast(@InTime as datetime) 
	end
	if(@Type=''O'')
	begin
		Select Clk_EmpId from TA_Tbl_ClockDetails where Clk_EmpId = @inClk_EmpId
		and Clk_OutDeviceId =(select Terminal_ReaderID from ta_tbl_terminal where Terminal_Id= @InReaderID) 
		and Clk_OutDate =cast(@InDate as datetime)  and clk_OutTime=cast(@InTime as datetime)	
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Checking Employee Availed In Clock Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingEmployeeAvailedInClockDetails]
	@inClk_EmpId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	Select Clk_EmpId from TA_Tbl_ClockDetails WHERE Clk_EmpId =@inClk_EmpId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveSanctioningPerson]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveSanctioningPerson]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:	K. Gopinath
-- Create date: 13-Jun-2014
-- Description:	for getting Approval authority for OD application
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveSanctioningPerson]
	@EmpID as int
AS
BEGIN
	SET NOCOUNT ON;
	Select Leave_Sanc_Authority from ta_tbl_employee where Employee_ID=@EmpID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavepolicyName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavepolicyName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : Proc_TA_CheckLeavePolicy    
Description : check leave policy before insert, is already there or not    
Tables Included : TA_Tbl_Emp_LeavePolicy    
Created By : Arun Vinoth.T    
Created On : 14-Aug-2007    
Modified By :    
Modified On :  */  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeavepolicyName](@PolicyName varchar(50))
AS
begin
	SET NOCOUNT ON;
	SELECT COUNT(*) FROM TA_Tbl_LeavePolicy WHERE PolicyName=@PolicyName --and IsDeleted=0
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEmployeePFESI]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEmployeePFESI]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckEmployeePFESI  
Description : Select PF Eligible, ESI Eligible for an Employee for a given Swipe Card No.
Tables Included : TA_Tbl_Employee  
Created By : Kumuthini.L
Created On : 22-Apr-2008
Modified By : 
Modified On :
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckEmployeePFESI] 
(
   @SwipeCardNo NVARCHAR(10)
)
AS
     SELECT PF_Eligible,ESI_Eligible  FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND IsDeleted = 0
     AND SwipeCardNo = @SwipeCardNo
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_checkDuplicationUsergroup]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_checkDuplicationUsergroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_checkDuplicationUsergroup  
Description : Checking for duplication of usergroup 
Tables Included : ta_tbl_usergroup  
Created By : Senthil  
Created On : 13-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_checkDuplicationUsergroup]
	(
		@groupName nvarchar(100)
	)
AS
BEGIN
		select groupName  as recCount from ta_tbl_usergroup where groupName=@groupName and isdeleted !=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAttandanceCode]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_CheckAttandanceCode 2,1,''present'',3,''U''
CREATE PROCEDURE [dbo].[Proc_TA_CheckAttandanceCode]
	@AttandanceID as int,
	@AttandanceCode as varchar(25),
	@AttandanceValue as varchar(25),
	@CompanyID as int,
	@opr as varchar(1)
AS
BEGIN
	if (@opr=''I'')
		Begin
			select count(*) as RecCount from TA_Tbl_AttandanceCode  where 
			(AttandanceCode=@AttandanceCode or AttandanceValue=@AttandanceValue) and
			CompanyID=@CompanyID 
		End
	else
		Begin
			--declare @AttCode varchar(25)
			--declare @AttValue varchar(25)
			--declare @CompID int
			--select @AttCode=AttandanceCode,@AttValue=AttandanceValue,@CompID=CompanyID
			--from TA_Tbl_AttandanceCode where AttandanceID=@AttandanceID
			----select @AttCode,@AttValue,@CompID
			select count(*) as RecCount from TA_Tbl_AttandanceCode  where 
			(AttandanceCode=@AttandanceCode or AttandanceValue=@AttandanceValue) and	CompanyID=@CompanyID and AttandanceID!=@AttandanceID
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckExactDuplicateRecordExists]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckExactDuplicateRecordExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 11.59 AM>
-- Description:	<Checking Exact record already exists>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckExactDuplicateRecordExists]
	-- Add the parameters for the stored procedure here
	@Clk_Date datetime,
	@Clk_Time datetime,
	@Clk_CardId varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Count(*) AS Count FROM TA_Tbl_ClockDetails WHERE ((Clk_OutDate = @Clk_Date AND Clk_OutTime = @Clk_Time) or (Clk_InDate = @Clk_Date AND Clk_InTime = @Clk_Time)) 
	AND Clk_EmpId = @Clk_CardId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntranceMap]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntranceMap]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_CheckEntranceMap]
(
@Entrance NVARCHAR(50)
)
AS
BEGIN
	SELECT COUNT (TerMap_Id) AS TID FROM TA_Tbl_TerminalMapping WHERE EntranceName=@Entrance AND IsDeleted=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Insert]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckEntrance_Insert
Description	:	Checking the entrance name already exists in the same level
Tables Included	:	ta_tbl_entrance
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:  R.Manikandan
Modified On	:23-11-2016	12.43
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Insert]    
(  
	@EntranceName as nvarchar(50),
	@OrgLevel as int
) 
AS   
 BEGIN    
   SET NOCOUNT ON
   Select Count(Entrance_Name) AS EntranceNameCount from TA_Tbl_entrance WHERE Entrance_Name=@EntranceName AND OrgLevel_Id = @OrgLevel
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHalfDayLeave]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHalfDayLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Created by	:	Prabakaran.P
-- Created on	:	15-Mar-08
-- Description	:	Procedure to check the Half Day Leaves exist or not
-- Proc_TA_CheckHalfDayLeave 1224,''10/02/2013'',''10/04/2013'',''First half'',''First half''
CREATE PROCEDURE [dbo].[Proc_TA_CheckHalfDayLeave]
(
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@SessionFrom nvarchar(50),
	@SessionTo nvarchar(50)
)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @diff int
	declare @i int
	declare @fromdate datetime
	declare @Todate datetime
	declare @fromsession varchar(20)
	declare @tosession varchar(20)
	declare @count int	
	set @count=0	
	set @i=0
	set @fromdate=@Leave_FromDate 
	set @Todate=@Leave_ToDate	
	set @diff=(select DATEDIFF(d,@Leave_FromDate,@Leave_ToDate))	
	if(@diff=0)
		begin
			if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
				And(Leave_FromDate=@Leave_FromDate) and Status<>''Rejected'')>0)
					begin						
						if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
							And(Leave_FromDate=@Leave_FromDate) and Status<>''Rejected'')=1)
								begin								 
									select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
									And(Leave_FromDate=@Leave_FromDate) and Status<>''Rejected''
									if @fromsession=@SessionFrom
										begin
											set @count=@count+1
										end
									if @tosession=@SessionTo
										begin
											set @count=@count+1
										end
								end
						else
							begin
								set @count=@count+1
							end
					end
		end
	else
		begin
			while @i<=@diff 
				begin
					if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
				And(Leave_FromDate=@fromdate) and Status<>''Rejected'')>0)
					begin
						if((select COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
							And(Leave_FromDate=@fromdate) and Status<>''Rejected'')=1)
								begin
									if(@fromdate=@Todate)
										begin									
											select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
											And(Leave_FromDate=@fromdate) and Status<>''Rejected''									
											if @fromsession=''First half'' and @tosession=''First half''
												begin
													if(@SessionTo=''Second half'' or @SessionTo=''First half'')
														begin
															set @count=@count+1
														end
												end
											if @fromsession=''Second half'' and @tosession=''Second half''
												begin
													if(@SessionTo=''Second half'')
														begin
															set @count=@count+1
														end
												end
											if @fromsession=''First half'' and @tosession=''Second half''
												begin
													if(@SessionTo=''Second half'' or @SessionTo=''First half'')
														begin
															set @count=@count+1
														end
												end
										end
									else if(@fromdate=@Leave_FromDate)
										begin											
											select @fromsession=[Leave_SessionFrom],@tosession=[Leave_SessionTo] from TA_Tbl_LeaveApplicationExists where Employee_Id =@Employee_Id And IsDeleted=0 
											And(Leave_FromDate=@fromdate) and Status<>''Rejected''																										if @fromsession=''First half'' and @tosession=''First half''
												begin
													if(@SessionFrom=''First half'')
														begin
															set @count=@count+1
														end
												end
											if @fromsession=''Second half'' and @tosession=''Second half''
												begin
													if(@SessionTo=''Second half'' or @SessionTo=''First half'')
														begin
															set @count=@count+1
														end
												end
											if @fromsession=''First half'' and @tosession=''Second half''
												begin
													if(@SessionTo=''Second half'' or @SessionTo=''First half'')
														begin
															set @count=@count+1
														end
												end
										end
									else
										begin
											set @count=@count+1											
										end
								end
						else
							begin
								set @count=@count+1
							end
					end					
					set @fromdate=DATEADD(d,1,@fromdate)					
					set @i=@i+1	
				end
		end
		select @count as CS
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeStandard]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeStandard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckGradeStandard 
Description : check grade name before insert, is already there  
Tables Included : Ta_Tbl_Grade  
Created By : Arun Vinoth.T  
Created On : 21-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeStandard]      
AS      
BEGIN      
declare @RecordCount as int
set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name=''StandardGradeDefault'' and Grade_Level=1 and IsDeleted=0)    
if(@RecordCount=0)
	begin
		insert into Ta_Tbl_Grade (Grade_Name,Grade_Level,Emp_ID,Isdeleted)
		values (''StandardGradeDefault'',''1'',''1'',''0'')
	end
END      
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGradeName_Update]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGradeName_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name : Proc_TA_CheckGradeName_Update   
Description : check grade name before update, is already there    
Tables Included : Ta_Tbl_Grade    
Created By : Arun Vinoth.T    
Created On : 21-Aug-2007  
Modified By :
Modified On : 
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckGradeName_Update]    
(    
	@GradeId int
)     
AS    
	Declare @Isdel int    
	declare @sql as nvarchar(3000)
	declare @Grade_Name NVARCHAR(50)         
	SET @Isdel=0    
BEGIN
	Select @Grade_Name=grade_name from TA_Tbl_Grade where Grade_ID=@GradeId 
	set @sql = ''SELECT COUNT(Grade_Name) AS GradeNameCount FROM Ta_Tbl_Grade WHERE Grade_Name=N''''''+@Grade_Name+'''''' AND Grade_ID<>''+cast(@GradeId as	nvarchar(250))+'' ''
	exec(@sql)    
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGEOLocationUtilization]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGEOLocationUtilization]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-Aug-2020 10:21 AM,,>
-- Description:	<Which is used to check whether geo location was utilized for any one person or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckGEOLocationUtilization]
	@LandMarkID bigint
AS
BEGIN	
	SET NOCOUNT ON;
	select LocationId from TA_tbl_ShiftAdd_Location where LocationId=@LandMarkID	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForwardingPerson]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForwardingPerson]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:	K. Gopinath
-- Create date: 13-Jun-2014
-- Description:	for getting FOrwarding authority for OD application
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForwardingPerson]
	@EmpID as int
AS
BEGIN
	SET NOCOUNT ON;
	Select Reporting_TO from ta_tbl_employee where Employee_ID=@EmpID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForProcessing]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForProcessing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckLeaveForProcessing
Created By		:	Kumuthini.L
Created On		:	16-Sep-08
Description		:	Used to get approved leave details for particular Employee and Date
*/
CREATE   PROCEDURE [dbo].[Proc_TA_CheckLeaveForProcessing]
(
	@SwipeCardNo nvarchar(25),
	@Date nvarchar(15)
)
AS
begin
SET NOCOUNT ON;
SELECT LA.Employee_Id,LA.Leave_SessionFrom,LA.Leave_SessionTo FROM TA_Tbl_LeaveApplication LA,TA_Tbl_Employee E WHERE E.SwipeCardNo = @SwipeCardNo AND Leave_FromDate >= @Date AND Leave_ToDate <= @Date AND LA.Employee_Id = E.Employee_Id AND LA.Leave_SessionFrom = LA.Leave_SessionTo AND LA.Status = ''Approved'' AND LA.IsDeleted = 0
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForOnDuty]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForOnDuty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 12-02-2014
-- Description:	Check for leave entry sessions available to particular employee
--	Modified By		:	Manjula.P
--	Modified On		:	17-Feb-2014
--	Descriptinos	:	Changing @EmployeeCodeId datatype from int to varchar(50) to avoid error conversion failed server error  :0021751(timecheckV1.4)	 
--	Proc_TA_CheckLeaveForOnDuty ''11/01/2016'',''100''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForOnDuty]
	@Date Varchar(15),
	@EmployeeCodeId varchar(50)
AS
BEGIN	
	SET NOCOUNT ON;
	IF((SELECT COUNT(*) from TA_Tbl_LeaveApplicationExists L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0 
	And(L.Leave_FromDate=@Date) and L.Status<>''Rejected'')>0)
		BEGIN
			IF((SELECT COUNT(*) from TA_Tbl_LeaveApplicationExists  L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0
			And(L.Leave_FromDate=@Date) and L.Status<>''Rejected'')=1)
				BEGIN																
					SELECT L.Leave_SessionFrom,L.Leave_SessionTo from TA_Tbl_LeaveApplicationExists L INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id where E.Employee_Code_Id =@EmployeeCodeId And L.IsDeleted=0
					And(L.Leave_FromDate=@Date) and L.Status<>''Rejected''					
				END
			ELSE
				BEGIN
					SELECT ''First half'' as Leave_SessionFrom,''Second half'' as Leave_SessionTo
				END
		END
	else
		begin
			SELECT ''NoLeave'' as Leave_SessionFrom,''NoLeave'' as Leave_SessionTo
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForManualEntry_OD]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : Proc_TA_CheckLeaveForManualEntry_OD  ''ot2'',''9/03/2012'',''9/03/2012''
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Gopinath.k   
Created On : 03-Feb-2014
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry_OD]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15)
)
AS
BEGIN  	
	SET NOCOUNT ON;
	SELECT COUNT(*) as ManualEntry FROM TA_Tbl_LeaveApplication P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND 
	((Cast(@ManualInDate as DateTime) between P.Leave_FromDate and P.Leave_ToDate))
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForManualEntry]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : Proc_TA_CheckLeaveForManualEntry  ''ot2'',''9/03/2012'',''9/03/2012''
Description : Checking whether the Permission is within the Manual Time Entry   
Tables Included : TA_Tbl_Permission, TA_Tbl_Employee    
Created By : Gopinath.k   
Created On : 03-Feb-2014
Modified By :    
Modified On :    
*/    
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForManualEntry]
(
	@EmpCode varchar(10),
	@ManualInDate varchar(15)
)
AS
BEGIN  	
	SET NOCOUNT ON;
	SELECT COUNT(*) as ManualEntry FROM TA_Tbl_LeaveApplication P  
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Id = P.Employee_Id  
	WHERE P.Status = ''Approved'' AND P.IsDeleted = 0 AND E.Employee_Code_Id = @EmpCode AND  
	((Cast(@ManualInDate as DateTime) between P.Leave_FromDate and P.Leave_ToDate))
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveForGivenDate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveForGivenDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	: Proc_TA_CheckLeaveForGivenDate  
Description		: check leave for given date 
Tables Included              : TA_Tbl_LeaveApplication, TA_Tbl_Employee  
Created By		: Prabakaran.P  
Created On		: 14-Aug-2007
Modified By		:  
Modified On		:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveForGivenDate] 
(
   @SwipeCardNo Varchar(15),
   @Date DateTime
)
AS
begin
SET NOCOUNT ON;
SELECT la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate FROM TA_Tbl_LeaveApplication la,TA_Tbl_Employee emp WHERE la.Employee_Id = emp.Employee_Id AND emp.SwipeCardNo = @SwipeCardNo AND la.Leave_FromDate <= @Date AND la.Leave_ToDate >= @Date AND la.Status = ''Approved'' AND la.IsDeleted = 0
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name  : Proc_TA_CheckLeaveExistsBeforeBorrow ''06/09/2008 12:00:00 AM'',''06/10/2008 12:00:00 AM'',2    
Description  : Check normal Leave Exists Before Borrow leave    
Tables Included  : TA_Tbl_LeaveApplication    
Created By  : Prabakaran    
Created On  : 10-Sep-08    
Modified By  :     
Modified On  :     
*/    
CREATE  PROCEDURE [dbo].[Proc_TA_CheckLeaveExistsBeforeBorrow]     
@LeaveFromDate datetime,    
@LeaveToDate datetime,   
@LeaveTypeId int,   
@EmployeeId int    
as    
declare @Count as int    
SET NOCOUNT ON;
-- Check normal Leave Exists Before Borrow leave    
 BEGIN    
  set @Count=(select count(LeaveApplication_Id) from TA_Tbl_LeaveApplication la  
inner join TA_Tbl_YearSetting ys on  ys.YearSettings_Id=la.YearSettings_Id  
  where   
--(Leave_FromDate < @LeaveFromDate or Leave_FromDate < @LeaveToDate or Leave_ToDate < @LeaveFromDate or Leave_ToDate < @LeaveToDate)   and   
la.Employee_Id=@EmployeeId and la.Isdeleted=0 and la.Type=''Leave''  
and la.LeaveType_Id=@LeaveTypeId  
  and la.Status in(''Pending'',''Forwarded'') and la.IsBorrow=0 and ys.IsActive=1)    
  select @Count as LeaveCount    
 END     
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckLeaveBeforeAfterWithPermission ''02/19/2008'',''02/20/2008'',''LeaveOnPermission'',5
Description		:	Check Permission Count for Before or After Leave Dates
Tables Included	:	TA_Tbl_Permission
Created By		:	Kumuthini.L
Created On		:	05-Sep-08
Modified By		:	Sasireka.M
Modified On		:	25.04.09
*/
-- [Proc_TA_CheckLeaveBeforeAfterWithPermission] ''09/17/2008'',''09/17/2008'',''LeaveAfterPermission'',''152''
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveBeforeAfterWithPermission]
@LeaveFromDate datetime,
@LeaveToDate datetime,
@LeaveType nvarchar(50),
@EmployeeId int
as
BEGIN
SET NOCOUNT ON;
	declare @Count as int
	if(@LeaveType=''LeaveBeforePermission'')
	-- Check Leave falls Before Permission
		BEGIN
			select * from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,1,@LeaveToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END
	else if(@LeaveType=''LeaveAfterPermission'')
	-- Check Leave falls After Permission
		BEGIN
			select * from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,-1,@LeaveFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END 
	else if(@LeaveType=''LeaveOnPermission'')
	-- Check Leave and Permission on same day
		BEGIN
			select * from TA_Tbl_Permission
			where (Permission_Date between  @LeaveFromDate and @LeaveToDate)
			and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationUpdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeaveApplicationUpdate  
Description : check leave application before update, is already there or not 
Tables Included : TA_Tbl_LeaveApplication  
Created By : Prabakaran.P  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationUpdate](@LID int,@Employee_Id int,@Leave_FromDate datetime,@Leave_ToDate datetime)
 AS
	begin
		SET NOCOUNT ON;
		select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id =@Employee_Id and LeaveApplication_Id<>@LID  And IsDeleted=0 And (( Leave_FromDate  between @Leave_FromDate And @Leave_ToDate) or (Leave_ToDate between @Leave_FromDate And @Leave_ToDate))
	end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeaveApplicationRestrictedHolidays    
Description : check leave application on restricted holidays   
Tables Included : TA_Tbl_LeaveApplication    
Created By : Prabakaran.P    
Created On : 14-Aug-2007  
Modified By :    
Modified On :  
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationRestrictedHolidays](@Employee_Id int,@HolidayId int)
AS
BEGIN
	SET NOCOUNT ON;
	select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id =@Employee_Id And IsDeleted=0 And 
	LeaveType_Id=@HolidayId and Type=''Restricted Holiday'' and Status<>''Rejected''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By		:	A.K.T.MOORTHI
-- Modified Date	:	02-07-2013
-- Description		:	Change The Query
-- Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat -1, 396, ''5/Jul/2013'', ''5/Jul/2013'', ''First Half'', ''First Half''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplicationAlreadyExistsOnSat]
	@leaveApplicationId int,
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@SessionFrom nvarchar(50),
	@SessionTo nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @intCount as int
	set @intCount=0
	if(@leaveApplicationId=-1)
		BEGIN
			SELECT 
				@intCount = CASE WHEN Leave_FromDate = @Leave_FromDate AND Leave_ToDate = @Leave_ToDate THEN 0 ELSE COUNT(LeaveApplication_Id) END from TA_Tbl_LeaveApplication 
			WHERE Employee_Id = @Employee_Id AND IsDeleted = 0 AND [Status] <> ''Rejected'' AND
				Leave_FromDate = @Leave_FromDate and Leave_ToDate = @Leave_ToDate
			GROUP BY Leave_FromDate, Leave_ToDate
		end
	select @intCount as CS
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplication_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckLeaveApplication  
Description : Angler Timecheck
Tables Included : TA_Tbl_LeaveApplication  
Created By : Karthikeyan  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
Proc_TA_CheckLeaveApplication -1,32,''01/20/2010'',''01/20/2010'',''Second Half'',''Second Half''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication_Angler]
(
@leaveApplicationId int,
@Employee_Id int,
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@SessionFrom nvarchar(50),
@SessionTo nvarchar(50)
)
 AS
begin
SET NOCOUNT ON;
declare @intCount as int
declare @intCount1 as int
declare @intCount2 as int
declare @intCount3 as int
declare @intCount4 as int
set @intCount=0
set @intCount1=0
set @intCount2=0
set @intCount3=0
set @intCount4=0
if(@leaveApplicationId=-1)
BEGIN
set @intCount = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected''
And
(
(@Leave_FromDate > Leave_FromDate and @Leave_FromDate<Leave_ToDate)
or
(@Leave_ToDate > Leave_FromDate and @Leave_ToDate<Leave_ToDate)
or
(Leave_FromDate > @Leave_FromDate and Leave_FromDate<@Leave_ToDate)
or
(Leave_ToDate > @Leave_FromDate and Leave_ToDate<@Leave_ToDate)
))
if(@intCount=0)
	begin
		set @intCount1 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected''
		And
		(
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount2 = (select COUNT(*) as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected''
		And
		(
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionTo)
		)
		)
		set @intCount3 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected''
		And
		(
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount4 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected''
		And
		(
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionTo)
		))
	end
else
	BEGIN
	select @intCount as CS
	END
if(@intCount1=0 and @intCount2=0 and @intCount3=0 and @intCount4=0)
BEGIN
select ''0'' as CS
END
else
BEGIN
select ''1'' as CS
END
END
ELSE
BEGIN
	set @intCount = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected'' and LeaveApplication_Id<>@leaveApplicationId
And
(
(@Leave_FromDate > Leave_FromDate and @Leave_FromDate<Leave_ToDate)
or
(@Leave_ToDate > Leave_FromDate and @Leave_ToDate<Leave_ToDate)
or
(Leave_FromDate > @Leave_FromDate and Leave_FromDate<@Leave_ToDate)
or
(Leave_ToDate > @Leave_FromDate and Leave_ToDate<@Leave_ToDate)
))
if(@intCount=0)
	begin
		set @intCount1 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected'' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_FromDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount2 = (select COUNT(*) as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected'' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_FromDate and Leave_SessionTo=@SessionTo)
		)
		)
		set @intCount3 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected'' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionFrom)
			or
			(Leave_FromDate=@Leave_ToDate and Leave_SessionFrom=@SessionTo)
		))
		set @intCount4 = (select COUNT(*)  as CS from TA_Tbl_LeaveApplication where Employee_Id=@Employee_Id And IsDeleted=0 and Status<>''Rejected'' and LeaveApplication_Id<>@leaveApplicationId
		And
		(
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionFrom)
			or
			(Leave_ToDate=@Leave_ToDate and Leave_SessionTo=@SessionTo)
		))
	end
else
	BEGIN
	select @intCount as CS
	END
if(@intCount1=0 and @intCount2=0 and @intCount3=0 and @intCount4=0)
BEGIN
select ''0'' as CS
END
else
BEGIN
select ''1'' as CS
END
END
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveApplication]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeaveApplication    
Description : check leave application is already there or not   
Tables Included : TA_Tbl_LeaveApplication    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By : Manikandan.R   
Modified On : 2012-Mar-03
*/  
--[Proc_TA_CheckLeaveApplication] 3,''2015-09-30'',''2016-09-30''

CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeaveApplication]
(
	@Employee_Id int,
	@Leave_FromDate datetime,
	@Leave_ToDate datetime,
	@LeaveType int
)
AS
BEGIN
	SET NOCOUNT ON;
	if exists(Select * from TA_Tbl_LeaveType where LeaveType_Id=@LeaveType and isnull(isWFH,0)=1)
		begin
			select COUNT(*)  as CS from TA_Tbl_LeaveApplication LA 
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			inner join TA_Tbl_LeaveApplicationExists LAE on LA.Employee_Id=LAE.Employee_Id and la.LeaveApplication_Id=lae.LeaveApplicationId where LA.Employee_Id =cast(@Employee_Id as nvarchar(5)) And LAE.IsDeleted=0 and LAE.Status<>''Rejected'' AND ((LAE.Leave_FromDate between(CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))   , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102))) or (LAE.Leave_ToDate between (CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))  , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102)))) and isnull(LT.isWFH,0)=1
		end
	else
		begin
			select COUNT(*)  as CS from TA_Tbl_LeaveApplication LA 
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LA.LeaveType_id
			inner join TA_Tbl_LeaveApplicationExists LAE on LA.Employee_Id=LAE.Employee_Id and la.LeaveApplication_Id=lae.LeaveApplicationId where LA.Employee_Id =cast(@Employee_Id as nvarchar(5)) And LAE.IsDeleted=0 and LAE.Status<>''Rejected'' AND ((LAE.Leave_FromDate between(CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))   , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102))) or (LAE.Leave_ToDate between (CONVERT(DATETIME, cast(@Leave_FromDate as nvarchar(50))  , 102)) and (CONVERT(DATETIME, cast(@Leave_ToDate as nvarchar(50)), 102)))) and isnull(LT.isWFH,0)=0
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Created Date	:	16-Dec-2013
-- Description	:	Check The Leave And Permission Exists When Deleted Date(Reg Bug No 0020677, 0020676).
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId=1,@FromDate=''2012/12/17'',@ToDate=''2013/12/31''
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId=''346, 345'',@FromDate=''12/24/2013'',@ToDate=''12/24/2013'',@Func=''SEC''
-- EXEC Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift @EmployeeId=''<DocumentElement><Table><EmployeeAutoID>346</EmployeeAutoID></Table></DocumentElement>'',@FromDate=''2013/12/19'',@ToDate=''2013/12/31'',@Func=''SRA''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpShift]
	@EmployeeId VARCHAR(MAX),
	@FromDate VARCHAR(25),
	@ToDate VARCHAR(25),
	@Func VARCHAR(5)
AS
BEGIN
	SET NOCOUNT ON;
	IF(@Func = ''SD'')
	BEGIN
		SELECT ''ShiftDelete_Check_Permission'' [Message] FROM TA_Tbl_Permission P		
		INNER JOIN TA_Tbl_TempShiftAllocation TSA ON TSA.EmpID = P.Employee_Id
		WHERE TSA.LoginEmployeeId = CAST(@EmployeeId AS BIGINT) AND P.Permission_Status = ''Approved'' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)
		UNION
		SELECT ''ShiftDelete_Check_Leave'' [Message] FROM TA_Tbl_LeaveApplication LA
		INNER JOIN TA_Tbl_TempShiftAllocation TSA ON TSA.EmpID = LA.Employee_Id
		WHERE TSA.LoginEmployeeId = CAST(@EmployeeId AS BIGINT) AND [Status] = ''Approved'' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)))
	END
	ELSE IF(@Func = ''SEC'')
	BEGIN
		DECLARE @Query VARCHAR(MAX)
		SET @Query = ''SELECT ''''ShiftExchange_Check_Permission'''' [Message] FROM TA_Tbl_Permission P		
			WHERE P.Employee_Id IN('' + @EmployeeId + '') AND P.Permission_Status = ''''Approved'''' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), '''''' + @FromDate + '''''', 102) AND CONVERT(VARCHAR(11), '''''' + @ToDate + '''''', 102)
			UNION
			SELECT ''''ShiftExchange_Check_Leave'''' [Message] FROM TA_Tbl_LeaveApplication LA
			WHERE LA.Employee_Id IN('' + @EmployeeId + '') AND [Status] = ''''Approved'''' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), '''''' + @FromDate + '''''', 102) AND CONVERT(VARCHAR(11), '''''' + @ToDate + '''''', 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), '''''' + @FromDate + '''''', 102) AND CONVERT(VARCHAR(11), '''''' + @ToDate + '''''', 102)))''
		EXEC(@Query)
	END
	ELSE IF(@Func = ''SRA'')
	BEGIN
		DECLARE @XML XML
		DECLARE @Index INT
		CREATE TABLE #TempEmployeeId(Employee_Id BIGINT)
		SET @XML = @EmployeeId
		SET @Index = 0
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO #TempEmployeeId
			SELECT Emp.EmployeeAutoID FROM OPENXML(@Index, ''/DocumentElement/Table'') WITH(EmployeeAutoID BIGINT ''EmployeeAutoID'') AS Emp
		EXEC sp_xml_removedocument @Index
		SELECT ''ShiftReAlloc_Check_Permission'' [Message] FROM TA_Tbl_Permission P
			INNER JOIN #TempEmployeeId E ON E.Employee_Id = P.Employee_Id
		WHERE P.Permission_Status = ''Approved'' AND P.Permission_Date BETWEEN CONVERT(VARCHAR(11), @FromDate , 102) AND CONVERT(VARCHAR(11), @ToDate, 102)
		UNION
		SELECT ''ShiftReAlloc_Check_Leave'' [Message] FROM TA_Tbl_LeaveApplication LA
		INNER JOIN #TempEmployeeId E ON E.Employee_Id = LA.Employee_Id
		WHERE [Status] = ''Approved'' AND ((LA.Leave_FromDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)) OR (LA.Leave_ToDate BETWEEN CONVERT(VARCHAR(11), @FromDate, 102) AND CONVERT(VARCHAR(11), @ToDate, 102)))
	END	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy 5,''01-Aug-2008'',''31-Dec-2016''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeaveAndPermissionWhileDeleteEmpLeavePolicy]
	-- Add the parameters for the stored procedure here
	@intEmpId int, 
	@leavePolicyFromDate nvarchar(25),
	@leavePolicyToDate nvarchar(25)
AS
	DECLARE @flag as int 
	DECLARE @count as int
	SET @flag = 0
	SET @count = 0
BEGIN
	SET NOCOUNT ON;
	SELECT @count =count(*) FROM TA_Tbl_LeaveApplication 
	WHERE Employee_Id = @intEmpId And IsDeleted = 0 
	And 
	((
	Leave_FromDate between CONVERT(DATETIME,@leavePolicyFromDate,102) And CONVERT(DATETIME,@leavePolicyToDate,102)
	) 
	or 
	(
	Leave_ToDate between CONVERT(DATETIME,@leavePolicyFromDate,102) And CONVERT(DATETIME,@leavePolicyToDate,102)
	))
	IF(@count=0)
		BEGIN
			SELECT @count = count(*) FROM TA_Tbl_Permission WHERE Employee_Id =@intEmpId And IsDeleted=0 And (Permission_Date >=  CONVERT(DATETIME,@leavePolicyFromDate,102) AND Permission_Date <=  CONVERT(DATETIME,@leavePolicyToDate,102))
		END
	SELECT @count as mappedCount
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Update]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeave_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeave_Update ''CL'',3
Description : check leave before update, is alraedy there   
Tables Included : TA_Tbl_LeaveType  
Created By : Arun Vinoth T  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeave_Update]    
(    
 @LeaveType NVARCHAR(50),    
 @Type_Id int    
)     
As    
 BEGIN    
  SET NOCOUNT ON;
   Select Count(LeaveType)as Ltype from TA_Tbl_LeaveType where LeaveType_Id<> cast(@Type_Id as nvarchar(20)) And LeaveType= @LeaveType 
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeave_Insert]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeave_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeave_Insert  
Description : check leave before insert, is alraedy there   
Tables Included : TA_Tbl_LeaveType  
Created By : Arun Vinoth T  
Created On : 14-Aug-2007
Modified By :  Karthikeyan.R
Modified On :  23-11-2016
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeave_Insert]  
(  
	@LeaveType NVARCHAR(50)
)   
As  
 BEGIN  
	SET NOCOUNT ON;
	Select Count(LeaveType)as Ltype from TA_Tbl_LeaveType where LeaveType=@LeaveType
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActiveEmployeeDetails]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ActiveEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_ActiveEmployeeDetails  
Description : select active employee details 
Tables Included : TA_Tbl_Employee  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007
Modified By : Kumuthini.L
Modified On :19-Feb-2008
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_ActiveEmployeeDetails] 
 AS
BEGIN
	SELECT Employee_Id,Employee_Code_Id,SwipeCardNo,OT_Eligible,EmailId  FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND IsDeleted = 0
	AND Employee_Firstname <> ''Administrator''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	06-SEP-2013
-- Description	:	Import the Employees
-- EXEC [Proc_TA_ActivateEmployeeBasedOnLicence] ''1000''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ActivateEmployeeBasedOnLicence]
	@EmployeeCount VARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @EmpIdTbl TABLE(Employee_Id INT)
	DECLARE @Query VARCHAR(MAX) 
	Declare @Deleted int	
	IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[UpdateTrigTA_Tbl_Employee]''))
		begin
			--DROP TRIGGER [dbo].[UpdateTrigTA_Tbl_Employee]
			DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
			set @Deleted=1
		end	
	SET @EmployeeCount = (CASE WHEN ISNULL(@EmployeeCount, '''') = '''' THEN ''0'' ELSE @EmployeeCount END)
	--SET @Query = ''SELECT TOP '' + @EmployeeCount + '' Employee_Id FROM TA_Tbl_Employee WHERE Employee_Status = 1 AND Isdeleted = 1 AND Employee_Code_Id <> ''''18000000''''''
	UPDATE TA_Tbl_Employee SET	
		Isdeleted = 1
		--Commented By Manikandan.R. while updating the license, inactive employees are activating automatically.
		--,
		--Report_Exclude = 0,
		--Employee_Status = 0,
		--InActiveDate = DATEADD(D, 1, DateOfJoining)
	WHERE Employee_Code_Id <> ''18000000'' AND ISNULL(InActive_Status, 0) = 0
	INSERT INTO @EmpIdTbl
		SELECT TOP (CAST(@EmployeeCount AS BIGINT)) Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 1 	
		AND Employee_Code_Id <> ''18000000'' AND ISNULL(Isdeleted_Status, 0) = 0
		ORDER BY Employee_Id
	UPDATE TA_Tbl_Employee SET	Isdeleted = 0
		--Commented By Manikandan.R. while updating the license, inactive employees are activating automatically.
		--,
		--Report_Exclude = 0,
		,Employee_Status = 1
		--,--InActiveDate = NULL
	FROM TA_Tbl_Employee E
	INNER JOIN @EmpIdTbl TE ON TE.Employee_Id = E.Employee_Id
	WHERE ISNULL(InActive_Status, 0) = 0
	Declare @SQLQuery varchar(max)
	set @SQLQuery=''''
	if @Deleted=1
		begin
			Enable TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllEmployees]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AllEmployees]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_AllEmployees  
Description : To get all the Employee without Filter Condition  
Tables Included : TA_Tbl_Employee  
Created By : Abul  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE  Proc [dbo].[Proc_TA_AllEmployees]
@LevelID int
As
Select * from TA_Tbl_Employee where Employee_Firstname<>''Administrator'' 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseRequestIDReactivation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:	Gopinath
-- Create date: <Create Date,,>
-- Description:	select Active and top 1 request ID 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestIDReactivation]
AS
BEGIN
select top(1) RequestID from TA_Tbl_LicenseRequestDetail order by CreatedDate desc 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseRequestID]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseRequestID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:	Gopinath
-- Create date: <Create Date,,>
-- Description:	select Active and top 1 request ID 
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseRequestID]
AS
BEGIN
select top(1) RequestID from TA_Tbl_LicenseRequestDetail where Status=1 order by CreatedDate desc 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_OL_SelectLicenseExpiryDate]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_OL_SelectLicenseExpiryDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:	Gopinath
-- Create date: 7htJuly2014
-- Description:select expiry date from the license expiry table  
-- =============================================
CREATE PROCEDURE [dbo].[Proc_OL_SelectLicenseExpiryDate]
AS
BEGIN
	select expirydate from ta_tbl_lic_details 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_lateEntry]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_lateEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : proc_lateEntry  
Description : get late entries  
Tables Included : ta_tbl_shift, ta_tbl_processedData, TA_Tbl_Employee
Created By : Kumuthini  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[proc_lateEntry]
	-- Add the parameters for the stored procedure here
(
	@fromDat datetime,
	@ToDat datetime,
	--@empId varchar(100),
	@shift int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	declare @shfTime as dateTime
	set @shfTime = (select Shift_StartTime from ta_tbl_shift where shift_id = @shift)	
	declare @graceTime as decimal
	set @graceTime = (select shift_graceInTime from ta_tbl_shift where shift_id=@shift)
	select @shfTime as shiftIn, dbo.TA_Tbl_Employee.Employee_Code_Id, dbo.TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.InTime,ta_tbl_processeddata.shift_id,
TA_Tbl_ProcessedData.lateIn,dbo.TA_Tbl_Employee.Employee_FirstName FROM  dbo.TA_Tbl_ProcessedData INNER JOIN
                      dbo.TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.Employee_Id
			where ta_tbl_processeddata.lateIn <> ''00:00:00'' and ta_tbl_processedData.lateIn is not null
And     (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, @fromDat, 102)) AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME, 
                      --@todat, 102)) AND (dbo.TA_Tbl_ProcessedData.Employee_Code_Id = @empid) AND 
@todat, 102))  AND 
                      (dbo.TA_Tbl_ProcessedData.InTime >= CONVERT(datetime, @shfTime, 101))and (DATEDIFF(mi, CONVERT(datetime, 
                      @shfTime, 101), dbo.TA_Tbl_ProcessedData.InTime)>@graceTime)
    -- Insert statements for procedure here
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDuplicateEmailID]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDuplicateEmailID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: [Proc_TA_CheckDuplicateEmailID]   
Description 	: check Email ID is already there or not to avoid duplication  
Tables Included : TA_Tbl_Employee  
Created By 		: karthikeyan.R
Created On 		: 23-08-2017
Proc_TA_CheckDuplicateEmailID ''U'',60,''manikandan.rr@angleritech.com''
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckDuplicateEmailID] 
(
	@tag char(1),
	@EmployeeID int,
	@EmailID NVARCHAR(500)
)
AS
BEGIN
	set nocount on
	declare @sql as varchar(3000)
	if(@tag=''I'')
		begin
			select COUNT(EmailId) as EID from TA_Tbl_Employee where EmailId=@EmailID
		end
	else if(@tag=''U'')
		begin
			select COUNT(EmailId) as EID from TA_Tbl_Employee where EmailId=@EmailID and Employee_Id<>@EmployeeID
		end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-01-2013>
-- Description:	<To check whether default shift is created or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCountForUpdate]
	-- Add the parameters for the stored procedure here
	@LevelId int,
	@ShiftID int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_Shift where Level_Id=@LevelId and DefaultShift=1 and Shift_Id<>@ShiftID and Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckDefaultShiftCount]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckDefaultShiftCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-01-2013>
-- Description:	<To check whether default shift is created or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckDefaultShiftCount]
	-- Add the parameters for the stored procedure here
	@LevelId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_Shift where Level_Id=@LevelId and DefaultShift=1 and Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCountFacorLeaveTypes]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCountFacorLeaveTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created date	:	29-Jan-2014
Descriptinos	:	Adding this procedure for checking whether the leave types is with count factor or not
Proc_TA_CheckCountFacorLeaveTypes 0
*/
CREATE PROC [dbo].[Proc_TA_CheckCountFacorLeaveTypes]
(
	@LeaveTypeId int=0
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @count int;
	DECLARE @LeaveType VARCHAR(10)
	select @count=COUNT(*),@LeaveType=LeaveType from TA_Tbl_LeaveType where LeaveType_Id<>@LeaveTypeId and CountFactor=1 group by LeaveType
	select  cast(isnull(@count,0) as varchar) +'',''+isnull(@LeaveType,'''') as count
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckConcurrentUserCount]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckConcurrentUserCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckConcurrentUserCount  
Description : check maximum no of concurrent user count   
Tables Included : TA_Tbl_ConcurrentUser  
Created By : Christopher S   
Created On : 24-Mar-08
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckConcurrentUserCount]
	-- Add the parameters for the stored procedure here	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_ConcurrentUser WHERE UserId<>''Admin''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompOffMapped]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCompOffMapped]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan
-- Create date: 22-Mar-2017
-- Description:	Delete the compensation entry by ID check the compoff taken any leave, If yes then entry can''t deleted.
-- Proc_TA_CompensationEntryByID 253
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_CheckCompOffMapped]
	-- Add the parameters for the stored procedure here
	@CompOff_ID as bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LeaveApplication as nvarchar(50)
	SELECT @LeaveApplication=LeaveApplicationId FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@CompOff_ID
	if(@LeaveApplication is null or @LeaveApplication='''')
		Begin
			Select ''1''
		END
	else
		BEGIn
			Select ''Availed''
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Update]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAddlWeekOff_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckAddlWeekOff_Update  
Description : check additional week off before update, is already there   
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P  
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Update]
(
	@AddlWeekOffID INT,
	@LevelId INT,
	@addlWeekoffDay NVARCHAR(15)='''',
	@addlWeekoffWeek NVARCHAR(15)=''''
)
AS
BEGIN
	SELECT COUNT(Addl_WeeklyOff_Id) AS AID FROM TA_Tbl_Additional_WeeklyOff WHERE LevelId_Id=@LevelId AND Addl_WeekOff_Day=@addlWeekoffDay AND Addl_WeekOff_Week=@addlWeekoffWeek AND Isdeleted=0 AND Addl_WeeklyOff_Id<>@AddlWeekOffID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAddlWeekOff_Insert]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAddlWeekOff_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckAddlWeekOff_Insert  
Description : check additional week off before insert, is already there   
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P   
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckAddlWeekOff_Insert]
(
	@LevelID INT,
	@addlWeekoffDay NVARCHAR(15)='''',
	@addlWeekoffWeek NVARCHAR(15)=''''
)
AS
BEGIN
	SELECT COUNT(Addl_WeeklyOff_Id) AS AID FROM TA_Tbl_Additional_WeeklyOff WHERE LevelId_Id=@LevelID AND Addl_WeekOff_Day=@addlWeekoffDay AND Addl_WeekOff_Week=@addlWeekoffWeek AND Isdeleted=0	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDuplicateForAdding]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		R.Manikandan
-- Create date: 12-June-2012
-- Description:	Checking Duplication Before adding category
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicateForAdding]
	@Opr as nvarchar(1),	
	@CategoryName as nvarchar(50),
	@CategoryID as int
AS
BEGIN
	SET NOCOUNT ON;
	if (@Opr=''I'')
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName 
		End
	Else
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and CategoryId<>@CategoryId 
		End	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDuplicate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDuplicate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : Prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDuplicate]
	@Opr as nvarchar(1),	
	@CategoryID as int
AS
BEGIN
	Declare @CategoryName as nvarchar(50)
	Set @CategoryName=(select CategoryName from ta_tbl_Category where CategoryId=@CategoryID)
	if (@Opr=''I'')
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and Isdeleted=0
		End
	Else
		Begin
			select * from ta_tbl_Category where CategoryName=@CategoryName and CategoryId<>@CategoryId and Isdeleted=0
		End	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCategoryDelete]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCategoryDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCategoryDelete]
	@CategoryID as int
AS
BEGIN
	select count(*) as RecCount from ta_tbl_employeeCategory
	where CategoryId=@CategoryId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowLeaveExists]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckBorrowLeaveExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name  : Proc_TA_CheckBorrowLeaveExists ''2008-09-15'',''2008-12-17'',151  
Description  : Check Approved Borrow Leave Exists after normal leaves  
Tables Included  : TA_Tbl_LeaveApplication  
Created By  : Prabakaran  
Created On  : 10-Sep-08  
Modified By  :   
Modified On  :   
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckBorrowLeaveExists]   
	@LeaveFromDate datetime,  
	@LeaveToDate datetime,
	@LeaveTypeId int,  
	@EmployeeId int  
as  
 BEGIN 
	SET NOCOUNT ON;
	select count(LeaveApplication_Id) as BorrowCount  from TA_Tbl_LeaveApplication   
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=TA_Tbl_LeaveApplication.YearSettings_Id  
	where LeaveType_Id=@LeaveTypeId and Employee_Id=@EmployeeId and Isdeleted=0 and Status=''Approved'' and IsBorrow=1 and ys.IsActive=1
 END   
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PermissionDate]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_PermissionDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_PermissionDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @PerDate VARCHAR(8000)
SELECT @PerDate = ISNULL(@PerDate + '', '', '''') + replace(convert(varchar(20),Permission_Date,106)+''(''+ISNULL(Permission_Hours,CONVERT(varchar(6), DATEDIFF(second,Permission_FromTime, Permission_ToTime)/3600) + '':'' + RIGHT(''0'' + CONVERT(varchar(2), (DATEDIFF(second, Permission_FromTime, Permission_ToTime) % 3600) / 60), 2) )+'')'','' '',''-'')   FROM Ta_tbl_Permission
where 
(TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, @fromDat, 102) and TA_Tbl_Permission.Permission_Date <= CONVERT(DATETIME, @ToDat, 102))
and 
TA_Tbl_Permission.Employee_id = @empId 
and permission_status=''Approved''
and IsDeleted=0
--select @PerDate as PermissionDate
return @PerDate
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_PendingLeaveDate]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_PendingLeaveDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_PendingLeaveDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @LeaveDate VARCHAR(8000)
 -- + '' ('' + cast(NumberOfDays as varchar(5)) + '') ''
 SELECT @LeaveDate = ISNULL(@LeaveDate + '', '', '''') + 
 case when  leave_fromdate=leave_todate then replace(convert(varchar(20),leave_fromdate,106)+''(''+ cast(NumberOfDays as varchar(5))+'')'','' '',''-'')
      else  replace(convert(varchar(20),leave_fromdate,106),'' '',''-'') + '' - '' +  replace(convert(varchar(20),leave_todate,106)+''(''+ cast(NumberOfDays as varchar(5))+'')'','' '',''-'')
      end
 FROM TA_Tbl_LeaveApplication
 where Employee_id = @EmpId and isdeleted=0 and Status!=''Approved'' and  Status!=''Rejected'' and (((CONVERT(DATETIME, cast(@fromDat as nvarchar(50))  , 102) between Leave_FromDate and Leave_ToDate) or (CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102) between Leave_FromDate and Leave_ToDate) )
 or (Leave_FromDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102)) or (Leave_ToDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50)) , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)))
 if(@LeaveDate!='''')
 begin
 set @LeaveDate= ''Pending Leaves : '' + isnull(@LeaveDate,'''')
 end
 return isnull(@LeaveDate,'''')
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_OnDuty]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_OnDuty]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 17-02-2014
-- Description:	Modified for weekly off records
-- =============================================
----select [dbo].[Func_TA_OnDuty](''2015/10/03'',''Present'',100,''FN'',''09:00 AM'',''01:30 PM'',''06:00 PM'',1,4,''04:30'')
CREATE FUNCTION [dbo].[Func_TA_OnDuty] 
(
	@Date as datetime,
	@AttendanceCode as varchar(50),
	@EmployeeCodeId as nvarchar(15),
	@AttendType as varchar(2),
	@ShiftStartTime varchar(20),
	@Shift_SecondHalf_Starttime varchar(20),
	@ShiftEndtime varchar(20),
	@isFlexible int,
	@Shiftid int,
	@TotWrkHrs varchar(10)
)
RETURNS varchar(15)
AS
BEGIN	
	declare @recCount as int
	declare @OnDutyText as varchar(15)
	set @OnDutyText=''''
	if((charindex(''PM'',@ShiftStartTime) > 0) and (charindex(''AM'',@ShiftEndtime) > 0))
		Begin
			if(charindex(''AM'',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType=''FN'')
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
									or
									cast(ManualTimeEntry_OutTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
							)
						end
					else
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry 
								where ManualTimeEntry_OutDate = case when ((charindex(''PM'',ManualTimeEntry_InTime)>0) and (charindex(''AM'',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
									or
									cast(ManualTimeEntry_OutTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
							)
						end
				End
			else if(charindex(''PM'',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType=''FN'')
						begin
							set @recCount=
							(
								select count(*) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date			
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < cast(@Shift_SecondHalf_Starttime as datetime)
									or
									case when charindex(''AM'',ManualTimeEntry_OutTime)>0 then
														dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime)) else cast(ManualTimeEntry_OutTime as datetime) end < cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
							)
						end
			else
				begin
						set @recCount=
						(
							select count(*) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate = case when ((charindex(''PM'',ManualTimeEntry_InTime)>0) and (charindex(''AM'',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
							and 
							(
								cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								or
								case when charindex(''AM'',ManualTimeEntry_OutTime)>0 then
								(dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime))) else (cast(ManualTimeEntry_OutTime as datetime)) end  > cast(@Shift_SecondHalf_Starttime as datetime)
							)
							and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
						)
				end
		End
End
else
Begin
	if(@AttendType=''FN'')
	begin
		set @recCount=(select count(*) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_InDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) < @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) < @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status=''Approved''
		)
	end
	else
	begin
		set @recCount=(select count(*) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_OutDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) > @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) > @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status=''Approved''
		)
	end
End
		if(@isFlexible=1)
			begin
				Declare @Count int
				select @count=count(*) from TA_Tbl_ManualTimeEntry 
				where ManualTimeEntry_OutDate = @Date and IsOnDuty=1
				and ManualTimeEntry_Employee_Id=@EmployeeCodeId
				and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
				if @count=0
					begin						
						if(substring(@ShiftStartTime,7,8)=''PM'' and substring(@ShiftEndtime,7,8)=''AM'')
						begin
							select @count=count(*) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate =dateadd(d,1, @Date)and IsOnDuty=1
							and ManualTimeEntry_Employee_Id=@EmployeeCodeId
							and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
						end
					end
				if(@Count>0)
				begin
					Declare @FHTotHrs varchar(20)
					Declare @SHTotHrs varchar(20)
					select @FHTotHrs= Shift_FirstHalfWorkingHours,@SHTotHrs=Shift_SecondHalfWorkingHours from TA_Tbl_Shift where Shift_Id=@Shiftid and Isdeleted=0
					if(@AttendType=''FN'')
					begin
						if(@TotWrkHrs<>''00:00'' and convert(datetime,@TotWrkHrs)>=convert(datetime,@FHTotHrs))
							begin
								set @recCount=1
							end
					end
					if(@AttendType=''AN'')
					begin
						if(@TotWrkHrs<>''00:00'' and CONVERT(datetime,@TotWrkHrs)>=convert(datetime,@SHTotHrs))
							begin
								set @recCount=1
							end
					end
				end
			end
if(@recCount>0)
begin
	if(@AttendanceCode=''Present'' or @AttendanceCode=''Weekly Off'' or @AttendanceCode=''Holiday'')
	begin
		set @OnDutyText='' (On Duty) ''
	End
end
RETURN @OnDutyText
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_MusterRoll_OD_Notation]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_MusterRoll_OD_Notation]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	19-02-2014
-- Description	:	Muster Roll On Duty Notation
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_MusterRoll_OD_Notation] 
(
	@Date DATETIME,
	@AttendanceCode NVARCHAR(50),
	@EmployeeCodeId NVARCHAR(15),
	@AttendType NVARCHAR(2),
	@ShiftId INT,
	@ReplaceText NVARCHAR(50)
)
RETURNS NVARCHAR(15)
AS
BEGIN	
	DECLARE @RecCount INT
	DECLARE @OnDutyText NVARCHAR(15), @ShiftStartTime NVARCHAR(20), @Shift_SecondHalf_Starttime NVARCHAR(20), @ShiftEndtime NVARCHAR(20)
	IF(@ShiftId = -1)
		SELECT @ShiftId = PD.Shift_Id FROM TA_Tbl_ProcessedData PD WHERE PD.[Date] = DATEADD(D, -1, @Date) AND PD.Employee_Code_Id = @EmployeeCodeId
	IF(@ShiftId = -1)
		SELECT @ShiftId = PD.Shift_Id FROM TA_Tbl_ProcessedData PD WHERE PD.[Date] = DATEADD(D, -2, @Date) AND PD.Employee_Code_Id = @EmployeeCodeId
	IF(EXISTS (SELECT S.Shift_EndTime FROM TA_Tbl_Shift S WHERE S.Shift_Id = @ShiftId))
		SELECT @ShiftStartTime = S.Shift_StartTime, @Shift_SecondHalf_Starttime = S.Shift_SecondHalf_StartTime, @ShiftEndtime = S.Shift_EndTime FROM TA_Tbl_Shift S WHERE S.Shift_Id = @ShiftId
	SET @OnDutyText = @ReplaceText
	IF((CHARINDEX(''PM'', @ShiftStartTime) > 0) AND (CHARINDEX(''AM'', @ShiftEndtime) > 0))
	BEGIN
		IF(CHARINDEX(''AM'', @Shift_SecondHalf_Starttime)>0)
		BEGIN
			IF(@AttendType = ''FN'')
			BEGIN
				SELECT @RecCount = COUNT(MTE.IsOnDuty) FROM TA_Tbl_ManualTimeEntry MTE
				WHERE MTE.ManualTimeEntry_InDate = @Date
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
									or
									cast(ManualTimeEntry_OutTime as datetime) < (dateadd(dd,1,cast(@Shift_SecondHalf_Starttime as datetime)))
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
						end
					else
						begin
							set @RecCount=
							(
								select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
								where ManualTimeEntry_OutDate = case when ((CHARINDEX(''PM'',ManualTimeEntry_InTime)>0) and (CHARINDEX(''AM'',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
									or
									cast(ManualTimeEntry_OutTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
							)
						end
				End
			else if(CHARINDEX(''PM'',@Shift_SecondHalf_Starttime)>0)
				Begin
					if(@AttendType=''FN'')
						begin
							set @RecCount=
							(
								select count(IsOnDuty) from TA_Tbl_ManualTimeEntry where ManualTimeEntry_InDate = @Date			
								and 
								(
									cast(ManualTimeEntry_InTime as datetime) < cast(@Shift_SecondHalf_Starttime as datetime)
									or
									case when CHARINDEX(''AM'',ManualTimeEntry_OutTime)>0 then
														dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime)) else cast(ManualTimeEntry_OutTime as datetime) end < cast(@Shift_SecondHalf_Starttime as datetime)
								)
								and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
							)
						end
			else
				begin
						set @RecCount=
						(
							select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
							where ManualTimeEntry_OutDate = case when ((CHARINDEX(''PM'',ManualTimeEntry_InTime)>0) and (CHARINDEX(''AM'',ManualTimeEntry_OutTime)>0)) then dateadd(dd,1,@Date) else @Date end
							and 
							(
								cast(ManualTimeEntry_InTime as datetime) > cast(@Shift_SecondHalf_Starttime as datetime)
								or
								case when CHARINDEX(''AM'',ManualTimeEntry_OutTime)>0 then
								(dateadd(dd,1,cast(ManualTimeEntry_OutTime as datetime))) else (cast(ManualTimeEntry_OutTime as datetime)) end  > cast(@Shift_SecondHalf_Starttime as datetime)
							)
							and IsOnDuty=1 and ManualTimeEntry_Employee_Id=@EmployeeCodeId and IsDeleted=0 and ManualTimeEntry_Status=''Approved''
						)
				end
		End
End
else
Begin
	if(@AttendType=''FN'')
	begin
		set @RecCount=(select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_InDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) < @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) < @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status=''Approved''
		)
	end
	else
	begin
		set @RecCount=(select count(IsOnDuty) from TA_Tbl_ManualTimeEntry 
		where ManualTimeEntry_OutDate = @Date
		and 
		(
		cast(ManualTimeEntry_InTime as datetime) > @Shift_SecondHalf_Starttime
		or
		cast(ManualTimeEntry_OutTime as datetime) > @Shift_SecondHalf_Starttime
		)
		and IsOnDuty=1
		and ManualTimeEntry_Employee_Id=@EmployeeCodeId
		and IsDeleted=0
		and ManualTimeEntry_Status=''Approved''
		)
	end
End
if(@RecCount>0)
begin
	if(@AttendanceCode=''Present'' or @AttendanceCode=''Weekly Off'' or @AttendanceCode=''Holiday'')
	begin
		set @OnDutyText=''OD''
	End
end
RETURN @OnDutyText
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_LeaveDate]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_LeaveDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_LeaveDate]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @LeaveDate VARCHAR(8000)
 -- + '' ('' + cast(NumberOfDays as varchar(5)) + '') ''
 SELECT @LeaveDate = ISNULL(@LeaveDate + '', '', '''') + 
 case when  leave_fromdate=leave_todate then replace(convert(varchar(20),leave_fromdate,106)+''(''+ cast(NumberOfDays as varchar(5))+'')'','' '',''-'')
      else  replace(convert(varchar(20),leave_fromdate,106),'' '',''-'') + '' - '' +  replace(convert(varchar(20),leave_todate,106)+''(''+ cast(NumberOfDays as varchar(5))+'')'','' '',''-'')
      end
 FROM TA_Tbl_LeaveApplication
 where Employee_id = @EmpId and isdeleted=0 and Status=''Approved'' and (((CONVERT(DATETIME, cast(@fromDat as nvarchar(50))  , 102) between Leave_FromDate and Leave_ToDate) or (CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102) between Leave_FromDate and Leave_ToDate) )
 or (Leave_FromDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)) , 102)) or (Leave_ToDate between CONVERT(DATETIME, cast(@fromDat as nvarchar(50)) , 102) and CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)))
 return isnull(@LeaveDate,'''')
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:           <R.Manikandan>
-- Create date: <04-11-2016>
-- Description:      <Get the closed shift details>
-- select dbo.[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](2,''03/01/2017 06:00 pM'',1,''03/01/2017'')
-- select * from ta_tbl_leveldetails
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData]
(
       -- Add the parameters for the function here
       @CompanyId int,
       @InPunchTime varchar(30),
       @Selectby int,
	   @Date datetime
)
RETURNS varchar(max)
AS
BEGIN
       -- Declare the return variable here
       DECLARE @Final TABLE(NearShift varchar(max),Differences int,Shift_StartTime varchar(20),Orderby int)
       DECLARE @TimeFormat as nvarchar(10)
       SELECT @TimeFormat=TimeFormat FROM TA_Tbl_DateandTimeFormat
       -- Add the T-SQL statements to compute the return value here
       Insert into @Final
       select *,RANK()over(order by diff) from 
	   (
			select Shift_ShortName +'': ''+
			case   when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex('':'',Shift_StartTime)))=1 then ''0''+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,@Date+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,@Date+Shift_StartTime,@InPunchTime)
				  else datediff(minute,@Date+Shift_StartTime,@InPunchTime) end as diff,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!=''No Shift'' and shift_shortName!=''NOS'' 
		   union all
		   select Shift_ShortName +'': ''+
			case   when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex('':'',Shift_StartTime)))=1 then ''0''+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)
				  else datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime) end as diff,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!=''No Shift'' and shift_shortName!=''NOS'' 
	   )as a
       Declare @FinalData varchar(max)
       select @FinalData=coalesce(@FinalData+'';'','''')+ NearShift from @Final where orderby=@Selectby order by Orderby,Shift_StartTime
       -- Return the result of the function
       RETURN (@FinalData)
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Description,,>
-- select * from [Func_TA_GettingCloseShiftDetailsUsingInpunchTime](2,''03/01/2017 06:00 PM'',1,''03/01/2017'')
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime]
(	
	@CompanyId int,
	@InPunchTime varchar(30),
	@Selectby int,
	@Date datetime
)
RETURNS @Final TABLE(NearShift varchar(max),Differences int,ShiftID int,Shift_StartTime varchar(20),Orderby int)
AS
BEGIN	
	DECLARE @TimeFormat as nvarchar(10)
    SELECT @TimeFormat=TimeFormat FROM TA_Tbl_DateandTimeFormat
	INSERT INTO @Final
	 select *,RANK()over(order by diff) from 
	   (
			select Shift_ShortName +'': ''+
			case   when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex('':'',Shift_StartTime)))=1 then ''0''+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,@Date+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,@Date+Shift_StartTime,@InPunchTime)
				  else datediff(minute,@Date+Shift_StartTime,@InPunchTime) end as diff,Shift_Id,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!=''No Shift'' and shift_shortName!=''NOS'' 
		   union all
		   select Shift_ShortName +'': ''+
			case   when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Shift_StartTime,0)), 114),0,6)
						 else   case   when len(SUBSTRING(Shift_StartTime,0,charindex('':'',Shift_StartTime)))=1 then ''0''+Shift_StartTime
													else Shift_StartTime
									  end
		   end Shift_StartTime,
		   case when datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)<0 then -datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime)
				  else datediff(minute,dateadd(d,1,@Date)+Shift_StartTime,@InPunchTime) end as diff,Shift_Id,Shift_StartTime as start
		   from ta_tbl_shift where level_id=@companyid and Shift_Name!=''No Shift'' and shift_shortName!=''NOS'' 
	   )as a order by RANK()over(order by diff),Shift_StartTime
	RETURN
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[CheckVehicleNoExists]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckVehicleNoExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : CheckVehicleNoExists
Description : check vehicle no is exist or not  
Tables Included : TA_Tbl_Transportation  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE procedure [dbo].[CheckVehicleNoExists](@VehicleNo INT) as 
     SELECT * FROM TA_Tbl_Transportation
                         WHERE VehicleNo=@VehicleNo
' 
END
GO
/****** Object:  StoredProcedure [dbo].[CheckLeaveBeforeAfterWithPermission]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckLeaveBeforeAfterWithPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	CheckLeaveBeforeAfterWithPermission ''02/19/2008'',''02/20/2008'',''PermissionOnLeave'',5
Description		:	Check Permission Count for Before or After Leave Dates
Tables Included	:	TA_Tbl_Permission
Created By		:	Kumuthini
Created On		:	04-Sep-08
Modified By		:	
Modified On		:	
*/
-- [CheckLeaveBeforeAfterWithPermission] ''09/03/2016'',''09/03/2016'',''LeaveAfterPermission'',''''
CREATE PROCEDURE [dbo].[CheckLeaveBeforeAfterWithPermission] 
	@LeaveFromDate datetime,
	@LeaveToDate datetime,
	@LeaveType nvarchar(50),
	@EmployeeId int
as
begin
	SET NOCOUNT ON;
	declare @Count as int
	if(@LeaveType=''LeaveAfterPermission'')
	-- Check Leave falls After Permission
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission 
			where Permission_Date=DATEADD( day ,1,@LeaveToDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END
	else if(@LeaveType=''LeaveBeforePermission'')
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission
			where Permission_Date=DATEADD( day ,-1,@LeaveFromDate) and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END 
	else if(@LeaveType=''LeaveOnPermission'')
	-- Check Permission and Leave on same day
		BEGIN
			select @Count=count(Permission_Id) from TA_Tbl_Permission 
			where ((@LeaveFromDate between Permission_FromTime and Permission_ToTime) or (@LeaveToDate between Permission_FromTime and Permission_ToTime)) 
			and Employee_Id=@EmployeeId and Isdeleted=0 and Permission_Status<>''Rejected''
		END 
	select @Count as PermissionCount
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[CheckApplicationDateExistsinYearsettings]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckApplicationDateExistsinYearsettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- CheckApplicationDateExistsinYearsettings ''10/Apr/2012'',''10/Apr/2012'',2
-- =============================================
CREATE PROCEDURE [dbo].[CheckApplicationDateExistsinYearsettings]  
	-- Add the parameters for the stored procedure here
	@Fromdate datetime,
	@ToDate datetime,
	@YearsettingId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if exists(select * from ta_tbl_yearsetting where Yearsettings_Id=@YearsettingId and FromDate <= @Fromdate and FromDate <= @ToDate 
		and ToDate >= @Fromdate and ToDate >= @ToDate )
			begin
				select ''OK''
			end
	else
	 select ''wrong''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [CalculateSpecialOvertimeOnWeeklyAndHolidays_09Sep2019] ''2019-09-08 08:18:00.000'',''2019-09-08 17:30:00.000'',5722,132,'''',64
-- =============================================
CREATE PROCEDURE [dbo].[CalculateSpecialOvertimeOnWeeklyAndHolidays]	
	@FirstInDateTime DATETIME,
	@LastOutDateTime DATETIME,
	@CompanyID INT,
	@TotalOTMins INT,
	@flag char(2),
	@ShiftID int,
	@ShiftDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	IF(@TotalOTMins>0)
	BEGIN
		DECLARE @ConfigSpecialOverTime1 INT
		DECLARE @ConfigSpecialOverTime2 INT
		SET @ConfigSpecialOverTime1 =0
		SET @ConfigSpecialOverTime2 =0
		DECLARE @SpecialOverTime1_StartTime DATETIME
		DECLARE @SpecialOverTime1_EndTime DATETIME
		DECLARE @SpecialOvertime1Mins INT
		DECLARE @SpecialOvertime2Mins INT
		DECLARE @NormalOvertimeMins INT
		IF(@flag=''WH'')
		BEGIN
			SELECT @ConfigSpecialOverTime1=SpecialOverTime1*60,@ConfigSpecialOverTime2=SpecialOverTime2*60 FROM TA_Tbl_ShiftSETtings WHERE CompanyId=@CompanyID
			SET @ConfigSpecialOverTime1=ISNULL(@ConfigSpecialOverTime1,0)
			SET @ConfigSpecialOverTime2=ISNULL(@ConfigSpecialOverTime2,0)
			IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2>0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@SpecialOverTime1_EndTime)
					SET	@SpecialOvertime2Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_EndTime,@LastOutDateTime)
				END
				ELSE
				BEGIN
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@LastOutDateTime)
					SET	@SpecialOvertime2Mins		=0
				END
			END
			ELSE IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2=0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN
					--SELECT ''2 Loop 1''
					SET @SpecialOverTime1_StartTime	=DATEADD(MINUTE,@ConfigSpecialOverTime1,@FirstInDateTime)
					SET @SpecialOverTime1_EndTime	=DATEADD(MINUTE,@ConfigSpecialOverTime2,@SpecialOverTime1_StartTime)
					SET	@NormalOvertimeMins			=DATEDIFF(MINUTE,@FirstInDateTime,@SpecialOverTime1_StartTime)
					SET @SpecialOvertime1Mins		=DATEDIFF(MINUTE,@SpecialOverTime1_StartTime,@LastOutDateTime)
					SET	@SpecialOvertime2Mins		=0
				END
				ELSE
				BEGIN
					--SELECT ''2 Loop 2''
					SET	@NormalOvertimeMins			=@TotalOTMins
					SET @SpecialOvertime1Mins		=0
					SET	@SpecialOvertime2Mins		=0
				END
			END
			else
			BEGIN
				SET	@NormalOvertimeMins			=@TotalOTMins
				SET @SpecialOvertime1Mins		=0
				SET	@SpecialOvertime2Mins		=0
			END
		END
		ELSE
		BEGIN		
			SELECT @ConfigSpecialOverTime1=specialOvertime_start1,@ConfigSpecialOverTime2=specialOvertime_start2 
			FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID and Level_Id=@CompanyID
		
			SET @ConfigSpecialOverTime1=ISNULL(@ConfigSpecialOverTime1,0)
			SET @ConfigSpecialOverTime2=ISNULL(@ConfigSpecialOverTime2,0)					
			IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2>0)
			BEGIN
				IF(@TotalOTMins>=(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2))
				BEGIN					
					--6>=5
					--SPECIAL OT2=1
					--SPECILA OT1=2
					--NORMAL  OT =3
					--5>=5
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3										
					SET	@SpecialOvertime2Mins		=@TotalOTMins-(@ConfigSpecialOverTime1+@ConfigSpecialOverTime2)
					SET @SpecialOvertime1Mins		=@ConfigSpecialOverTime2
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins-@SpecialOvertime2Mins
				END
				ELSE IF(@TotalOTMins>=@ConfigSpecialOverTime1)
				BEGIN					
					SET	@SpecialOvertime2Mins		=0
					SET @SpecialOvertime1Mins		=@TotalOTMins-(@ConfigSpecialOverTime1)
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins-@SpecialOvertime2Mins
				END
				ELSE
				BEGIN
					--4>=5
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3
					SET	@SpecialOvertime2Mins		=0
					SET @SpecialOvertime1Mins		=0
					SET	@NormalOvertimeMins			=@TotalOTMins
				END
			END
			ELSE IF(@ConfigSpecialOverTime1>0 AND @ConfigSpecialOverTime2=0)
			BEGIN
				IF(@TotalOTMins>=@ConfigSpecialOverTime1)
				BEGIN
					--5>=3
					--SPECIAL OT2=0
					--SPECILA OT1=2
					--NORMAL  OT =3
					--4>=3
					--SPECIAL OT2=0
					--SPECILA OT1=1
					--NORMAL  OT =3				
					SET @SpecialOvertime1Mins		=@TotalOTMins-@ConfigSpecialOverTime1
					SET	@NormalOvertimeMins			=@TotalOTMins-@SpecialOvertime1Mins
					SET	@SpecialOvertime2Mins		=0
				END
				ELSE
				BEGIN
					SET @SpecialOvertime1Mins		=0
					SET	@NormalOvertimeMins			=@TotalOTMins
					SET	@SpecialOvertime2Mins		=0
				END
			END
			ELSE
			BEGIN
				--5>=3
				--SPECIAL OT2=0
				--SPECILA OT1=0
				--NORMAL  OT =5
				--4>=3
				--SPECIAL OT2=0
				--SPECILA OT1=0
				--NORMAL  OT =4	
				SET	@NormalOvertimeMins			=@TotalOTMins
				SET @SpecialOvertime1Mins		=0
				SET	@SpecialOvertime2Mins		=0
			END
		END
		select	Normal	=case when @NormalOvertimeMins<0	then 0 else @NormalOvertimeMins end,
				Special1=case when @SpecialOvertime1Mins<0	then 0 else @SpecialOvertime1Mins end,
				Special2=case when @SpecialOvertime2Mins<0	then 0 else @SpecialOvertime2Mins end
	END
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckVehicleMapping_VehicleID_Update
Description : check vehicle mapping while update
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_Update]
(
	@VehicleId INT,
	@RouteId   INT
) 
As
DECLARE @Isdel INT
SET @Isdel=1
	BEGIN
			SELECT count(VehicleId) AS VId FROM TA_Tbl_Transportation_Mapping 
			WHERE VehicleId<>@VehicleId AND RouteId=@RouteId AND Isdeleted=@Isdel
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckVehicleMapping_VehicleID_INSERT
Description : check vehicle mapping while insert
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicleMapping_VehicleID_INSERT]
(
	@VehicleId INT
) 
As
DECLARE @Isdel INT
SET @Isdel=1
	BEGIN
			SELECT count(VehicleId) AS VId FROM TA_Tbl_Transportation_Mapping WHERE VehicleId=@VehicleId AND Isdeleted=@Isdel
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckVehicle_Update]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckVehicle_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name : Proc_TA_CheckVehicle_Update  
Description : check vehicle before update, is exist or not    
Tables Included : TA_Tbl_Transportation_Vehicle    
Created By : Arun Vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckVehicle_Update]
(
	@VehicleId int
)   
As
	DECLARE @sql as nvarchar(3000)
	DECLARE @Isdel INT  
	SET @Isdel=0
	DECLARE @VehicleNo varchar(50)
	BEGIN  
		--Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>@VehicleId And VehicleNo=@VehicleNo AND Isdeleted=@Isdel
		Select @VehicleNo=VehicleNo  from TA_Tbl_Transportation_Vehicle where VehicleId=@VehicleId
		set @sql = ''Select Count(VehicleNo)as VNO from TA_Tbl_Transportation_Vehicle where VehicleId<>''+cast(@VehicleId as nvarchar(25))+'' And VehicleNo=N''''''+@VehicleNo+'''''' AND Isdeleted=''+cast(@Isdel as nvarchar(25))+''''
		exec(@sql)     
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationEntryByID]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationEntryByID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan
-- Create date: 22-Mar-2017
-- Description:	Delete the compensation entry by ID check the compoff taken any leave, If yes then entry can''t deleted.
-- Proc_TA_CompensationEntryByID 253
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CompensationEntryByID]
	-- Add the parameters for the stored procedure here
	@CompOff_ID as bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @LeaveApplication as nvarchar(50)
	SELECT @LeaveApplication=LeaveApplicationId FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@CompOff_ID
	if(@LeaveApplication is null or @LeaveApplication='''')
		Begin
			update TA_Tbl_ProcessedData set OvertimeStatus=''Canceled'' where Process_Rec_ID in (select Process_Rec_ID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@CompOff_ID)
			update TA_Tbl_OverTimeStatus set isdelete=1,OverTimeStatus=''Canceled'' where ExtraTime_Id=@CompOff_ID
			Select ''1''
		END
	else
		BEGIn
			Select ''Availed''
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectTerminalDetailsForService]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CollectTerminalDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 23-05-2015
-- Description:	Getting The terminal details for processing
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CollectTerminalDetailsForService]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select TD.TerminalDatatype_ID,TD.FileType,TB.KeyValue from TA_Tbl_TerminalDatatype TD 
	inner join TA_Tbl_TerminalBrand TB on TD.BrandID=TB.BrandID where TD.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CollectRBMSRawDataForService]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CollectRBMSRawDataForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 23-05-2015
-- Description:	Getting The RDBMSRaw data details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CollectRBMSRawDataForService]
	-- Add the parameters for the stored procedure here
	@FileType nvarchar(30),
	@TerminalDatatype_ID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ConnectionString,TableName,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_DateTime,DateTimeFormat,RDBMS_Date,DateFormat,RDBMS_Time,TimeFormat,
	RDBMS_Type,RDBMS_MDB_Flag,RDBMS_TransactionIdentifier,TransactionIdentifierBit,TransactionIdentifierValue,IsEncrypted from TA_Tbl_TerminalDataType 
	where FileType = @FileType and TerminalDatatype_ID = @TerminalDatatype_ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Show Employee info in Grid - CMI Tech>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CleartableCMITechSyncEmployeeInfo]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	Delete from Ta_Tbl_ImportMasterData

END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserStatus]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckUserStatus  
Description : check user status 
Tables Included : TA_Tbl_ConcurrentUser  
Created By : S.Christopher 
Created On : 30-Oct-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckUserStatus] 
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_ConcurrentUser
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserRights]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckUserRights  
Description : Checking UserRights
Tables Included : ta_tbl_userRights  
Created By : senthil  
Created On : 11-oct-2007
Modified By :  
Modified On :  
[dbo].[Proc_TA_CheckUserRights]243,1,''''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckUserRights]
(
	@pageId int,
	@groupId int,
	@opr varchar(20)
)
AS
BEGIN
	if (@opr='''')
		Begin
			select * from ta_tbl_userRights where (pageid=@pageId and groupid=@groupId and Isdeleted=0) and (addPrv=1 or modifyPrv=1 or deletePrv=1 or viewPrv=1)
		End
	Else
		Begin
			declare @sql as nvarchar(500)
			set @sql = ''select * from ta_tbl_userRights where (pageid='' + cast(@pageId as nvarchar(10)) + '' and groupid= '' + cast(@groupId as nvarchar(10)) + '' and Isdeleted=0) and ('' + cast(@opr as nvarchar(20)) + ''=1)''
			exec(@sql)
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUserExists]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUserExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_CheckUserExists] 
(
@UserName VARCHAR(15)
)
AS
BEGIN
SELECT Count(UserName) as UserCount FROM TA_Tbl_Employee WHERE UserName=@UserName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckUnProcessedDataExists]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckUnProcessedDataExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/***************************************************************************
    Purpose  - Checking in the Processed Data whether records are processed
    Author     - Kumuthini.L 
    Proc_TA_CheckUnProcessedDataExists	'''','''',''''
****************************************************************************/
CREATE PROCEDURE [dbo].[Proc_TA_CheckUnProcessedDataExists]
(
	@SwipeCardNo nVarchar(25),
	@FromDate datetime,
	@ToDate datetime
)
AS
BEGIN
	SELECT Count(*) AS Count FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id = @SwipeCardNo AND Date BETWEEN @FromDate AND @ToDate AND ProcessFlag = 0
END
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicateForRestore]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDuplicateForRestore]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicateForRestore]
	@Opr as nvarchar(1),	
	@TypeID as int
AS
BEGIN
	Declare @TypeName as nvarchar(50)
	set @TypeName=(select TypeName from TA_Tbl_Type where TypeId=@TypeID)
	if (@Opr=''I'')
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and Isdeleted=0
		End
	Else
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and TypeId<>@TypeId and Isdeleted=0
		End	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDuplicate]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDuplicate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- ALTER  date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by : prabakaran.P
-- Modified on : 22-Aug-08
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDuplicate]
	@Opr as nvarchar(1),
	@TypeName as nvarchar(50),
	@TypeID as int
AS
BEGIN
	if (@Opr=''I'')
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName 
		End
	Else
		Begin
			select * from ta_tbl_Type where TypeName=@TypeName and TypeId<>@TypeId 
		End	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTypeDelete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTypeDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckTypeDelete]
	@TypeID as int
AS
BEGIN
	select count(*) as RecCount from ta_tbl_employeeType
		where TypeId=@TypeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleNameBYID]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitleNameBYID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckTitleNameBYID  
Description : check title by id
Tables Included : TA_Tbl_TitleMapping  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckTitleNameBYID]    
(    
 --@TitleName NVARCHAR(50),    
 @TitleId int    
)     
As    
DECLARE @Isdel INT    
SET @Isdel=1    
 BEGIN    
   Select Count(TitleId)as TName from TA_Tbl_TitleMapping    
   where TitleId=@TitleId AND Isdeleted=@Isdel --And TitleName=@TitleName     
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitleName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitleName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_CheckTitleName]
(@CompanyId INT,@RegionId INT,@BranchId INT,@DepartmentId INT,@Section INT,@TitleId INT)
as
BEGIN
	SELECT COUNT(TitleId) as TId  FROM TA_Tbl_TitleMapping WHERE Company_Id=@CompanyId 
		and Region_Id=@RegionId and Branch_Id=@BranchId and Department_Id=@DepartmentId And Section_Id=@Section AND TitleId=@TitleId AND IsDeleted=1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalNameUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckTerminalNameUpdate  
Description 	: check terminal name before update
Tables Included : TA_Tbl_Terminal  
Created By 	: kumuthini  
Created On 	: 14-Aug-2007
Modified By 	: Prabakaran.P
Modified On 	: 17-Mar-08
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckTerminalNameUpdate]
(
@TerminalID INT,
@TerminalReaderID NVARCHAR(50),
@TerminalName nvarchar(50)
)
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
	SELECT count(Terminal_Id)  AS TID FROM TA_Tbl_Terminal 
	WHERE (Terminal_ReaderID=@TerminalReaderID OR Terminal_Name=@TerminalName) and Terminal_Id<>@TerminalID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName_Sync]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalName_Sync]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	:	Proc_TA_CheckTerminalName_Sync  
Description 	:	check terminal name before insert
Tables Included :	TA_Tbl_Terminal  
Created By 	:	karthikeyan.R
Created On 	:	05-Mar-2016
*/  
create  PROCEDURE [dbo].[Proc_TA_CheckTerminalName_Sync]
(
@TerminalReaderId nvarchar(50)=''''
)
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
SELECT count(Terminal_Id) AS TID FROM TA_Tbl_Terminal 
WHERE Terminal_ReaderID=@TerminalReaderId
END
----------------------------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTerminalName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTerminalName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	:	Proc_TA_CheckTerminalName  
Description 	:	check terminal name before insert
Tables Included :	TA_Tbl_Terminal  
Created By 	:	kumuthini  
Created On 	:	14-Aug-2007
Modified By 	: 	Manikandan.R
Modified On 	:  	22-11-2016 15.17
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckTerminalName]
(
	@TerminalReaderId nvarchar(10)='''',
	@TerminalName nvarchar(50)
)
AS
BEGIN
	SELECT count(Terminal_Id) AS TID FROM TA_Tbl_Terminal WHERE (Terminal_ReaderID=@TerminalReaderId OR Terminal_Name=@TerminalName) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckTempShiftAllocation  
Description : check temporary shift allocation 
Tables Included : TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTempShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
        SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckTemporaryShiftAllocation  
Description : check temporary shift allocation 
Tables Included : TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckTemporaryShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
               SELECT EmployeeId  FROM TA_Tbl_TemporaryShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSuperAdminUser]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckSuperAdminUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_CheckSuperAdminUser
Description		:	validates the user is a super admin user
Tables Included	:	TA_Tbl_Employee, TA_Tbl_UserGroup
Created By		:	Prabakaran.P
Created On		:	24-July-09
Modified By		:
Modified On		:
Proc_TA_CheckSuperAdminUser '''',''''
*/
CREATE PROCEDURE [dbo].[Proc_TA_CheckSuperAdminUser]
@Username varchar(50),
@PassWord varchar(200)
as
BEGIN
select count(*) as UserCount from TA_Tbl_Employee e
inner join TA_Tbl_UserGroup ug
on ug.groupId=e.UserGroup_Id
where e.UserName=@Username and e.Emp_Password=@PassWord and 
ug.groupName=''SuperAdmin'' and e.isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftRestore]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftRestore]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name	: Proc_TA_CheckShiftRestore  
Description	: While Restore Shift, Checking duplicate shift Name 
Tables Included : Ta_tbl_Shift
Created By 	: Prabakaran  
Created On 	: 06-FEB-08  
Modified By 	:  
Modified On 	:  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftRestore] 
@ShiftId int
as
select count(Shift_Name)as ShiftCount from TA_Tbl_Shift
where lower(Shift_Name)in (select lower(Shift_Name) from TA_Tbl_Shift where Shift_Id=@ShiftId) and Shift_Id<>@ShiftId AND Isdeleted = 0
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftTime]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftTime]
	@ShiftID as int
AS
BEGIN	
	select shift_StartTime,shift_EndTime,Shift_FirstHalf_StartTime,Shift_FirstHalf_EndTime,Shift_SecondHalf_StartTime,Shift_SecondHalf_EndTime,Shift_BreakStartTime1,Shift_BreakEndTime1,
	Shift_BreakStartTime2,Shift_BreakEndTime2,Shift_BreakStartTime3,Shift_BreakEndTime3,[24HrsShift] from ta_tbl_shift where  shift_ID=@ShiftID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftDelete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name	: Proc_TA_CheckShiftDelete    
Description	: check shift Delete   
Tables Included : Ta_tbl_PermanentShiftAllocation, Ta_tbl_TemporaryShiftAllocation, TA_Tbl_ShiftPattern    
Created By 	: Prabakaran    
Created On 	: 30-Jul-07    
Modified By 	:
Modified On 	:
*/  
CREATE       PROCEDURE [dbo].[Proc_TA_CheckShiftDelete] 
@ShiftId int
as
	declare @loop as int
	declare @count as int
	declare @count1 as int
	declare @count2 as int
	declare @query as varchar(2000)
	create table #Temp(Result int)
	set @loop=1
	set @count=0
	set @count1=0
	set @count2=0
	/* For getting count from Ta_tbl_PermanentShiftAllocation */
	while @loop<=31
		begin
			set @query=''select count(*) as Result  from Ta_tbl_PermanentShiftAllocation where Day'' + Cast(@loop as Varchar(3)) + ''Shift='' + Cast(@ShiftId as varchar(2000))
			insert into #Temp EXEC(@query)
			set @loop=@loop+1
		end
	set @count=(select sum(Result) from #Temp)
	delete from #Temp
	set @loop=1
	/*------------------*/
	/* For getting count from Ta_tbl_TemporaryShiftAllocation */
	--while @loop<=31
	--
	--begin
	--set @query=''select count(*) as Result  from Ta_tbl_TemporaryShiftAllocation where Day'' + Cast(@loop as Varchar(3)) + ''Shift='' + Cast(@ShiftId as varchar(2000)) 
	--
	--insert into #Temp EXEC(@query)
	--
	--
	--set @loop=@loop+1
	--end
	--
	--set @count1=(select sum(Result) from #Temp)
	delete from #Temp
	set @loop=1
	/*------------------*/
	/* For getting count from TA_Tbl_ShiftPattern */
	while @loop<=31
		begin
			set @query=''select count(*) as Result  from TA_Tbl_ShiftPattern where Day'' + Cast(@loop as Varchar(3)) + ''_Shift='' + Cast(@ShiftId as varchar(2000))
			 --Isdeleted=0 and 
			insert into #Temp EXEC(@query)
			set @loop=@loop+1
		end
	set @count2=(select sum(Result) from #Temp)
	drop table #Temp
/*------------------*/
	set @count=@count+ @count1+ @count2
	if(@count>1)
		begin
			set @count=1
		end
	declare @LevelId as int
	set @LevelId=(select Level_Id FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftId)
	if(@LevelId=0)
		begin
			set @count=1
		end
	select @count as ShiftCount
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: 27-May-2011
-- Description:	To check whether shift overlaps which shift re-allocating.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftOverLapping_ForShiftReallocation]
(
	@ShiftID as int,
	@LoggedInemployeeId bigint,
	@xml xml
)
AS
BEGIN
    Declare @Index int
	Set @Index = 0;
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
    --Deletes the employee in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" whom are not available in the xml data
	DELETE from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where not exists
	(select xm.EmployeeAutoID from  OpenXML(@Index, ''/DocumentElement/Table'') With (EmployeeAutoID Bigint ''EmployeeAutoID'') as xm
	where xm.EmployeeAutoID=TA_Tbl_EmployeeShiftId_ForShiftReAllocation.EmployeeAutoId and TA_Tbl_EmployeeShiftId_ForShiftReAllocation.LoggedInEmployeId = @LoggedInemployeeId)
	Exec sp_xml_removedocument @Index
	declare @FromDate datetime
	set @FromDate = (select MIN(date) from TA_Tbl_EmployeeShiftId_ForShiftReAllocation)
	declare @ToDate datetime
	set @ToDate = (select MAX(Date) from TA_Tbl_EmployeeShiftId_ForShiftReAllocation)
    --Updates the current shift Id.
	update TA_Tbl_EmployeeShiftId_ForShiftReAllocation 
	set CurrentShiftId = @ShiftID where LoggedInEmployeId = @LoggedInemployeeId
	and Date between DATEADD(dd,1,@FromDate) and DATEADD(dd,-1,@ToDate)
	if(DATEADD(dd,1,@FromDate) <> DATEADD(dd,-1,@ToDate))
	BEGIN
		update A set A.PreviousDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on A.Date = dateadd(dd,-1,B.Date)
		where A.Date between DATEADD(dd,1,@FromDate) and @ToDate and A.EmployeeAutoId=B.EmployeeAutoId
		update A set A.NextDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on A.Date = dateadd(dd,1,B.Date)
		where A.Date between @FromDate and DATEADD(dd,-1,@ToDate) and A.EmployeeAutoId=B.EmployeeAutoId
	END
	declare @ToDateTemp datetime
	 set @ToDateTemp=@ToDate
	While(@ToDateTemp>@FromDate)
	begin
		update A set A.PreviousDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date = dateadd(dd,-1,@ToDateTemp)
		where A.Date =@ToDateTemp and A.EmployeeAutoId=B.EmployeeAutoId
		set @ToDateTemp=dateadd(dd,-1,@ToDateTemp)
	end
	declare @FromDateTemp datetime
	set @FromDateTemp=@FromDate
	While(@FromDateTemp<@ToDate)
	begin
		update A set A.NextDayShift = B.CurrentShiftId
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A 
		inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date = dateadd(dd,1,@FromDateTemp)
		where A.Date = @FromDateTemp  and A.EmployeeAutoId=B.EmployeeAutoId		
		set @FromDateTemp=dateadd(dd,1,@FromDateTemp)
	end	
		--Updates the flag to 1 if the current shift overlaps the previous shift.
		update TA_Tbl_EmployeeShiftId_ForShiftReAllocation set Flag=1 
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_tbl_shift A on A.Shift_Id= ES.CurrentShiftId
		inner join ta_tbl_shift B on B.Shift_Id = ES.PreviousDayShift
		where cast(A.Shift_StartTime as datetime) <= cast(B.Shift_EndTime as datetime) and charindex(''PM'',B.Shift_StartTime)>0 and charindex(''AM'',B.Shift_EndTime)>0
		--Updates the flag to 1 if the current shift overlaps the next day shift.
		update TA_Tbl_EmployeeShiftId_ForShiftReAllocation set Flag=1 
		from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_tbl_shift A on A.Shift_Id= ES.CurrentShiftId
		inner join ta_tbl_shift B on B.Shift_Id = ES.NextDayShift
		where cast(A.Shift_EndTime  as datetime) >= cast(B.Shift_StartTime as datetime) and charindex(''PM'',A.Shift_StartTime)>0 and charindex(''AM'',A.Shift_EndTime)>0
		--select the employees for whom the shift overlaps
		select E.Employee_Code_Id,E.Employee_FirstName,ES.Date from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeAutoId
		where Flag=1 and LoggedInEmployeId = @LoggedInemployeeId
		declare @String varchar(max)
		set @String = (select E.Employee_Code_Id + ''- ('' + (convert(varchar(10),ES.Date,103)) + '') '' + '','' from TA_Tbl_EmployeeShiftId_ForShiftReAllocation ES 
		inner join TA_Tbl_Employee E on E.Employee_Id = ES.EmployeeAutoId
		where Flag=1 and LoggedInEmployeId = @LoggedInemployeeId for xml path(''''))
		SET @String = LEFT(@String, LEN(@String) - 1)
		select @String
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShift]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckShift  
Description : check shift name before insert, is already there or not
Tables Included : TA_Tbl_Shift  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
Proc_TA_CheckShift 151,''test10''
*/  
-- select * from ta_tbl_leveldetails
-- Proc_TA_CheckShift 1,''Testing''
CREATE PROCEDURE [dbo].[Proc_TA_CheckShift]
(
	@companyId int,
	@ShiftName nvarchar(50)
)
AS
BEGIN
    SELECT COUNT(Shift_Name) AS SCount from TA_Tbl_Shift WHERE Shift_Name=@ShiftName
	and Level_Id=cast(@companyId as nvarchar(8))	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckSanctioningPerson]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckSanctioningPerson]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckSanctioningPerson]
	@EmpID as int
AS
BEGIN
	Select count(*) from ta_tbl_employee where Leave_Sanc_Authority=@EmpID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeaveType]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckRestoreLeaveType
Description : check leave type before insert, is already there or not  
Tables Included : TA_Tbl_LeaveType
Created By : Kumuthini.L  
Created On : 5-Feb-2008  
Modified By :  
Modified On :  
*/
CREATE Procedure [dbo].[Proc_TA_CheckRestoreLeaveType]
(        
  @LeaveTypeId INT       
)         
As          
BEGIN        
	SET NOCOUNT ON;
	Declare @LeaveType nVarchar(200)
	Select @LeaveType=Leavetype from TA_Tbl_LeaveType where LeaveType_Id= @LeaveTypeId
	SELECT COUNT(LeaveType_Id) AS LType FROM TA_Tbl_LeaveType WHERE LeaveType = @LeaveType AND LeaveType_Id <> @LeaveTypeId AND IsDeleted = 0
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreEntrance]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreEntrance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name  : Proc_TA_CheckRestoreEntrance 
Description 	: Check Entrance before restore, is already there or not  
Tables Included : TA_Tbl_Entrance
Created By 	: Kumuthini.L  
Created On 	: 8-Feb-2008  
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreEntrance]
(        
	@EntranceId INT
)         
AS  
BEGIN
	SET NOCOUNT ON
	Declare @EntranceName NVARCHAR(50)
	select @EntranceName=Entrance_Name FROM TA_Tbl_Entrance where Entrance_Id=@EntranceId
	SELECT COUNT(Entrance_Id) AS EntranceCount FROM TA_Tbl_Entrance WHERE Entrance_Id<>@EntranceId AND Entrance_Name = @EntranceName         
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReportingPerson]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReportingPerson]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckReportingPerson]
	@EmpID as int
AS
BEGIN
	Select count(*) from ta_tbl_employee where Reporting_To=@EmpID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckreligionType]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckreligionType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_CheckreligionType]
(        
 @ID int        
)         
As        
DECLARE @Isdel INT        
SET @Isdel=0        
 BEGIN 
	/*      
		Select Count(LeaveType_Id)as LType from TA_Tbl_LeavePolicyDetails        
		where LeaveType_Id=@LeaveTypeId     
	*/ 
    select count(ID) as LType from TA_Tbl_Religion 
	where ID=@ID and IsDeleted=0    
 END   
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReligion_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReligion_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_CheckReligion_Insert]
( 
@mode int= 1,
@ID int =0, 
 @Name NVARCHAR(50),
 @Description NVARCHAR(255)
)   
As  
 BEGIN 
 DECLARE @err_message nvarchar(255) 
  if(@mode = 1)
  Begin
  if Exists(SELECT ID as count FROM TA_Tbl_Religion WHERE Name=@Name) 
  begin
SET @err_message = ''Record already Exist''
	RAISERROR (@err_message,0,0)
End
  else
   begin
   INSERT INTO TA_Tbl_Religion(Name,Description,IsDeleted) VALUES (''''+ @Name + '''',''''+ @Description + '''',0)
   end
  End
   if(@mode=2)
  Begin
  if Exists(Select Name as Ltype from TA_Tbl_Religion where ID<>'''' + cast(@ID as nvarchar(20)) +'''' And Name='''' + @Name + '''' )
   begin
SET @err_message = ''Record already Exist''
	RAISERROR (@err_message,0,0)
End
  else
  begin
 UPDATE TA_Tbl_Religion SET Name ='''' +  @Name + '''',Description='''' + @Description + '''' WHERE ID='''' + cast(@ID as nvarchar(20)) + ''''
  end 
  end
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckReferranceReligion]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckReferranceReligion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Rukmnai Devi.P
-- Create date: 12-oct-2011
-- Description:	to check the check boxes.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckReferranceReligion] 
	-- Add the parameters for the stored procedure here
 @ID int 
As          
--DECLARE @Isdel INT          
--SET @Isdel=0          
BEGIN   
	declare @RecCont as bigint
	set @RecCont=(select count(ID)as Rcount from TA_Tbl_religion TR inner join TA_Tbl_Employee TE on TE.Religion =  TR.ID 
					where TR.ID = @ID and TE.IsDeleted=0) 
	set @RecCont=@RecCont + (select count(ID)as Rcount from TA_Tbl_religion TR 
							inner join TA_Tbl_leavetype LT on LT.Religion =  TR.ID 
							where TR.ID = @ID and LT.IsDeleted=0)
	select @RecCont as Rcount  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRawFormat]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRawFormat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckRawFormat  
Description : check raw data format  
Tables Included : TA_tbl_TerminalDatatype  
Created By : Kumuthini.L  
Created On : 13-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckRawFormat](@Rawdataformat varchar(60))
as
 SELECT COUNT(*) FROM TA_tbl_TerminalDatatype   where Raw_Data_Format =@Rawdataformat
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminalDataType]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreTerminalDataType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name : Proc_TA_CheckRestoreTerminalDataType  
Description : Check Terminal Data Type before restoring, is already there or not    
Tables Included : TA_Tbl_TerminalDataType  
Created By : Kumuthini.L    
Created On : 7-Feb-2008    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreTerminalDataType]
(        
  @TerminalDataTypeId INT        
)         
As
BEGIN
	Declare @RawDataFormat nVarchar(50)
	Declare @FileType nVarchar(25)
	Select @RawDataFormat=Raw_Data_Format,@FileType =FileType from TA_tbl_TerminalDatatype where TerminalDatatype_ID=@TerminalDataTypeId
	SELECT COUNT(TerminalDatatype_ID) AS [Count] FROM TA_Tbl_TerminalDataType
	WHERE Raw_Data_Format = @RawDataFormat AND FileType = @FileType AND TerminalDatatype_ID <> @TerminalDataTypeId  AND IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreTerminal]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreTerminal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckRestoreTerminal  
Description : Check Terminal before Restoring, is already there or not    
Tables Included : TA_Tbl_Terminal  
Created By : Kumuthini.L    
Created On : 7-Feb-2008    
Modified By :    
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreTerminal]
(        
	@TerminalId INT  
)         
As        
BEGIN        
	Declare @TerminalReaderId nVarchar(50)
	Declare @TerminalName nVarchar(50)    
	Select @TerminalReaderId=Terminal_ReaderID,@TerminalName=Terminal_Name from TA_Tbl_Terminal where Terminal_Id=@TerminalId
	SELECT COUNT(Terminal_Id) AS [Count] FROM TA_Tbl_Terminal       
	WHERE ((Terminal_ReaderID = @TerminalReaderId) OR (Terminal_Name = @TerminalName)) AND Terminal_Id <> @TerminalId AND IsDeleted = 0
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreReligion]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreReligion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_CheckRestoreReligion]  
(          
  @ID INT 
)           
As
BEGIN
	Declare @Name nVarchar(200)
	Select @Name=Name from TA_Tbl_Religion where ID=@ID 
	SELECT COUNT(ID) AS LType FROM TA_Tbl_Religion WHERE Name = @Name AND ID <> @ID AND IsDeleted = 0             
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckRoute  
Description : check route
Tables Included : TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRoute]     
(      
-- @RouteName NVARCHAR(50),      
 @RouteId int      
)       
As      
DECLARE @Isdel INT      
SET @Isdel=1      
 BEGIN      
   Select Count(RouteId)as RName from TA_Tbl_Transportation_Mapping      
   where RouteId=@RouteId  AND Isdeleted=@Isdel   --And RouteName=@RouteName    
 END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Created by	:	Prabakaran.P
-- Created on	:	05-Jan-10
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplicationChildDetails]
(
@LeaveApplication_Id int,
@auEmpId int
)
AS
BEGIN
SET NOCOUNT ON;
		BEGIN
				update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
				where LeaveApplication_Id = @LeaveApplication_Id
		END
		BEGIN
				Delete from TA_Tbl_LeaveApplication where LeaveApplication_Id = @LeaveApplication_Id
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created by		:	Prabakaran.P
Created on		:	
Modified on		:	03-Mar-08
Modified By		:	A.K.T.MOORTHI
Modified On		:	24-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
	EXEC [Proc_TA_DeleteLeaveApplication] 42, 1

		EXEC [Proc_TA_DeleteLeaveApplication] 159, 1
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication]
(
	@LeaveApplication_Id INT,
	@auEmpId INT
)
AS
BEGIN		
	SET NOCOUNT ON;
	DECLARE @CompOffId BIGINT 
	set @CompOffId= 0
	Declare @RemainingDays NUMERIC(18,1) 
	set @RemainingDays= 0.0
	declare @EmployeeId INT
	declare @NumberOfDays NUMERIC(18, 1)
	DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
	SELECT @EmployeeId = Employee_Id, @NumberOfDays = NumberOfDays FROM TA_Tbl_LeaveApplication
		WHERE LeaveApplication_Id = @LeaveApplication_Id
	INSERT INTO @TblRecord
		SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE ''%:'' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + ''%''
		ORDER BY [Date]
		declare @ValCount as int
		SELECT @ValCount=COUNT(*) FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE ''%:'' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + ''%''
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
		
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@ValCount=2) THEN @RemainingDays + 0.5 else case when (@ValCount>2) THEN CASE 
				WHEN (@NumberOfDays > NoOfDays) THEN NoOfDays
				ELSE (@RemainingDays + @NumberOfDays) end else NoOfDays end END),
				CompOffSatus = (CASE
					WHEN DateToExpired < GETDATE() THEN ''Expired''
					WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN ''Not Taken'' END),
				LeaveApplicationId = case	when @NumberOfDays>0.5 then REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''') 
								else	case	when (select COUNT(Value) from dbo.Split(LeaveApplicationId,'':'') where Value=@LeaveApplication_Id)=2 
								then '':''+CAST(@LeaveApplication_Id AS VARCHAR(20))
												else REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''') 
										end
					end
			WHERE ExtraTime_Id = @CompOffId
			SELECT @NumberOfDays = case when (@ValCount=2) then (@NumberOfDays - 0.5) else (@NumberOfDays - RemainingDays) end FROM TA_Tbl_OverTimeStatus
				WHERE ExtraTime_Id = @CompOffId
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId

		END
	--WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
	--BEGIN
	--	SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
	--	UPDATE TA_Tbl_OverTimeStatus SET
	--		@RemainingDays = RemainingDays,
	--		RemainingDays = (CASE 
	--			WHEN (@NumberOfDays > NoOfDays) THEN (@RemainingDays + @NumberOfDays) - NoOfDays
	--			ELSE (@RemainingDays + @NumberOfDays) END),
	--		CompOffSatus = (CASE
	--			WHEN DateToExpired < GETDATE() THEN ''Expired''
	--			WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN ''Not Taken'' END),
	--		LeaveApplicationId = REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''')
	--	WHERE ExtraTime_Id = @CompOffId
	--	SELECT @NumberOfDays = (@NumberOfDays - RemainingDays) FROM TA_Tbl_OverTimeStatus
	--		WHERE ExtraTime_Id = @CompOffId
	--	UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
	--END
	Delete from TA_Tbl_LeaveApplication WHERE LeaveApplication_Id = @LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplicationExists WHERE LeaveApplicationId = @LeaveApplication_Id
	Delete from TA_Tbl_LeaveApplicationPrintDetails_Eastman WHERE leaveAppID = @LeaveApplication_Id
	--print ''test loop''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteGrade]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteGrade]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteGrade]
		@Type CHAR(1),
		@GradeId INT,
		@GradeIds NVARCHAR(50)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_Grade SET IsDeleted=@DEL WHERE Grade_Id=@GradeId
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Grade SET IsDeleted='' + @DEL + '' WHERE Grade_Id IN  ('' + @GradeIds + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmailLogData]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmailLogData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <16-Feb-2013>
-- Description:	<Delete the Email log data>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmailLogData]
	-- Add the parameters for the stored procedure here
	@Date varchar(25)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	delete from TA_tbl_EmailScheduleStatus where SentDate <= @Date
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualEntry]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualEntry]
(
	@Type CHAR(1),
	@MID int=0,
	@ManualEntryIds NVARCHAR(25)
)
AS 
	DECLARE @Isdel VARCHAR
	SET @Isdel=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
	IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_ManualTimeEntry SET Isdeleted = @Isdel  WHERE ManualTimeEntry_Id=@MID
	END
	ELSE IF (@Type=''C'')
	BEGIN
		SET @Query= ''UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = '' + @Isdel +''  WHERE ManualTimeEntry_Id IN ('' + @ManualEntryIds + '')''
	EXEC (@Query)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLookupData]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLookupData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLookupData]
(
@Type CHAR(1),		
@Id INT=0,
@Ids NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
		BEGIN
			UPDATE TA_Tbl_Lookup
			SET IsDeleted=@del 
			WHERE ID=@Id
		END
ELSE IF (@Type=''C'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_Lookup SET IsDeleted= '' + @del + '' WHERE ID IN (''+ @Ids +'')''
			EXEC (@Query)
		END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLogo]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLogo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Janakaraj>
-- Create date: <Create Date,,26-Nov-07>
-- Description:	<Description,,Inserting CustomerLogo>
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_DeleteLogo]
AS
BEGIN	
		Delete from Ta_Tbl_Branding
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLevelWiseRights]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLevelWiseRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 04-Sep-2010
-- Description:	Deleted Level wise rights.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLevelWiseRights]
	@GroupId as int
AS
delete from TA_Tbl_LevelRights where GroupId=@GroupId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveType]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
created by		:	Manjula.P
Created Date	:	19-Jul-2013
Descriptions	:	Deleting leave types 
*/
CREATE proc [dbo].[Proc_TA_DeleteLeaveType]
(
@EmployeeId int,
@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	delete from ta_tbl_emp_LeaveTypedetails where YearSettingsId=@YearSettingsId and EmployeeId=@EmployeeId
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Leave Policy - Delete
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicy]
	-- Add the parameters for the stored procedure here
@Type CHAR(1),		
@LeavePolicyID INT=0,
@LeavePolicies NVARCHAR(25)
AS
SET NOCOUNT ON;
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
		BEGIN
			SET NOCOUNT ON;
		UPDATE TA_Tbl_LeavePolicy SET IsDeleted=1 WHERE Policy_Id=@LeavePolicyID 
		END
ELSE IF (@Type=''C'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_LeavePolicy SET IsDeleted= 1 WHERE Policy_Id IN (''+ @LeavePolicies +'')''
			EXEC (@Query)
		END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 11-03-2016
-- Description:	Delete manual time entry using On duty ID
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntryForOndutyID]
	@OndutyID as int
AS
BEGIN
	SET NOCOUNT ON;
    delete from Ta_Tbl_ManualTimeEntry where OnDuty_ID=@OndutyID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeesFromTempTable]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeesFromTempTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeesFromTempTable]
(
   @xml xml,
   @loginEmployeeId int
)
AS
BEGIN 
  Declare @Index int
  Set @Index = 0;
   EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	  delete from TA_Tbl_TempShiftAllocation
	  from OpenXML(@Index, ''/DocumentElement/Table'')
	  With (EmployeeAutoId Bigint ''EmployeeAutoId'') as xm 
	  inner join TA_Tbl_TempShiftAllocation TS on TS.EmpID = xm.EmployeeAutoId
	  and TS.LoginEmployeeId = @loginEmployeeId
  Exec sp_xml_removedocument @Index
  select * from TA_Tbl_TempShiftAllocation where LoginEmployeeId=@loginEmployeeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <22-03-2019>
-- Description:	<Deleting employee details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_DeleteEmployeeDetails_EmailScheduler]
@ScheduleID int
AS
BEGIN
	SET NOCOUNT ON;
	Delete from TA_Tbl_EmailScheduled_Employees where ScheduleId=@ScheduleID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeedetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeedetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_DeleteEmployeedetails ''145'',''Restore'' 
Description 	:	Delete Employee  details
Tables Included :	TA_Tbl_Employee, TA_Tbl_EmpChildrenDetails 
*/     
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteEmployeedetails]  
(  
	@Employees NVARCHAR(max), 
	@strType NVARCHAR(50),
	@auditEmpId int,
	@ApplnMode BIT
)  
AS  
BEGIN
	DECLARE @Query NVARCHAR(2000)  
	SET @Query=''''  
	IF (@strType=''TemporaryDelete'')  
	BEGIN  
   		SET @Query =''UPDATE TA_Tbl_Employee SET Isdeleted_Status = 1, IsDeleted= 1 WHERE Employee_Id IN (''+ @Employees +'')''  
		EXEC (@Query)  
	END
	ELSE IF (@strType=''PermanentDelete'')  
	BEGIN  
		-- delete employee bonus leave
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmployeeBonusLeave WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee year closure
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_YearClosure WHERE Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee leave policy details
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee leave policy
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee children details
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee type
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmployeeType WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee category
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmployeeCategory WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee level
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmployeeLevel WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee designation
		SET @Query =''''
		SET @Query =''DELETE FROM  TA_Tbl_EmployeeDesignation WHERE EmployeeID IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
		-- delete employee pay
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_EmployeePay WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query) 
  		-- delete employee Permission
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_Permission WHERE Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)   
  		-- delete employee LeaveApplication
		SET @Query =''''
		SET @Query =''DELETE FROM TA_Tbl_LeaveApplication WHERE Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)  
  		-- delete employee permanentshiftallocation
		SET @Query =''''
		SET @Query =''DELETE FROM ta_Tbl_permanentshiftallocation WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query) 
  		-- delete employee temporaryshiftallocation
		SET @Query =''''
		SET @Query =''DELETE FROM ta_Tbl_temporaryshiftallocation WHERE EmployeeId IN ('' + cast(@Employees as NVARCHAR) + '') ''
  		EXEC(@Query)
  		-- delete employee clk_rawdata
  		SET @Query =''''
		SET @Query =''DELETE FROM ta_Tbl_clk_rawdata where CLK_CARDID in (select distinct SwipeCardNo FROM TA_Tbl_Employee E inner join ta_Tbl_clk_rawdata crd on E.SwipeCardNo=crd.CLK_CARDID WHERE E.Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '')) ''
  		EXEC(@Query)
		-- delete employee Clockdetails
  		SET @Query =''''
		SET @Query =''DELETE FROM ta_Tbl_Clockdetails where CLK_EMPID in (select distinct SwipeCardNo  FROM TA_Tbl_Employee E  inner join ta_Tbl_Clockdetails cd on E.SwipeCardNo=cd.CLK_EMPID WHERE E.Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '')) ''
  		EXEC(@Query)
  		-- delete employee processeddata
  		SET @Query =''''
		SET @Query =''DELETE FROM ta_Tbl_processeddata where Employee_Code_ID in (select distinct SwipeCardNo FROM  TA_Tbl_Employee E inner join ta_Tbl_processeddata pd  on E.SwipeCardNo=pd.Employee_Code_ID WHERE E.Employee_Id IN ('' + cast(@Employees as NVARCHAR) + '')) ''
  		EXEC(@Query)
		-- delete employee
		SET @Query =''''
   		SET @Query =''DELETE FROM TA_Tbl_Employee WHERE Employee_Id IN (''+ @Employees +'')''  
		EXEC (@Query)
	END
	ELSE IF (@strType=''Restore'')  
	BEGIN  
   		SET @Query =''UPDATE TA_Tbl_Employee SET Isdeleted_Status = 0, IsDeleted= 0 WHERE Employee_Id IN (''+ @Employees +'')''  
		EXEC (@Query)
	END
  	IF(@ApplnMode = 0)
	BEGIN
		/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
		UPDATE TA_Tbl_Employee SET
			Isdeleted = 1,
			--Report_Exclude = 1,
			Employee_Status = 0,
			InActiveDate = DATEADD(D, 1, DateOfJoining)
		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> ''18000000'' ) AND
			Employee_Code_Id <> ''18000000'' AND ISNULL(InActive_Status, 0) = 0
		/* End */
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEntranceDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEntranceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEntranceDetails]
(
@Type CHAR(1),		
@entranceId INT=0,
@Entrances NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
		BEGIN
			UPDATE TA_Tbl_Entrance SET Isdeleted=@del WHERE Entrance_Id=@entranceId
		END
ELSE IF (@Type=''C'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_Entrance SET IsDeleted= '' + @del + '' WHERE Entrance_Id IN (''+ @Entrances +'')''
			EXEC (@Query)
		END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpNameGroupPolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmpNameGroupPolicy]     
/****************************************************************************************/          
-- Name    : Proc_TA_DeleteEmpNameGroupPolicy         
-- Desc    : To delete the enties in TA_Tbl_TempGroupPolicyAllocation          
-- Company : Angler Technologies          
-- Author  : P.Santhosh Raj          
-- Date    : 25-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/   
(      
@Type CHAR,      
@EmpId int,    
@loginEmployeeId int      
)      
AS      
BEGIN      
 SET NOCOUNT ON;      
IF (@Type=''I'')      
BEGIN      
 Delete FROM TA_Tbl_TempGroupPolicyAllocation Where EmpID=@EmpId and LoginEmployeeId = @loginEmployeeId       
END      
ELSE IF (@Type=''A'')      
BEGIN      
 Delete FROM TA_Tbl_TempGroupPolicyAllocation Where LoginEmployeeId = @loginEmployeeId       
END      
END      
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpName]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_DeleteEmpName  
Description : Delete Employee name
Tables Included : TA_Tbl_TempShiftAllocation 
Created By : Arun vinoth	  
Created On : 10 Aug 07 
Modified By :  
Modified On :  
*/   
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmpName]
(  
	@Type CHAR,
	@EmpId int,
	@loginEmployeeId int
)  
AS  
BEGIN  
	SET NOCOUNT ON;  
	IF (@Type=''I'')  
	BEGIN  
		Delete FROM TA_Tbl_TempShiftAllocation Where EmpID=@EmpId and LoginEmployeeId = @loginEmployeeId   
	END  
	ELSE IF (@Type=''A'')  
	BEGIN  
		Delete FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @loginEmployeeId   
	END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CounShift]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CounShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_Ta_CounShift] (@ShiftId int)
AS
	BEGIN
		SELECT COUNT(*) FROM TA_Tbl_Shift where Shift_Id=@ShiftId and Isdeleted=1
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CountTotInAndOutPunches]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CountTotInAndOutPunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 14:24PM>
-- Description:	<Count the total number of in and out punches>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CountTotInAndOutPunches]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(50),
	@strOutDateTime varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT Count(*) AS Count FROM TA_Tbl_ClockDetails 
	WHERE (Clk_InDate+Clk_InTime) > cast(@strOutDateTime as datetime) AND (Clk_InDate+Clk_InTime) < cast(@strOutDateTime as datetime) 
	AND Clk_EmpId = @inClk_EmpId  AND Clk_OutDate IS NULL AND IsVoid = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountTitle]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountTitle]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : [Proc_TA_CountTitle]    
Description : counting total title   
Tables Included : TA_tbl_Employee    
Created By : Arun vinoth    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE  procedure [dbo].[Proc_TA_CountTitle]
(@Title INT)
as
--select count(*) from TA_tbl_Employee where Designation_Id=@Title and isdeleted=0
select count(*) from TA_tbl_EmployeeDesignation where DesignationID=@Title
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternOverlapping]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternOverlapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_CheckShiftPatternOverlapping ''125'',''106''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftPatternOverlapping]
	@Shift1ID as int,
	@Shift2ID as int
AS
BEGIN
 set nocount on;
		declare @Shift1StartTime as dateTime
		declare @Shift1EndTime as dateTime
		declare @Shift2StartTime as dateTime
		declare @Shift2EndTime as dateTime
		declare @Flag as int
		declare @CheckPM as int
		declare @checkAM as int
		set @Flag = 0;
		declare @Shift1Name as varchar(5)
		declare @Shift2Name as varchar(5)
		set @Shift1Name = ''''
		set @Shift2Name = ''''
		select @CheckPM = charindex(''PM'',shift_starttime), @checkAM = charindex(''AM'',shift_Endtime) from ta_tbl_shift where shift_id=@Shift1ID
		--select @CheckPM, @checkAM
		if (@CheckPM>0 and @checkAM>0)
		Begin
			select @Shift2StartTime=shift_starttime,@Shift2EndTime=shift_endtime, @Shift1Name=Shift_ShortName from ta_tbl_shift where shift_id = @Shift1ID 			
		    --select @Shift2StartTime,@Shift2EndTime
			select @Flag =count(*), @Shift2Name=Shift_ShortName from ta_tbl_shift  where Shift_ID=@Shift2ID and ((dateadd(day,1,cast(shift_starttime as datetime))  between @Shift2StartTime and dateadd(day,1,@Shift2EndTime) )) group by Shift_ShortName
			--select @Flag =count(*), @Shift1Name=Shift_ShortName from ta_tbl_shift  where @Shift1ID=@Shift1ID and ((cast(shift_starttime as datetime)  between @Shift2StartTime and @Shift2EndTime ) or (cast(shift_Endtime as datetime)  between @Shift2StartTime and @Shift2EndTime  )) group by Shift_ShortName
		End
		select @Flag as ShiftOverLapping, @Shift1Name as Shift1,@Shift2Name as Shift2
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitleMapping]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTitleMapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTitleMapping]  
  @Id INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=1  
 BEGIN  
  UPDATE TA_Tbl_TitleMapping SET IsDeleted=@DEL WHERE Id=@Id
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLookup]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delLookup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_delLookup]  
(   
	@lookupID int  
)  
as  
begin  	
	declare @checkFlag  int  
	set @checkFlag = 0  
	declare @recCount as int  
	declare @recCount1 as int
	declare @recCount2 as int
	declare @recCount3 as int
	--checking in lookup mapping
	set @recCount = (select count(*) from ta_tbl_lookup where Parent=@lookupID)  
	--checking in Employee for City mapping
	set @recCount1 = (select count(*) from ta_tbl_Employee where Native_Place=@lookupID) 
	--checking in Employee for State mapping
	set @recCount2 = (select count(*) from ta_tbl_Employee where State=@lookupID) 
	--checking in Employee for Country mapping 
	set @recCount3 = (select count(*) from ta_tbl_Employee where Country=@lookupID)  
	if (@recCount>0)  
		Begin  
			set @checkFlag=1  
		End  
	else if (@recCount1>0)  
		Begin  
			set @checkFlag=1  
		End     
	else if (@recCount2>0)  
		Begin  
			set @checkFlag=1  
		End 
	else if (@recCount3>0)  
		Begin  
			set @checkFlag=1  
		End  
	select @checkFlag as checkFlag  
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftId]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftId]
		@Type CHAR(1),
		@ShiftId  INT,
		@ShiftIds varchar(200)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_Shift SET IsDeleted=@DEL WHERE Shift_Id=@ShiftId
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Shift SET IsDeleted='' + @DEL + '' WHERE Shift_Id IN  ('' + @ShiftIds + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShift]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteShift]
(@ShiftId int,
 @auditEmpId int)
as
BEGIN
	UPDATE TA_Tbl_Shift SET Isdeleted=1,Emp_ID =@auditEmpId WHERE Shift_Id=@ShiftId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalMapping]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminalMapping]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminalMapping]
		@TerminalMapId INT
	AS
	DECLARE @DEL BIT
	SET @DEL=1
	BEGIN
		UPDATE TA_Tbl_TerminalMapping SET IsDeleted=@DEL
		 WHERE TerMap_Id=@TerminalMapId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminalDatatype]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminalDatatype]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminalDatatype]
(
@Type CHAR(1),
@TerminalDatatypeId INT,
@TerminalDataTypes NVARCHAR(25)
)
AS
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_tbl_TerminalDatatype SET IsDeleted=@del WHERE TerminalDatatype_ID=@TerminalDatatypeId
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query= ''UPDATE TA_tbl_TerminalDatatype SET IsDeleted = '' + @DEL + '' WHERE TerminalDatatype_ID IN ('' + @TerminalDataTypes + '')''
	             EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTerminal]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTerminal]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTerminal]
		@Type CHAR(1),
		@TerminalId INT=0,
		@Terminals NVARCHAR(25)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=0
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_Terminal SET IsDeleted=@DEL WHERE Terminal_Id=@TerminalId
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query= ''UPDATE TA_Tbl_Terminal SET IsDeleted = '' + @DEL + '' WHERE Terminal_Id IN ('' + @Terminals + '')''
	EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTempShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Manikandan.R
-- Create date: 30-07-2014 04:19
-- Description:	Delete the records in temporary shift allocation
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTempShiftAllocation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DELETE FROM TA_Tbl_TempShiftAllocation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOtType]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteOtType] 
	@OtTypeID as int,	
	@EmpId as int
AS
BEGIN	
	update  TA_Tbl_OtType set IsDeleted=1,EmpID=@EmpID where OtTypeID=@OtTypeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOTRoundoffSettings]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOTRoundoffSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		christopher
-- Create date:19-05-09
-- Description:	deleting ot round off settings before inserting or updating
-- ============================================
Create PROCEDURE [dbo].[Proc_TA_DeleteOTRoundoffSettings]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int 
AS
BEGIN
	SET NOCOUNT ON;
    delete  from TA_Tbl_OTRoundoffSettings where ShiftSettingId=@shiftSettingId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProject]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteProject]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani.P>
-- Create date: <06Jan2020>
-- Description:	<Delete the project info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteProject]
	@ProjectId bigint, @UserId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	IF EXISTS(select isnull(Project_Id,0) from TA_Tbl_Project where Project_Id = @ProjectId)
	begin
		update TA_Tbl_Project set IsDeleted = 1 where Project_Id = @ProjectId
	End
	

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteProgressDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteProgressDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteProgressDetails]
	@ProgressTaskID bigint
AS
BEGIN
	SET NOCOUNT ON;
	Delete from Ta_tbl_TaskProgressDetails where TaskDetailID=@ProgressTaskID
END
' 
END
GO
/****** Object:  View [dbo].[OrderByEmployeeCodeId]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[OrderByEmployeeCodeId]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[OrderByEmployeeCodeId]
AS
select cast(substring(Employee_Code_Id,Len(Employee_Code_Id) - Len(Replace(Employee_Code_Id, ''0'', ''''))+1,
len(Employee_Code_Id))as int)as Order1,
Employee_Code_Id,
cast(Len(Employee_Code_Id) - Len(Replace(Employee_Code_Id, ''0'', ''''))as int)as Order2
from ta_tbl_employee where Employee_Code_Id like(''0%'')
'
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_GetProcessedDataDetailsForPayrollProcess  
Description : get process data detail for payroll process  
Tables Included : TA_Tbl_ProcessedData  
Created By : Kumuthini.L  
Created On : 05-Aug-2007  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_GetProcessedDataDetailsForPayrollProcess]
(
    @EmpId NVARCHAR(20),
    @StartDate DateTime,   
    @EndDate DateTime
)
 AS
SELECT * FROM TA_Tbl_ProcessedData P 
INNER JOIN TA_Tbl_Employee E  ON E.SwipeCardNo = P.Employee_Code_Id
where E.Swipecardno = @EmpId and P.Date between @StartDate and @EndDate
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetEmployeeDetails]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_GetEmployeeDetails]       
-- Proc_GetEmployeeDetails ''EIT02'',1.2,1.2      
 -- Add the parameters for the stored procedure here      
 @EmpId nvarchar(100)=NULL,      
 @PresentDays NUMERIC(18,1)=NULL,      
 @Difference_Days NUMERIC(18,1)=NULL      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
    -- Insert statements for procedure here      
 IF @EmpId <> ''0''      
  BEGIN      
    UPDATE TA_Tbl_AttendenceData SET PresentDays=@PresentDays,Difference_Days=@Difference_Days      
    WHERE EmpId=@EmpId      
   END      
  ELSE   
  BEGIN     
 SELECT EmpId,PresentDays,OD,EL,CL,SL,LOP_Absent,Difference_Days FROM TA_Tbl_AttendenceData      
 END  
END ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Get_VehicleDetailsByRouteId]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Get_VehicleDetailsByRouteId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_Get_VehicleDetailsByRouteId  
Description : get vehicle details by route id  
Tables Included : TA_Tbl_Transportation_Vehicle, TA_Tbl_Transportation_Mapping  
Created By : Arun Vinoth  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_Get_VehicleDetailsByRouteId] (@ID int) As  
Select A.VehicleNo,A.VehicleId from TA_Tbl_Transportation_Vehicle A, TA_Tbl_Transportation_Mapping B  
Where A.VehicleId = B.VehicleId AND B.RouteId = @Id 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_editLevel]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_editLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_editLevel  
Description : edit level details  
Tables Included : ta_tbl_level, TA_Tbl_ParentIDs 
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_editLevel] 
(
	@lid int
)
AS
BEGIN
	SET NOCOUNT ON
	--DECLARE @lelid int, @lelName nvarchar(100)
	--SELECT @lelName = levelname FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
	--INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName ) VALUES (@lid,@lelName)
	--SELECT @lelid = parentlevelID FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
	--if (@lelid >0)
	--BEGIN
	--	EXEC dbo.proc_editLevel @lelid
	--END	
	--Commented by Manikandan.rr on 05-Feb-2020 due to performance issue.	
	;with cte
	as
	(
		SELECT levelid,parentLevelID as id, levelname name FROM ta_tbl_level WHERE isdeleted=0 and levelid = @lid
		union all
		SELECT l.levelID,l.parentLevelID,l.levelName from cte c
		inner join ta_tbl_level  l on l.levelID=c.id 
	)
	INSERT INTO TA_Tbl_ParentIDs
	select levelID,name,id from cte
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_CheckNewsInYearSettings]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_CheckNewsInYearSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- SELECT * FROM TA_Tbl_YearSettinG WHERE ISACTIVE=1
-- Proc_CheckNewsInYearSettings ''2012-04-01'',''2013-04-01''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_CheckNewsInYearSettings]
	-- Add the parameters for the stored procedure here
	@Fromdate nvarchar(50),
	@ToDate nvarchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @YSFromDate datetime
    select @YSFromDate=Fromdate from TA_Tbl_YearSetting where IsActive=1
    Declare @YSToDate datetime
    select @YSToDate=TODATE from TA_Tbl_YearSetting where IsActive=1
    Declare @result nvarchar(20)
    set @result=''''
    Declare @result1 nvarchar(20)
    set @result1=''''
     if(@Fromdate >= @YSFromDate and @Fromdate <= @YSToDate)
		begin
			set @result=''True''
		end
	if(@ToDate >= @YSFromDate and @ToDate <= @YSToDate)
		begin
			set @result1=''True''
		end
	if(@result=''True'' and @result1=''True'')
		begin
			select 1 as RESULT
		end
	else 
		begin
			select 0 as RESULT
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[InsertMariaLogsInToReportsList]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertMariaLogsInToReportsList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[InsertMariaLogsInToReportsList]
	@cDate numeric(18,0),
	@CLK_ID varchar(20),
	@IO varchar(20),
	@nReaderIdn varchar(20),
	@nEventIdn varchar(20)
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @ORGDATE DATETIME 
	DECLARE @strUniqueKey NVARCHAR(255)
	set @ORGDATE=dateadd(SS,@cDate,''01/01/1970 05:30'')
	set @strUniqueKey=@CLK_ID+@IO
	--4098	VERIFY_SUCCESS_ID_FINGERPRINT
	--4100	VERIFY_SUCCESS_ID_FACE
	--4865	IDENTIFY_SUCCESS_FINGERPRINT
	--4867	IDENTIFY_SUCCESS_FACE	
	if(@nEventIdn in(4100,4865,4867,4865,4098))
	begin
		IF NOT EXISTS(SELECT nIndex FROM tb_reportslist where dtDateTime=@ORGDATE and nDeviceID=@nReaderIdn and nEvent=@nEventIdn and nUserID=@CLK_ID and nTNAEvent=@IO and strUniqueKey=@strUniqueKey)
		BEGIN
			INSERT INTO dbo.tb_reportslist(dtDateTime,nDeviceID,nEvent,nUserID,nTNAEvent,strUniqueKey) 
			SELECT @ORGDATE,@nReaderIdn,@nEventIdn,@CLK_ID,@IO, @strUniqueKey 					
		END
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetDatetime]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDatetime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Batch submitted through debugger: SQLQuery6.sql|15|0|C:\Users\karthikeyan.r\AppData\Local\Temp\~vsE8C2.sql
-- =============================================
-- Author:		<Author,,Karthikeyan.R>
-- Create date: <28-04-2015,3.45 PM,>
-- Description:	<Description,,>
-- GetDatetime ''Daily'',0,0
-- =============================================
CREATE PROCEDURE [dbo].[GetDatetime] 
	-- Add the parameters for the stored procedure here
	@ScheduleBasis varchar(20),
	@DateFrom int=null,
	@DateTo int=null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @Month varchar(20)
	declare @Year varchar(20)
	set	@Month = MONTH(getdate())
	set @Year=YEAR(getdate())
    -- Insert statements for procedure here
    declare @FromDate varchar(20)
    declare @ToDate varchar(20)
    if(@ScheduleBasis=''Monthly'')
		begin
			if (@Month != 1)
			begin
				declare @preMonth varchar(20)
				declare @PreYear varchar(20)
				set @preMonth=(select dateadd(month, -1,GETDATE()))
				set @Month= MONTH(@preMonth)
				if (@DateFrom <= 28)
				begin
					set	@FromDate = @Month + ''/'' + CONVERT(varchar(10),@DateFrom) + ''/'' + @Year
				end
				else
				begin
					if (@Month = 4 or @Month = 6 or @Month  = 9 or @Month  = 11)
						begin
							if (@DateFrom = 31)
								begin
                                       set @FromDate = @Month + ''/'' + ''30'' + ''/'' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 = 0)
						begin
							if (@DateFrom > 29)
								begin
									set @FromDate = @Month + ''/'' + ''29'' + ''/'' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 != 0)
						begin
							set @FromDate = @Month + ''/'' + ''28'' + ''/'' + @Year
						End
					else
						begin
							set	@FromDate = @Month + ''/'' + CONVERT(varchar(10),@DateFrom) + ''/'' + @Year
						end
				end
			--To Date
			if (@DateTo <= 28)
				begin
					set @ToDate = @Month + ''/'' + CONVERT(varchar(10),@DateTo) + ''/'' + @Year
				end
			else
				begin
					if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
						begin
                            if (@DateTo = 31)
								begin
									set @ToDate = @Month + ''/'' + ''30'' + ''/'' + @Year
								end
						end
					else if (@Month = 2 and @Month % 4 = 0)
                        begin
                            if (@DateTo > 29)
								begin
									set @ToDate = @Month + ''/'' + ''29'' + ''/'' + @Year
								end
                        end
					else if (@Month = 2 and @Month % 4 != 0)
                        begin
                           set @ToDate = @Month + ''/'' + ''28'' + ''/'' + @Year
                        end
					else
						begin
                            set @ToDate = @Month + ''/'' + CONVERT(varchar(10),@DateTo) + ''/'' + @Year
                        end
				end
		end                            
		else
			begin
				set @preMonth=(select dateadd(month, -1,GETDATE()))
				set @PreYear=(select dateadd(YEAR, -1,GETDATE()))
				set @Month= MONTH(@preMonth)
				set @Year= YEAR(@PreYear)
			--From Date
				if (@DateFrom <= 28)
					begin
						set @FromDate = @Month + ''/'' + CONVERT(varchar(10),@DateFrom) + ''/'' + @Year
					end
				else
					begin
						if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
							begin
                                if (@DateFrom = 31)
									begin
										set @FromDate = @Month + ''/'' + ''30'' + ''/'' + @Year
									end
                            end
						else if (@Month = 2 and @Month % 4 = 0)
							begin
                                if (@DateFrom > 29)
									begin
										set @FromDate = @Month + ''/'' + ''29'' + ''/'' + @Year
									end
                            end
						else if (@Month = 2 and @Month % 4 != 0)
                            begin
                                set @FromDate = @Month + ''/'' + ''28'' + ''/'' + @Year
                            end
						else
							begin	
                               set @FromDate = @Month + ''/'' + CONVERT(varchar(10),@DateFrom) + ''/'' + @Year
                            end
					end
						--To Date
                        if (@DateTo <= 28)
							begin
								set @ToDate = @Month + ''/'' + CONVERT(varchar(10),@DateTo) + ''/'' + @Year
							end
                        else
							begin
								if (@Month = 4 or @Month = 6 or @Month = 9 or @Month = 11)
									begin
										if (@DateTo = 31)
											begin
												set @ToDate = @Month + ''/'' + ''30'' + ''/'' + @Year
											end
									end
								else if (@Month = 2 and @Month % 4 = 0)
									begin
										if (@DateTo > 29)
											begin
												set @ToDate = @Month + ''/'' + ''29'' + ''/'' + @Year
											end
									end
								else if (@Month = 2 and @Month % 4 != 0)
									begin
										set @ToDate = @Month + ''/'' + ''28'' + ''/'' + @Year
									end
								else
									begin
										set  @ToDate = @Month + ''/'' + CONVERT(varchar(10),@DateTo) + ''/'' + @Year
									end
							end
			end
		end
	else if(@ScheduleBasis=''Daily'')
		begin
			--updated previous day logic on 10-July-2019 02:06 PM by Manikandan.R
			declare @Date1 varchar(20)
			set @Month=RIGHT(''0''+CAST(MONTH(DATEADD(d,-1,GETDATE())) AS varchar(2)),2)
			set @Year=(YEAR(DATEADD(d,-1,GETDATE())))
			set @Date1=RIGHT(''0''+CAST(DAY(DATEADD(d,-1,GETDATE())) AS varchar(2)),2)
			set @FromDate=@Year + ''-'' + @Month + ''-'' + @Date1
			set @ToDate=@Year + ''-'' + @Month + ''-'' + @Date1
		end
	else
		begin
			select 1
		end
			DECLARE @dateFormat as int
			DECLARE @date as nvarchar(25)
			declare @FromDate1 varchar(25)
			declare @ToDate1 varchar(25)
			SET @FromDate1=@FromDate
			set @ToDate1=@ToDate
			SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
			IF(@date=''dd/MM/yyyy'')
				BEGIN
					SET @FromDate = CONVERT(varchar, @FromDate1, 103)
					SET @ToDate = CONVERT(varchar, @ToDate1, 103)
				END
			ELSE IF(@date=''MM/dd/yyyy'')
				BEGIN
					SET @FromDate = CONVERT(VARCHAR, @FromDate1, 101)
					SET @ToDate = CONVERT(VARCHAR, @ToDate1, 101)
				END
			ELSE
				BEGIN
					SET @FromDate = CONVERT(VARCHAR, @FromDate1, 106)
					SET @ToDate = CONVERT(VARCHAR, @ToDate1, 106)
				END
			select @FromDate as FromDate,@ToDate as ToDate
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[InsertIrisLogsFromDevice]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertIrisLogsFromDevice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[InsertIrisLogsFromDevice]
	@LogData XML = NULL,
	@ipAddress varchar(30),
	@TerminalID varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @local_LogData XML = @LogData
	DECLARE @XMLParams INT
	
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LogData	
			Create table #TempIrisLogs
			(
				AdditionalData varchar(max),
				EventType  varchar(max),
				Info varchar(max),
				LogUID int,
				SubjectUID varchar(max),
				Timestamp datetime
			)
			insert into #TempIrisLogs
			SELECT	AdditionalData,
					EventType,
					Info,
					LogUID,
					SubjectUID,
					Timestamp
					FROM OPENXML (@XMLParams, ''/DocumentElement/IrisLog_Table'', 2) WITH 
					(
						AdditionalData varchar(max),
						EventType  varchar(max),
						Info varchar(max),
						LogUID int,
						SubjectUID varchar(max),
						Timestamp datetime
					) Tbl where SubjectUID is not null and AdditionalData=''Allowed'' and EventType=''Recognition''
			--select * from tb_reportslist
			insert into tb_reportslist (dtDateTime,nDeviceID,nEvent,nUserID,nTNAEvent,strUniqueKey,ipAddress,LogUID)
			select	convert(datetime,t1.Timestamp)+CONVERT(datetime,''05:30''),
					@TerminalID,
					case when t1.EventType=''Recognition'' and t1.AdditionalData=''Allowed'' then 55 else 0 end,  
					t1.SubjectUID,
					CASE WHEN SUBSTRING(Info,0,CHARINDEX(''/'',Info))=''In'' then 1
						 WHEN SUBSTRING(Info,0,CHARINDEX(''/'',Info))=''Out'' then 2
						 WHEN SUBSTRING(Info,0,CHARINDEX(''/'',Info))=''Leave'' then 3
						 WHEN SUBSTRING(Info,0,CHARINDEX(''/'',Info))=''Return'' then 4
						 else 0
					END,
					RTRIM(lTrim(Info +''-''+ AdditionalData)),
					@ipAddress,
					t1.LogUID
			FROM #TempIrisLogs t1 
			LEFT JOIN tb_reportslist t2 on convert(datetime,t1.Timestamp)+CONVERT(datetime,''05:30'') = t2.dtDateTime and t1.SubjectUID = t2.nUserID 
			WHERE t2.dtDateTime is null and convert(datetime,t1.Timestamp)+CONVERT(datetime,''05:30'') <= getdate()
			and t1.AdditionalData=''Allowed''
			--SELECT * FROM tb_reportslist
		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Insert_Update_CustomFormatForExportData]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Insert_Update_CustomFormatForExportData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name : Insert_Update_CustomFormatForExportData  
Description : inserts or updates the custom format for export data
Tables Included : TA_ExportData_FieldData  
Created By : Sashma
Created On : 02-Apr-2011
*/  
CREATE PROCEDURE [dbo].[Insert_Update_CustomFormatForExportData]
(
 @OptionType varchar(50),
 @DateFomat varchar(50),
 @TimeFormat varchar(50),	
 @DateTimeFormat varchar(50),
 @XMLRootTag varchar(50),
 @XMLFirstChildTag varchar(50),
 @DataType varchar(50),
 @CompanyID int
)
AS
BEGIN
  --Checks whether the custom format for the particular option type exists or not.
  --If exists inserts the custom format else updates the custom format based on option type.
  if exists(select OptionType from TA_ExportData_CustomFormat where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID)
	  BEGIN
		 update TA_ExportData_CustomFormat set 
		 DateFormat=@DateFomat,TimeFormat=@TimeFormat,DateTimeFormat=@DateTimeFormat,XML_RootTag=@XMLRootTag,XML_FirstChildTag=@XMLFirstChildTag
		 where OptionType=@OptionType and DataType=@DataType and CompanyID=@CompanyID
	  END
  else
	  BEGIN 
	     insert into TA_ExportData_CustomFormat values(@OptionType,@DateFomat,@TimeFormat,@DateTimeFormat,@XMLRootTag,@XMLFirstChildTag,@DataType,@CompanyID)
	  END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EditDeleteImportErrorData]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EditDeleteImportErrorData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-Apr-2017
-- Description:	
--[Proc_TA_EditDeleteImportErrorData] ''D'',14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EditDeleteImportErrorData]
	-- Add the parameters for the stored procedure here
	@tag char(1),
	@id bigint ,
	@Emp_FirstName nvarchar(50) = null,
	@Emp_MiddleName  nvarchar(50)= null,
	@Emp_LastName nvarchar(50)= null,
	@Father_Name nvarchar(50)= null,
	@Mother_Name nvarchar(50)= null,
	@DateOfBirth nvarchar(20)= null,
	@DateOfBirth_Record nvarchar(20)= null,
	@Blood_Group nvarchar(10)= null,
	@Email_Id nvarchar(100) = null,
	@Contact_Address nvarchar(MAX)= null,
	@Permanent_Address nvarchar(MAX)= null,
	@Phone_Number nvarchar(50)= null,
	@Mobile_Number nvarchar(50)= null,
	@Gender nvarchar(10)= null,
	@Marital_Status nvarchar(10)= null,
	@Nationality nvarchar(50)= null,
	@Religion nvarchar(50)= null,
	@Personal_EmailID nvarchar(100)= null,
	@Passport_No nvarchar(50)= null,
	@Passport_ExpiryDate nvarchar(20)= null,
	@Visa_No nvarchar(50)= null,
	@Visa_ExpiryDate nvarchar(20)= null,
	@Employee_Code nvarchar(50)= null,
	@DateOfJoining nvarchar(20)= null,
	@Qualification_joiningtime nvarchar(50)= null,
	@Qualification_Employement nvarchar(50)= null,
	@CompOff_Eligible nvarchar(5)= null,
	@OT_Eligible nvarchar(5)= null,
	@Report_Exclude nvarchar(5)= null,
	@Employee_Status nvarchar(5)= null,
	@IsDeleted nvarchar(5)= null,
	@Hostel nvarchar(5)= null,
	@Designation nvarchar(200)= null,
	@Grade nvarchar(50)= null,
	@GradeNo nvarchar(50)= null,
	@Employee_Type nvarchar(100)= null,
	@Employee_Category nvarchar(100)= null,
	@BasicSalary nvarchar(50)= null,
	@Level1 nvarchar(100)= null,
	@Level2 nvarchar(100)= null,
	@Level3 nvarchar(100) = null,
	@Level4 nvarchar(100)= null,
	@Level5 nvarchar(100)= null,
	@Level6 nvarchar(100)= null,
	@Level7 nvarchar(100)= null,
	@Level8 nvarchar(100)= null,
	@Level9 nvarchar(100)= null,
	@Level10 nvarchar(100)= null
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@tag=''M'')
		BEGIN
			update TA_Tbl_ImportMasterError set Emp_FirstName=@Emp_FirstName ,Emp_MiddleName=@Emp_MiddleName  ,Emp_LastName=@Emp_LastName ,Father_Name=@Father_Name ,Mother_Name=@Mother_Name ,DateOfBirth=@DateOfBirth ,DateOfBirth_Record=@DateOfBirth_Record ,Blood_Group=@Blood_Group ,Email_Id=@Email_Id,Contact_Address=@Contact_Address ,Permanent_Address=@Permanent_Address ,Phone_Number=@Phone_Number ,Mobile_Number=@Mobile_Number ,Gender=@Gender ,Marital_Status=@Marital_Status ,Nationality=@Nationality ,Religion=@Religion,Personal_EmailID=@Personal_EmailID ,Passport_No=@Passport_No ,Passport_ExpiryDate=@Passport_ExpiryDate ,Visa_No=@Visa_No ,Visa_ExpiryDate=@Visa_ExpiryDate ,Employee_Code=@Employee_Code ,DateOfJoining=@DateOfJoining ,Qualification_joiningtime=@Qualification_joiningtime ,Qualification_Employement =@Qualification_Employement,CompOff_Eligible=@CompOff_Eligible ,OT_Eligible=@OT_Eligible ,Report_Exclude=@Report_Exclude ,Employee_Status=@Employee_Status ,IsDeleted=@IsDeleted ,Hostel=@Hostel ,Designation=@Designation ,Grade=@Grade ,GradeNo=@GradeNo ,Employee_Type=@Employee_Type ,Employee_Category=@Employee_Category ,BasicSalary=@BasicSalary ,Level1=@Level1 ,Level2=@Level2 ,Level3=@Level3 ,Level4=@Level4 ,Level5=@Level5 ,Level6=@Level6 ,Level7=@Level7 ,Level8=@Level8 ,Level9=@Level9 ,Level10=@Level10 where id=@id
		END
	ELSE IF(@tag=''D'')
	BEGIN
		delete from TA_Tbl_ImportMasterError where id=@id
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeLeaveDetailsByDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	Proc_TA_EmployeeLeaveDetailsByDate    
Description 	:	Selecting the Leave Details of the particular Employee and Date
Tables Included :	TA_Tbl_LeaveApplication
Created By 	:	Kumuthini.L    
Created On 	:	21-Jan-09
Modified By 	:	
Modified On 	:	
*/
CREATE   Procedure [dbo].[Proc_TA_EmployeeLeaveDetailsByDate]              
(               
   @EmployeeId int,
   @LeaveDate nVarchar(20)             
)               
AS                     
BEGIN
SET NOCOUNT ON;
 SELECT la.LeaveType_id,la.Type,la.Leave_FromDate,la.Leave_ToDate,la.Leave_SessionFrom,la.Leave_SessionTo FROM TA_Tbl_LeaveApplication la where la.Employee_Id = @EmployeeId AND la.Leave_FromDate <= @LeaveDate and la.Leave_ToDate >= @LeaveDate and la.Status = ''Approved'' and la.IsDeleted = 0
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeProcessBonusLeave]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeProcessBonusLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_EmployeeProcessBonusLeave]
@EmployeeSwipeCardNo nvarchar(20),
@FromDate datetime,
@ToDate datetime
AS
BEGIN
SET NOCOUNT ON;
	select count(PD.Employee_Code_Id) as BonusLeaveCount,PD.Employee_Code_Id from ta_tbl_processeddata PD 
	where PD.status=''BL'' and PD.Employee_Code_Id=@EmployeeSwipeCardNo
	and Date between @FromDate and @ToDate Group by PD.Employee_Code_Id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delUserGroup]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delUserGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- Create date: 18-August-2007
-- Description:	Delete User Group
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_delUserGroup] 
@groupId int,
@opr varchar(1)
AS
BEGIN
	if (@opr=''C'')
		Begin
			select count(*) as recCount from ta_tbl_employee where userGroup_Id = @groupId
		End
	else
		Begin
			update ta_tbl_usergroup set isDeleted=1 where groupId=@groupId
			update ta_tbl_userrights set isDeleted=1 where groupId=@groupId
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_Proc_checkGroupName]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_Proc_checkGroupName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
	Created on : 11 August 2007
	Created by : Senthil
	Descripttion : Checking groupname for duplication
*/
CREATE procedure [dbo].[TA_Tbl_Proc_checkGroupName]
(
	@groupName as nvarchar(100)
)
as
Begin
	select count(*) as recCount from ta_tbl_userRights where groupName=@groupName
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 09-01-2015
-- Description:	To calculate the physical work hours
-- =============================================
-- select * from TA_Tbl_ClockDetails where clk_date=''2014-09-01'' and clk_empid=''788''
-- 300+51+120+39=351+159=510
-- Proc_TA_CalculatePhysicalWorkHoursForService ''789'',''2015-01-02 00:00:00.000''
CREATE PROCEDURE [dbo].[Proc_TA_CalculatePhysicalWorkHoursForService]
	-- Add the parameters for the stored procedure here
	@inSwipeCardNo varchar(50),
	@Date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @Start int
	Declare @TotalRecord int
	Declare @strInDateTime datetime
	declare @strOutDateTime datetime
	declare @strInDate datetime
	declare @strOutDate datetime
	declare @strOutDateTimeCrossed datetime
	declare @strInDateTimeCrossed datetime
	declare @NumberofApplied int
	Declare @TotalHoursWorked int
	Declare @FinalTotalHoursWorked int
	set @FinalTotalHoursWorked=0
	set @NumberofApplied=0
	set @Start=1
    -- Insert statements for procedure here
    if exists(SELECT Clk_InDate FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @Date AND IsVoid = 0)
		begin
			Create table #TempClockDetails
			(
				id int identity(1,1),Clk_InDate datetime,Clk_InTime datetime,Clk_OutDate datetime,Clk_OutTime datetime,
				--TotalHoursWorked as (datepart(hh,Clk_OutTime) * 60 + datepart(mi,Clk_OutTime))-(datepart(hh,Clk_InTime) * 60 + datepart(mi,Clk_InTime))
				TotalHoursWorked as (DATEDIFF(minute,Clk_InDate+Clk_InTime,Clk_OutDate + Clk_OutTime))
			)		
			Insert into #TempClockDetails
			SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inSwipeCardNo 
			AND Clk_Date = @Date AND IsVoid = 0			
			select @TotalRecord=COUNT(*)from #TempClockDetails
			while @TotalRecord>=@Start
				begin
					select	@strInDateTime=Clk_InTime,
							@strOutDateTime=Clk_OutTime,
							@strInDate=Clk_InDate,
							@strOutDate=Clk_OutDate,
							@TotalHoursWorked=TotalHoursWorked 
					from #TempClockDetails where id=@Start					
					if(@strInDate!='''' and @strInDateTime!='''' and @strOutDate!='''' and @strOutDateTime!='''')
						begin
							set @strInDateTime=@strInDate+'' ''+@strInDateTime
							set @strOutDateTime=@strOutDate+'' ''+@strOutDateTime
							if exists(SELECT P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0)
								begin
									SELECT @strInDateTime=P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
								end
							if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0)
								begin
									SELECT @strOutDateTime=P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
								end
							if exists(SELECT P.Permission_ToTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strInDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0)
								begin
									if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P inner join TA_Tbl_Employee E on E.Employee_Id = P.Employee_Id WHERE E.SwipeCardNo= @inSwipeCardNo AND @strOutDateTime between Permission_FromTime and Permission_ToTime AND P.Permission_Status=''Approved'' AND P.IsDeleted=0)
										begin
											if exists(SELECT P.Permission_FromTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status=''Approved'' AND P.IsDeleted=0)
												begin
													SELECT @strInDateTimeCrossed=P.Permission_FromTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
													SELECT @strOutDateTimeCrossed=P.Permission_ToTime FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
													if(@strOutDateTime>@strOutDateTimeCrossed)
														begin
															SELECT @NumberofApplied=P.No_Of_Hours FROM TA_Tbl_Permission P,TA_Tbl_Employee E WHERE E.Employee_Id = P.Employee_Id AND E.SwipeCardNo= @inSwipeCardNo AND ((P.Permission_FromTime between @strInDateTime and  @strOutDateTime)or(P.Permission_ToTime between @strInDateTime and @strOutDateTime))AND P.Permission_Status=''Approved'' AND P.IsDeleted=0
														end
												end
										end
								end
							set @FinalTotalHoursWorked=@FinalTotalHoursWorked+@TotalHoursWorked-@NumberofApplied
						end									
					set @Start=@Start+1
				end			
		end
		select @FinalTotalHoursWorked as TotalHoursWorked		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CalculateOTDays]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CalculateOTDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_CalculateOTDays
Description		:	Calculate OT Days
Tables Included		:	TA_Tbl_ProcessedData
Created By		:	Kumuthini.L
Created On		:	25-Apr-08
Modified By		:	
Modified On		:	
*/
CREATE PROCEDURE [dbo].[Proc_TA_CalculateOTDays]
(
	@SwipeCardNo NVARCHAR(10),
	@StartDate  NVARCHAR(10),
	@EndDate  NVARCHAR(10)
)
AS
DECLARE @TotalOTMins AS BIGINT
DECLARE @TotalOTDays AS NUMERIC(8,2)
BEGIN
	-- Get Total OT Minutes
	SET @TotalOTMins=(SELECT SUM(OtMins) FROM TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @StartDate AND @EndDate) AND Employee_Code_Id=@SwipeCardNo)
	-- Calculate Total OT Days
	SET @TotalOTDays = (@TotalOTMins / 60) / 8
	SELECT ISNULL(@TotalOTDays,0) AS TotalOTDays
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CalculateOnDutyWorkHoursForService]
	@inSwipeCardNo varchar(50),
	@Date varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Clk_InDate,Clk_InTime,Clk_OutDate,Clk_OutTime,Clk_InPunchType, clk_outpunchtype FROM TA_Tbl_ClockDetails 
	WHERE Clk_EmpId = @inSwipeCardNo AND Clk_Date = @Date AND IsVoid = 0 order by clk_id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkLeaveSanction]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkLeaveSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 29-Nov-2011
-- Description:	Bulk Leave Approval
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkLeaveSanction]
	@LeaveApplication_id int
AS
BEGIN
	SET NOCOUNT ON;
	update ta_tbl_leaveapplication set Status=''Approved'' where LeaveApplication_id=@LeaveApplication_id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVYearSetting]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVYearSetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DVYearSetting
Description : check year setting for demo version
Tables Included : TA_Tbl_YearSetting  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVYearSetting]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_YearSetting 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVLevelCreation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVLevelCreation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DVLevelCreation
Description : check level creation for demo version
Tables Included : TA_Tbl_YearSetting  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVLevelCreation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_Level where isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DVEmployeeCreation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DVEmployeeCreation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DVEmployeeCreation
Description : check employee creation for demo version
Tables Included : TA_Tbl_Employee  
Created By : Christopher S
Created On : 13-Nov-2008  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DVEmployeeCreation]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT COUNT(*) FROM TA_Tbl_Employee where isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DomainLogin]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DomainLogin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- [Proc_TA_DomainLogin] ''manikandan.rr@angleritech.com''
CREATE PROCEDURE [dbo].[Proc_TA_DomainLogin]
(
	@DomainUserName NVARCHAR(1000)
)
AS
BEGIN	
	SELECT	
	Employee_Id,Employee_FirstName + '' '' + Employee_LastName AS ''Employee Name'',
	Employee_Code_Id,EmailId,Photo,
	UserGroup_Id,Designation_Id,ShiftPattern_Id,Bus_Id,
			Employee_MiddleName,Employee_LastName,Father_name,Mother_name,DateofBirth,DateofBirth_Record,Blood_Group,Contact_Address, 
			Permanent_Address, Phone_Number, Mobile_Number, Gender, Marital_status, Nationality, Religion,Personal_mailid, Passport_No, 
			Passport_expirydate, Visa_No, Visa_expirydate, Vehicle_Type, Vehicle_No, Anniversary_Date, Native_Place, District, State, Country, 
			Spouse_No, Children_No, DateOfJoining, Reporting_To, Leave_Sanc_Authority, Prev_Experience, Basic_Salary, Allowances, 
			UserName, Emp_password, Qual_JoiningTime, Qual_Employment, OutDoorJob, CompOff_Eligible, OT_Eligible, ESI_Eligible, PF_Eligible, 
			Report_Exclude, Employee_Status, SwipeCardNo, Time_Stamp, Emp_ID, Isdeleted, Hostel, IsFlexible, InActiveDate, CustomField1, CustomField2, 
			CustomField3, CustomField4, CustomField5, IsComplete, Isdeleted_Status, InActive_Status, IsImported FROM TA_Tbl_Employee 
	--WHERE Employee_FirstName=@DomainUserName AND IsDeleted=0 and Employee_status=1
	WHERE (UserName=@DomainUserName) AND IsDeleted=0 and Employee_status=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutomaticLeaveCancellation]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutomaticLeaveCancellation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <02-July-2019>
-- Description:	<When the employee work hours meet out their day hours that case, it will cancel the leave application automatically,
-- even 1 minutes difference between work hours and defined hours, that case it will cancell the leave automatically.>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AutomaticLeaveCancellation]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    Declare @CurrentDate datetime
	Declare @currentDay varchar(20)
	set @CurrentDate=CONVERT(varchar(11),getdate())
	set @currentDay=DATENAME(dw,CONVERT(varchar(11),getdate()))
	if exists(select pageId from TA_Tbl_Page where pageId=185)
	begin
		
	CREATE TABLE #TempLeaveAppliedEmployees
	(
		[LeaveApplication_Id] [int] NOT NULL,
		[Employee_Id] [nvarchar](20) NOT NULL,
		[Leave_ApplicationDate] [datetime] NOT NULL,
		[LeaveType_id] [int] NOT NULL,
		[Type] [nvarchar](50) NOT NULL,
		[Leave_FromDate] [datetime] NOT NULL,
		[Leave_ToDate] [datetime] NOT NULL,
		[Leave_SessionFrom] [nvarchar](50) NULL,
		[Leave_SessionTo] [nvarchar](50) NULL,
		[NumberOfDays] [decimal](18, 1) NOT NULL,
		[Reason] [nvarchar](1000) NULL,
		[IntimationType] [nvarchar](25) NULL,
		[Status] [nvarchar](50) NOT NULL,
		[IsDeleted] [bit] NOT NULL,
		[Remarks] [nvarchar](1000) NULL,
		[IsBorrow] [bit] NULL,
		[Emp_Id] [int] NULL,
		[YearSettings_Id] [int] NULL,
		[CheckedIDs] [int] NULL,
		[InformTo] [varchar](max) NULL,
		[companyId] [int] NULL,
		[Successiveyear] [bit] NULL,
		[Intervening] [char](5) NULL
	) ON [PRIMARY]

	Insert into #TempLeaveAppliedEmployees
	select LA.* from TA_Tbl_LeaveApplication LA
	Inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
	Where E.Employee_Status=1 and (LA.Leave_FromDate>=@CurrentDate and LA.Leave_ToDate<=@CurrentDate)
	and LA.Status!=''Rejected''

	--select * from #TempLeaveAppliedEmployees

	
	create table #tempCategoryDetails
	(
		EmployeeId bigint,
		SwipeCardNo varchar(20),
		CategoryId int,
		WeekDay_WorkHrs decimal(18,1),
		Sat_WorkHrs decimal(18,1)
	)

	insert into #tempCategoryDetails
	select	EmpCategory.EmployeeId,
			SwipeCardNo,
			c.CategoryId,
			convert(decimal(18,1),WeekDay_WorkHrs)*60-5,convert(decimal(18,1),Sat_WorkHrs)*60-5
	from 
	(
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		inner join #TempLeaveAppliedEmployees TLA on TLA.Employee_Id=emp.Employee_Id
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ECategory.CategoryId is not null
	inner join TA_Tbl_Category c on c.CategoryId=ECategory.CategoryId

	--select * from #tempCategoryDetails
	
		if(@currentDay=''saturday'')
		begin
			update TA_Tbl_LeaveApplication set IsDeleted= 
			--SELECT 
			CASE	WHEN SUBSTRING(pd.HrsWork,0,CHARINDEX('':'',pd.HrsWork))*60+SUBSTRING(pd.HrsWork,CHARINDEX('':'',pd.HrsWork)+1,LEN(pd.HrsWork))=tcd.Sat_WorkHrs THEN 0
					ELSE 0
			END,Status=''Cancelled''
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!=''00:00'') AND LA.Status!=''Rejected''
			
			insert into AutoLeaveupdation
			select LA.LeaveApplication_Id
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!=''00:00'')AND LA.Status!=''Rejected''
			
		end
		else
		begin
			update TA_Tbl_LeaveApplication set IsDeleted= 
			--SELECT 
			CASE	WHEN SUBSTRING(pd.HrsWork,0,CHARINDEX('':'',pd.HrsWork))*60+SUBSTRING(pd.HrsWork,CHARINDEX('':'',pd.HrsWork)+1,LEN(pd.HrsWork))=tcd.WeekDay_WorkHrs THEN 1
					ELSE 0
			END,Status=''Cancelled''
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!=''00:00'')AND LA.Status!=''Rejected''
			
			insert into AutoLeaveupdation
			select LA.LeaveApplication_Id
			from TA_Tbl_ProcessedData PD
			Inner join #tempCategoryDetails tcd on PD.Employee_Code_Id=tcd.SwipeCardNo
			inner join TA_Tbl_LeaveApplication LA on (LA.Employee_Id=tcd.EmployeeId and LA.Leave_FromDate=@CurrentDate)
			where Date=@CurrentDate and (InTime is not null and InTime!=''00:00'')AND LA.Status!=''Rejected''
		end
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <14-11-2019 01:44 PM>
-- Description:	<Bulk UPDATE of availed leave values through excel sheet>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkImportAvailedLeavesUptoLastMonth]
AS
BEGIN
	SET NOCOUNT ON;	
	DECLARE @YearSetID int
	DECLARE @Count int
	DECLARE @Start int
	SET  @Start=1
	SELECT @YearSetID=YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive=1
	SELECT @Count=COUNT(*) FROM ImportFromExcel	
	WHILE @Count>=@Start
	BEGIN		
		DECLARE @EmpAutoID bigint
		DECLARE @Employeeid	varchar(50)
		DECLARE @LeaveType1	DECIMAL(18,1)
		DECLARE @LeaveType2	DECIMAL(18,1)
		DECLARE @LeaveType3	DECIMAL(18,1)
		DECLARE @LeaveType4	DECIMAL(18,1)
		DECLARE @LeaveType5	DECIMAL(18,1)
		DECLARE @LeaveType6	DECIMAL(18,1)
		DECLARE @LeaveType7	DECIMAL(18,1)
		DECLARE @LeaveType8	DECIMAL(18,1)
		DECLARE @LeaveType9	DECIMAL(18,1)
		DECLARE @LeaveType10 DECIMAL(18,1)
		DECLARE @LeaveType11 DECIMAL(18,1)
		DECLARE @LeaveType12 DECIMAL(18,1)
		DECLARE @LeaveType13 DECIMAL(18,1)
		DECLARE @LeaveType14 DECIMAL(18,1)
		DECLARE @LeaveType15 DECIMAL(18,1)
		
		SET  @Employeeid=''''
		SET  @LeaveType1=0 
		SET  @LeaveType2=0 
		SET  @LeaveType3=0 
		SET  @LeaveType4=0 
		SET  @LeaveType5=0 
		SET  @LeaveType6=0 
		SET  @LeaveType7=0
		SET  @LeaveType8=0 
		SET  @LeaveType9=0
		SET  @LeaveType10=0 
		SET  @LeaveType11=0 
		SET  @LeaveType12=0
		SET  @LeaveType13=0
		SET  @LeaveType14=0 
		SET  @LeaveType15=0
		
		SELECT
		@Employeeid=Employeeid,
		@LeaveType1=LeaveType1,
		@LeaveType2=LeaveType2,
		@LeaveType3=LeaveType3, 
		@LeaveType4=LeaveType4,
		@LeaveType5=LeaveType5,
		@LeaveType6=LeaveType6,
		@LeaveType7=LeaveType7,
		@LeaveType8=LeaveType8,
		@LeaveType9=LeaveType9,
		@LeaveType10=LeaveType10, 
		@LeaveType11=LeaveType11,
		@LeaveType12=LeaveType12,
		@LeaveType13=LeaveType13,
		@LeaveType14=LeaveType14,
		@LeaveType15=LeaveType15			
		FROM ImportFromExcel WHERE [Sl.No]=@Start
		
		SELECT @EmpAutoID=Employee_Id FROM TA_Tbl_Employee WHERE Employee_Code_Id=@Employeeid and Isdeleted=0		
		if(@EmpAutoID is not null and @EmpAutoID<>'''')
		BEGIN
			DECLARE @LeaveTypeID int
			--1
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=1 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType1,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---2
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=2 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType2,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---3
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=3 ORDER BY LeaveType_Id			
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType3,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---4
			SET  @LeaveTypeID=0							
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=4 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType4,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			END
			---5
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=5 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType5,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---6
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=6 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType6,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---7
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=7 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType7,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---8
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=8 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType8,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---9
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=9 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType9,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---10
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=10 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType10,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---11
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=11 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType11,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---12
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=12 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType12,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---13
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=13 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType13,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---14
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=14 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET  NoOffLeaveAvailed=ISNULL(@LeaveType14,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
			---15
			SET  @LeaveTypeID=0				
			SELECT @LeaveTypeID=LeaveType_Id FROM TA_Tbl_LeaveType WHERE LeaveType_Id=15 ORDER BY LeaveType_Id
			if(ISNULL(@LeaveTypeID,'''')!='''')
			BEGIN
				IF EXISTS(SELECT EmployeeId FROM ta_tbl_emp_LeaveTypedetails WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					UPDATE ta_tbl_emp_LeaveTypedetails SET NoOffLeaveAvailed=ISNULL(@LeaveType15,0) WHERE EmployeeId=@EmpAutoID and YearSettingsId=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			END
		END
		SET  @Start=@Start+1 
	END
	DELETE FROM ImportFromExcel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BindProjectdetails]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BindProjectdetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<Filter and dropdown filling of project info>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BindProjectdetails]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	select Project_Id, Project_Name=isnull(Project_Name,'''') from TA_Tbl_Project	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		<Velumani P>
-- CREATE DATE: <15/7/2019>
-- DESCRIPTION:	<THIS PROCEDURE WORKS FOR LATEIN AND EARLY OUT - attendance Updation>
-- =============================================
--PROC_TA_AttendanceUpdationBasedOnLateIn ''2020/12/01 00:00:00.000'',''5'',1
--THIS PROCEDURE WORKS FOR 2 CASES . ONE IS LATEIN AND ANOTHER ONE IS EARLY OUT
CREATE PROCEDURE [dbo].[PROC_TA_AttendanceUpdationBasedOnLateIn]
 @SHIFTDATE DATETIME,
 @EMPLOYEECODEID NVARCHAR(40),
 @COMPANYID INT
AS
BEGIN
	SET NOCOUNT OFF;
	--VARIABLES FOR LATE IN --
	DECLARE @LATEMINSPERDAY INT
	DECLARE @LATEDAYSPERMONTH INT	
	DECLARE @LATECOUNT INT
	DECLARE @ODDEVENDECIDER INT
	DECLARE @FROMDATE DATETIME
	DECLARE @TODATE DATETIME
	--VARIABLES FOR EARLY OUT--
	DECLARE @EARLYOUTMINSPERDAY INT
	DECLARE @EARLYOUTDAYSPERMONTH INT	
	DECLARE @EARLYOUTCOUNT INT
	DECLARE @EARLYOUTODDEVENDECIDER INT
		--GETTING COMPANY CONFIGURED LATEIN MINUTES VALUE--
	SELECT @LATEMINSPERDAY =  ISNULL(LATEMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	SELECT @LATEDAYSPERMONTH =   ISNULL(LATEDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	Declare @ShiftSecondHalf_Time datetime
	Declare @Shift_FirstHalf_EndTime datetime
	Declare @intime datetime
	Declare @outtime datetime
	Declare @shift_id int
	Declare @diff int			
	SELECT @shift_id= Shift_Id,@intime=InTime,@outtime=OutTime FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID 
	select @ShiftSecondHalf_Time=Shift_SecondHalf_StartTime,@Shift_FirstHalf_EndTime =Shift_FirstHalf_EndTime from TA_Tbl_Shift where shift_id=@shift_id
	--CHECKING LATEIN MINTES PER DAY CASE --
	IF(@LATEMINSPERDAY !=0)
	BEGIN
		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY AND FNATTENDANCECODE=''PRESENT'')
		BEGIN
			UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''Absent'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND FNATTENDANCECODE=''PRESENT''	
		END
		ELSE
		BEGIN			
			if(CONVERT(datetime,@intime)>convert(datetime,@ShiftSecondHalf_Time))
			BEGIN
				set @diff=DATEDIFF(minute,@intime,@ShiftSecondHalf_Time)
				if(@diff>=@LATEMINSPERDAY)
				begin
					UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''Absent'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > @LATEMINSPERDAY  AND ANATTENDANCECODE = ''PRESENT''
				end
			END
		END
	END
	--CHECKING LATEIN DAYS PER MONTH CASE --
	-- 2 CASES HERE, @LATEMINSPERDAY MAY BE  >0 , @LATEMINSPERDAY = 0
	--CASE 1 LATEMINTS PER DAY IS > 0 
	IF(@LATEDAYSPERMONTH !=0)
	BEGIN	
		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
		IF(@LATEMINSPERDAY > 0)
		BEGIN
			SET @LATECOUNT=0;
			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (LATEINMINS <= @LATEMINSPERDAY) and (LATEINMINS > 0)
			IF(@LATECOUNT > @LATEDAYSPERMONTH)
			BEGIN
				SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
				IF(@ODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY) AND FNATTENDANCECODE=''PRESENT'' and (LATEINMINS > 0))
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND FNATTENDANCECODE=''PRESENT'' and (LATEINMINS > 0)
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (LATEINMINS <= @LATEMINSPERDAY)  AND ANATTENDANCECODE = ''PRESENT'' and (LATEINMINS > 0)
					END
				END	
			END		
		END
			--CASE 2 LATEMINTS PER DAY IS = 0 
		ELSE IF(@LATEMINSPERDAY = 0)
		BEGIN
			SET @LATECOUNT=0;
			SELECT @LATECOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND LATEINMINS > 0
			IF(@LATECOUNT > @LATEDAYSPERMONTH)
			BEGIN
				SET @ODDEVENDECIDER = (@LATECOUNT - @LATEDAYSPERMONTH)%2;	
				IF(@ODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0 AND FNATTENDANCECODE=''PRESENT'')
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND FNATTENDANCECODE=''PRESENT''	
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND LATEINMINS > 0  AND ANATTENDANCECODE = ''PRESENT''
					END
				END	
			END		
		END
	END
	--EARLY OUT STARTS HERE--
	--GETTING COMPANY CONFIGURED EARLY OUT MINUTES VALUE--
	SELECT @EARLYOUTMINSPERDAY =  ISNULL(EARLYEXITMINSPERDAY,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	SELECT @EARLYOUTDAYSPERMONTH =   ISNULL(EARLYEXITDAYSPERMONTH,0) FROM TA_TBL_SHIFTSETTINGS WHERE COMPANYID = @COMPANYID
	--CHECKING LATEIN MINTES PER DAY CASE --
	IF(@EARLYOUTMINSPERDAY !=0)
	BEGIN
		IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY AND ANATTENDANCECODE=''PRESENT'')
		BEGIN
			UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''Absent'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND ANATTENDANCECODE=''PRESENT''	
		END
		ELSE
		BEGIN
			if(CONVERT(datetime,@outtime)<convert(datetime,@Shift_FirstHalf_EndTime))
			BEGIN
				set @diff=DATEDIFF(minute,@outtime,@Shift_FirstHalf_EndTime)
				if(@diff>=@EARLYOUTMINSPERDAY)
				begin
					UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''Absent'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > @EARLYOUTMINSPERDAY  AND FNATTENDANCECODE = ''PRESENT'' 
				end
			end
			--and ANATTENDANCECODE = ''ABSENT''
		END
	END
	--CHECKING EARLY OUT DAYS PER MONTH CASE --
	-- 2 CASES HERE, @EARLYOUTMINSPERDAY MAY BE  >0 , @EARLYOUTMINSPERDAY = 0
	--CASE 1 EARLY OUT  PER DAY IS > 0 
	IF(@EARLYOUTDAYSPERMONTH !=0)
	BEGIN	
		SET @FROMDATE  =  CONVERT(DATETIME,((DATEADD(M, DATEDIFF(M, 0, @SHIFTDATE), 0))));
		SET @TODATE= CONVERT(DATETIME, @SHIFTDATE);
		IF(@EARLYOUTMINSPERDAY > 0)
		BEGIN
			SET @EARLYOUTCOUNT=0;
			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) and (EARLYOUTMINS > 0)
			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
			BEGIN
				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;		
				IF(@EARLYOUTODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY) AND ANATTENDANCECODE=''PRESENT'' and (EARLYOUTMINS > 0 ))
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND ANATTENDANCECODE=''PRESENT''	and (EARLYOUTMINS > 0 )
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND (EARLYOUTMINS <= @EARLYOUTMINSPERDAY)  AND FNATTENDANCECODE = ''PRESENT'' and (EARLYOUTMINS > 0 )
					END
				END	
			END		
		END
			--CASE 2 EARLY OUT PER DAY IS = 0 
		ELSE IF(@EARLYOUTMINSPERDAY = 0)
		BEGIN
			SET @EARLYOUTCOUNT=0;
			SELECT @EARLYOUTCOUNT = ISNULL(COUNT(PROCESS_REC_ID),0) FROM TA_TBL_PROCESSEDDATA 
			WHERE (DATE >= @FROMDATE AND DATE <= @TODATE)
			AND (EMPLOYEE_CODE_ID=@EMPLOYEECODEID) AND EARLYOUTMINS > 0
			IF(@EARLYOUTCOUNT > @EARLYOUTDAYSPERMONTH)
			BEGIN
				SET @EARLYOUTODDEVENDECIDER = (@EARLYOUTCOUNT - @EARLYOUTDAYSPERMONTH)%2;	
				IF(@EARLYOUTODDEVENDECIDER = 0)
				BEGIN
					IF EXISTS(SELECT ISNULL(PROCESS_REC_ID,0)FROM TA_TBL_PROCESSEDDATA WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0 AND ANATTENDANCECODE=''PRESENT'')
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET ANATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND ANATTENDANCECODE=''PRESENT''	
					END
					ELSE
					BEGIN
						UPDATE TA_TBL_PROCESSEDDATA SET FNATTENDANCECODE=''LOP'' WHERE DATE=CONVERT(DATETIME, @SHIFTDATE) AND EMPLOYEE_CODE_ID=@EMPLOYEECODEID AND EARLYOUTMINS > 0  AND FNATTENDANCECODE = ''PRESENT''
					END
				END	
			END		
		END
	END
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetEmployeeWorkingHours]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetEmployeeWorkingHours]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <Create Date,,>    
-- Description: <Description,,>    
-- fn_TA_CountNumberOfWorkingDays 44    
-- =============================================    
CREATE function [dbo].[fn_TA_GetEmployeeWorkingHours]    
(
@EmployeeID int
)  
RETURNS numeric(9,2)   
AS    
BEGIN    
declare @WorkHours numeric(9,2)    
select @WorkHours= round(catmas.MonToSat_WorkHrs/6,1) from TA_Tbl_EmployeeCategory cat 
inner join TA_Tbl_Employee emp on emp.Employee_Id = cat.EmployeeId 
inner join TA_Tbl_Category catmas on catmas.CategoryId=cat.CategoryId 
where SwipeCardNo =@EmployeeID
return @WorkHours
END    
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[TimeOnly]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TimeOnly]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
create function [dbo].[TimeOnly](@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
returns datetime
as
    begin
    return @DateTime - dbo.DateOnly(@DateTime)
    end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[EmpReEntry]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpReEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[EmpReEntry] 
as
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_DEVICEID varchar(20)
declare @CLK_DATE datetime
declare @CLK_TIME datetime
declare @CardNo varchar(20)
declare @eCount int
	insert into dbo.TA_Tbl_Clk_BackupRawData (CLK_ID,CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME )(select Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime from TA_Tbl_ClockDetails WHERE
      Clk_InTime IS NULL AND Clk_OutTime IS NOT NULL and clk_outdate<> getdate())
delete from TA_Tbl_ClockDetails WHERE
      Clk_InTime IS NULL AND Clk_OutTime IS NOT NULL and clk_outdate<> getdate()
--exec EmpINReEntry -- Remove the In Entrys Below 5 minutes
declare emp_ReEntry cursor for 
select CLK_ID,CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME from TA_Tbl_Clk_BackupRawData order by  CLK_ID
open emp_ReEntry
fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
while (@@fetch_status = 0 )
begin
set @CardNo=''''
--set @CardNo=(select SwipeCardNo from dbo.TA_Tbl_Employee where Employee_Code_Id=@CLK_CARDID)
set @CardNo=@CLK_CARDID
set @eCount=(select count(@CLK_CARDID)  from dbo.TA_Tbl_ClockDetails where clk_EmpID=@CLK_CARDID and clk_outdate=@CLK_DATE and clk_outTime>dateadd(mi,-5,@CLK_TIME) and clk_outTime<dateadd(mi,5,@CLK_TIME) )
--set @eCount=(select  count(Clk_EmpId) from dbo.TA_Tbl_ClockDetails WHERE
		--	Clk_EmpId= @CLK_CARDID AND Clk_OutDate =@CLK_DATE and Clk_OutTime=@CLK_TIME  )
if (@eCount=0)
begin
	if len(@CardNo)>0
	begin
			set @eCount=(select  count(CLK_CARDID) from dbo.TA_Tbl_Clk_RawData WHERE
				CLK_CARDID = @CLK_CARDID AND CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=1  )
	if (@eCount>0)
		begin
				update dbo.TA_Tbl_Clk_RawData set CLK_FLAG=0,CLK_PROCESS=0 WHERE
					CLK_CARDID = @CLK_CARDID AND CLK_DATE=@CLK_DATE and CLK_TIME=@CLK_TIME and CLK_TYPE=1 
		end
		else
		begin
				insert into dbo.TA_Tbl_Clk_RawData(CLK_CARDID,CLK_DEVICEID,CLK_DATE,CLK_TIME,CLK_TYPE,CLK_FLAG,CLK_PROCESS)
											values(@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME,1,0,0)
		end
	end
end
delete from TA_Tbl_Clk_BackupRawData where @CLK_ID=CLK_ID
  fetch emp_ReEntry into @CLK_ID,@CLK_CARDID,@CLK_DEVICEID,@CLK_DATE,@CLK_TIME
end   
deallocate emp_ReEntry' 
END
GO
/****** Object:  StoredProcedure [dbo].[Template_LogInsert]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Template_LogInsert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Template_LogInsert]
	(@UserID   nvarchar(15),@LogFlag  nvarchar(2),@DeviceID nvarchar(15),@DeviceName nvarchar(15),@devDate nvarchar(15),@DevTime  nvarchar(15),@LogType nvarchar(10),@KeyID nvarchar(15))
AS
DECLARE @dtDateTime AS DATETIME
DECLARE @nTNAEvent AS INT
DECLARE @nEvent AS INT
DECLARE @lType AS varchar(3)
SET @dtDateTime=@devDate +'' '' +@DevTime
SET @nTNAEvent=@LogType
BEGIN
--"IV";// user identity varified    55
--"NH";// not currently used   54
--"UN";// valid user entered but hand rejected (Not Verified)   56
--"ER";//user enrolled at the reader   10
--"CM";// user entered through the terminal command mode      11
	IF(@LogFlag=''IV'')--user identity varified    55
	begin
		set @nEvent=55
	end
	 IF(@LogFlag=''NH'')--not currently used   54
	begin
		set @nEvent=54
	end
	 IF(@LogFlag=''UN'')-- valid user entered but hand rejected (Not Verified)   56
	begin
		set @nEvent=56
	end
 	IF(@LogFlag=''ER'')
	begin
		set @nEvent=10
	end
	 IF(@LogFlag=''CM'')
	begin
		set @nEvent=11
	end
--******************************************************************************************************************************************************************
	set @nTNAEvent=''0''
	if @LogType=''1''  --IN
	begin
		set @nTNAEvent=''0''
	end
	if @LogType=''3''--OUT
	begin
		set @nTNAEvent=''1''
	end
	if @LogType=''2''--Lunch IN 
	begin
		set @nTNAEvent=''2''
	end
	if @LogType=''4''--Lunch Out
	begin
		set @nTNAEvent=''3''
	end
	if @LogType=''5''
	begin
		set @nTNAEvent=''5''
	end
	if @LogType=''6''
	begin
		set @nTNAEvent=''6''
	end
	if @LogType=''7''
	begin
		set @nTNAEvent=''7''
	end
	if @LogType=''8''
	begin
		set @nTNAEvent=''8''
	end
--*******Based on Mechine IO Type Change the LOgs***********************************************************
	set  @lType=(select D_INOUT from dbo.tblDevice_Mast where Device_ID=@DeviceID)
	if  @lType=''IN''  --IN
	begin
		set @nTNAEvent=''0''
	end
	if  @lType=''OUT''--OUT
	begin
		set @nTNAEvent=''1''
	end
if len(@UserID)>6
	begin
		set @UserID=right(@UserID,6)
	end
INSERT INTO tb_reportslist(nUserID,dtDateTime,nDeviceID,nEvent,nTNAEvent,strUniqueKey)VALUES(@UserID,@dtDateTime,@DeviceID,@nEvent,@nTNAEvent,@KeyID)
IF(@LogFlag=''ER'' or @LogFlag=''CM'')
	begin
		delete from  tblDeviceEnrUsers where EmpCode=@UserID
		insert into tblDeviceEnrUsers(EmpCode,EnrDateTime,DeviceID) values(@UserID,@dtDateTime,@DeviceID)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[SelectReportingToSanctionAuthorityForPermission]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectReportingToSanctionAuthorityForPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[SelectReportingToSanctionAuthorityForPermission]
	-- Add the parameters for the stored procedure here
	@Permission_ID int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Reporting_To,Leave_Sanc_Authority from ta_tbl_employee Where employee_id=(
	select Employee_id from ta_tbl_Permission where Permission_id=@Permission_ID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[ReProcess_EmpLogs]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReProcess_EmpLogs]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--3 processing data last
CREATE procedure [dbo].[ReProcess_EmpLogs] @Process_Rec_ID varchar(20), @Employee_Code varchar(20),@Emp_Date Datetime,@Shift_Id varchar(10),@OTtype varchar(1)
as
declare @mOT char(1)--if you want Morning OT then Y else N
declare @RoundEnable char(1)-- if Enable  Roundoff tehn Y else N
declare @Clk_EmpId char(8)
declare @Clk_inDatetime datetime
declare @Clk_inTime char(8)
declare @Clk_outDatetime datetime
declare @Clk_outTime char(8)
declare @Clk_Remarks varchar(50)
declare @WMinutes numeric(18)
declare @TotalSWMin numeric(18)
declare @TotalShiftbreak numeric(18)
declare @check_In_time  datetime
declare @check_End_time  datetime
declare @check_In_date char(20)
declare @Shiftbreak varchar(10)
select @RoundEnable=''Y'' -- if Enable  Roundoff tehn Y else N
create table #loglist (emp_code char(8),emp_inDate datetime,emp_outdate datetime,emp_remark varchar(50) NULL,Work_minute numeric(8) null,ShiftWork_minute numeric(8) null)
declare emp_list cursor for 
select  Clk_EmpId,Clk_inDate+Clk_inTime as INTime,Clk_outDate + Clk_outTime as OutTime,Clk_Remarks,DateDiff("N", Clk_inDate+Clk_inTime, Clk_outDate + Clk_outTime) as WMinutes from TA_Tbl_ClockDetails WHERE
       Clk_EmpId = @Employee_Code AND Clk_InTime IS NOT NULL AND Clk_OutTime IS NOT NULL  AND Clk_InDate =@Emp_Date order by  Clk_inDate, Clk_inTime
open emp_list
fetch emp_list into  @Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks,@WMinutes
while (@@fetch_status = 0 )
begin
	select @Shiftbreak =(select Shift_BreakStartTime1 from dbo.TA_Tbl_Shift where shift_ID=@Shift_Id )
if len(@Shiftbreak)>0 
begin
--***************Calculate Working hours based on in and out on the log
	select @TotalShiftbreak =(select Datediff("n", Shift_BreakStartTime1,Shift_BreakEndTime1) from dbo.TA_Tbl_Shift where shift_ID=@Shift_Id )
end
else
begin
	set @TotalShiftbreak=0
end
	select @TotalSWMin =(select DateDiff("N", ''00:00'',Shift_TotalWorkingHours) from TA_Tbl_Shift where Shift_Id=@Shift_Id )
      if (@WMinutes<0 )
		begin 	
			set @WMinutes=0 -- if its negitive working time assign it zero
		end
		if (@TotalShiftbreak>0 )
		begin 	
			set @WMinutes=@WMinutes-@TotalShiftbreak -- if its negitive working time assign it zero
		end
--convert(int,@iTotalMin) <=convert(int,@TotalSWMin)+300 and
if ( convert(int, @WMinutes) >0 and  convert(int, @WMinutes) <1440 ) 
begin
	insert into #loglist(emp_code ,emp_inDate, emp_outdate,EMP_REMARK,Work_minute,ShiftWork_minute)
   values(@Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks, @WMinutes,@TotalSWMin)
end 
   fetch emp_list into @Clk_EmpId,@Clk_inDatetime,@Clk_outDatetime,@Clk_Remarks,@WMinutes
end   
deallocate emp_list
declare @fin  char(20) -- first in 
declare @lout  char(20) -- last out
declare @wTHour   numeric(4) -- Total working Minutes
declare @ShortageHour   numeric(4) -- shortage minutes
declare @wmin  char(2) -- shift break
declare @wH   char(2) -- shift break
declare @workingHour  char(20) -- shift break
declare @LmworkingHour  char(20) -- shift break
declare @REMARK  VARCHAR(50) -- shift break
declare @S_wTHour   numeric(4) -- shift work hours
declare @S_wmin  char(2) -- shift break
declare @S_wH   char(2) -- shift break
declare @S_workingHour  char(20) -- shift break
declare @phrswork char(5)
declare @Short_wH char(2)
declare	@Short_wmin char(2)
declare	@Short_workingHour char(5)
declare @pOT char(10)
declare @pHrsOT char(10)
declare @pHrsOT_hh char(2)
declare @pHrsOT_mm char(2)
declare @pNormOT char(5)
declare @pOffOT char(5)
declare @pHolOT char(5)
declare @pEarlyOut char(5)
declare @pLateIn char(5)
--pLeaveType
declare @pWorkHrs char(5)
declare @pHrsLess char(5)
declare @Pday char(5)
declare @Exot char(5)
declare  @pEarlyIn char(5)
declare @OTstatusDay char(15)
declare @OT_AMT numeric(2,2)
declare @MinOT char(5)
declare @MaxOT char(5)
select @fin=(select min(emp_inDate )as Firstin from #loglist )
select @lout=(select max(emp_outdate )as lastout from #loglist )
select @REMARK =(select   distinct (EMP_REMARK) from #loglist )
if @fin is null 
begin
	select @fin=(select distinct (emp_inDate)  from #loglist ) 
end
if @lout is null 
begin
	select @lout=(select distinct (emp_outDate) from #loglist)
end
select @wTHour= convert(int,(select sum(Work_minute)as totWH from #loglist ),5)
select @s_wTHour= convert(int,(select distinct  (ShiftWork_minute) from #loglist ),5)
	if  (@wTHour>1440)  -- not more thatn 24 hours
	begin
		select @wTHour=1440
	end
	if  (@wTHour<=1)  -- IN SECONDS
	begin
		select @wTHour=0
	end
-- convert the working minutes to hours and minutesselect @wH=convert(char,convert(int,(@wTHour/60),2),2)
select @wH=convert(char,convert(int,(@wTHour/60),2),2)
select @wmin= convert(int,@wTHour)%60
if (len(rtrim(@wH))=1) select @wH= ''0''+@wH
if (len(rtrim(@wmin))=1) select @wmin= ''0''+@wmin
select @workingHour=  rtrim(@wH) +'':''+   rtrim(@wmin)
-- convert the Shift working minutes to hours and minutes
select @S_wH=convert(char,convert(int,(@S_wTHour/60),2),2)
select @S_wmin= convert(int,@S_wTHour)%60
if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
select @S_workingHour= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
/*
-- convert the working minutes to hours and minutesselect @wH=convert(char,convert(int,(@wTHour/60),2),2)
set @ShortageHour=0
set @Short_workingHour=''00:00''
if @S_wTHour>@wTHour
begin
		select @ShortageHour=@S_wTHour-@wTHour
		-- convert the Shift working minutes to hours and minutes
		select @Short_wH=convert(char,convert(int,(@ShortageHour/60),2),2)
		select @Short_wmin= convert(int,@ShortageHour)%60
		if (len(rtrim(@Short_wH))=1) select @Short_wH= ''0''+@Short_wH
		if (len(rtrim(@Short_wmin))=1) select @Short_wmin= ''0''+@Short_wmin
		select @Short_workingHour= rtrim(@Short_wH) +'':''+   rtrim(@Short_wmin)
end
select @LmworkingHour=@workingHour
-- calculation of OT
if @pHrsOT is null 
begin
select @pHrsOT=''00:00'' 
end
if( DateDiff(mi,  @S_workingHour,@workingHour)> 0 )
--select DateDiff(mi,''09:00'',''10:30'')
begin
select @pOT=DateDiff(mi,  @S_workingHour,@workingHour)
	if ( @pOT>abs(@pEarlyIn))
		begin 
			select @LmworkingHour =convert(int,@wTHour) - convert(int,abs(@pEarlyIn))
		select @wH=convert(char,convert(int,(@LmworkingHour/60),2),2)
		select @wmin= convert(int,@LmworkingHour)%60
		if (len(rtrim(@wH))=1) select @wH= ''0''+@wH
		if (len(rtrim(@wmin))=1) select @wmin= ''0''+@wmin
		select  @LmworkingHour=  rtrim(@wH) +'':''+   rtrim(@wmin)
		end
if @mOT=''Y''
begin
--if you want the morning OT Comment this below line
select  @LmworkingHour=@workingHour
end
--end of morning OT
select @pOT=DateDiff(MI,  @S_workingHour,@LmworkingHour)/60
select @pHrsOT_hh=convert(char,@pOT,2)
select @pOT=DateDiff(mi,  @S_workingHour,@LmworkingHour)
	select @pHrsOT_mm=convert(char,@pOT%60,2)
*/
select @pHrsOT_hh=convert(char,DateDiff(hh,  @S_workingHour,@workingHour),2)
select @pHrsOT_mm=convert(char,DateDiff(mi, @S_workingHour,@workingHour)%60,2)
if convert(int,@pHrsOT_hh)<0 
begin
	set @pHrsOT_hh=0
end
	--convert(int,@S_wTHour)%60
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= ''0''+@pHrsOT_hh
	if (len(rtrim(@pHrsOT_mm))=1) select @pHrsOT_mm= ''0''+@pHrsOT_mm
select @Exot =rtrim(@pHrsOT_hh)+'':''+rtrim(@pHrsOT_mm)
-- Rounding the OT Calculation if <29 means 00  and >30 <59 menas 30
if @RoundEnable=''Y''
begin
if (convert(int,@pHrsOT_mm)<=15 )
	begin
	select @pHrsOT_mm=''00''
	end
if (convert(int,@pHrsOT_mm)>15) and (convert(int,@pHrsOT_mm)<=30 )
	begin
	select @pHrsOT_mm=''30''
	end
if (convert(int,@pHrsOT_mm)>30 and  convert(int,@pHrsOT_mm)<=45 )
	begin
	select @pHrsOT_mm=''30''
	end
if  convert(int,@pHrsOT_mm)>45  
	begin
	select @pHrsOT_mm=''00''
	select @pHrsOT_hh=convert(int,@pHrsOT_hh)+1
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= ''0''+@pHrsOT_hh
	end
-- end of  Rounding off
end
 	select @pHrsOT =rtrim(@pHrsOT_hh)+'':''+rtrim(@pHrsOT_mm)
select @MinOT =(select Shift_MinTimeOT from TA_Tbl_Shift where Shift_Id=@Shift_Id )
  select @MaxOT =(select Shift_MaxTimeOT from TA_Tbl_Shift where Shift_Id=@Shift_Id )
	if DateDiff(mi,''00:00'',@MinOT)> DateDiff(mi,''00:00'',@pHrsOT)
	begin
		select @pHrsOT=''00:00''
	end
	if DateDiff(mi,''00:00'',@MaxOT)>0
	begin
		if DateDiff(mi,''00:00'',@MaxOT)< DateDiff(mi,''00:00'',@pHrsOT)
		begin
			select  @pHrsOT=@MaxOT
		end
	end
	--end
if( DateDiff(mi,  @S_workingHour,@workingHour)<= 0 )
begin
select @pHrsOT=''00:00''
select @Exot=''00:00''
end
if @pHrsOT is null 
begin
select @pHrsOT=''00:00'' 
end
if @fin is null 
begin
select @fin=''00:00:00'' 
end
if @lout is null 
begin
select @lout=''00:00:00'' 
end
if @workingHour is null 
begin
select @workingHour=''00:00'' 
end
if @S_workingHour is null 
begin
select @S_workingHour=''00:00'' 
end
-- calculate late in and early out
if @OTtype=''N''
begin
	set @pNormOT =@pHrsOT
	set @pOffOT=''00:00''
	set @pHolOT =''00:00''
end
if @OTtype=''O''
begin
	set @pNormOT =''00:00''
	set @pOffOT=@workingHour
	set @pHolOT =''00:00''
end
if @OTtype=''H''
begin
	set @pNormOT =''00:00''
	set @pOffOT=''00:00''
	set @pHolOT =@workingHour
end
--ExtraMins              OtMins 
Update 	dbo.TA_Tbl_ProcessedData 
set HrsWork=@workingHour,HrsOT=@pHrsOT,NormOT=@pNormOT,OffOT=@pOffOT,HolOT=@pHolOT,WorkHrs=@workingHour,HrsExtra=@pHrsOT
where Process_Rec_ID=@Process_Rec_ID
/*
if @pHrsOT	is null
begin 
select @pHrsOT=''00:00''
end
	select @pHrsOT_hh=convert(char,convert(int,(@wTHour/60),2),2)
	select @pHrsOT_mm=convert(char,convert(int,(@wTHour),2)%60,2)
	--convert(int,@S_wTHour)%60
	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= ''0''+@pHrsOT_hh
	if (len(rtrim(@pHrsOT_mm))=1) select @pHrsOT_mm= ''0''+@pHrsOT_mm
		select @Exot =rtrim(@pHrsOT_hh)+'':''+rtrim(@pHrsOT_mm)
		if @RoundEnable=''Y''
		begin
			-- Rounding the OT Calculation if <29 means 00  and >30 <59 menas 30
			if (convert(int,@pHrsOT_mm)<30 )
				begin
					select @pHrsOT_mm=''00''
				end
			if  convert(int,@pHrsOT_mm)>30  
			begin
				select @pHrsOT_mm=''30''
			end
		end
	select @pHrsOT =rtrim(@pHrsOT_hh)+'':''+rtrim(@pHrsOT_mm)
if @Exot	is null
begin 
select @Exot=''00:00''
end
delete from tblprocesseddata where pEmpId=@EMP_ID and  pDate=@EMP_date
*/' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveTemporaryShiftAllocation]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveTemporaryShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[RemoveTemporaryShiftAllocation] 
	-- Add the parameters for the stored procedure here
AS
declare @EmployeeId varchar(5)
declare @day1shift varchar(3)
declare @day30shift varchar(3)
declare @emonth varchar(3)
declare @eCount int
declare emp_TempShift cursor for 
select  EmployeeId,day1shift,month,day30shift  from TA_Tbl_TemporaryShiftAllocation
open emp_TempShift
fetch emp_TempShift into @EmployeeId,@day1shift,@emonth,@day30shift
while (@@fetch_status = 0 )
begin
set @eCount=(select  count(shift_ID) from dbo.TA_Tbl_Shift WHERE
       shift_ID = @day1shift )
if @eCount=0
begin
delete   from TA_Tbl_TemporaryShiftAllocation where EmployeeId= @EmployeeId and day1shift=@day1shift and month=@emonth and day1shift <>0 and day1shift<>-1
 end
set @eCount=(select  count(shift_ID) from dbo.TA_Tbl_Shift WHERE
       shift_ID = @day30shift )
if @eCount=0
begin
delete   from TA_Tbl_TemporaryShiftAllocation where EmployeeId= @EmployeeId and day30shift=@day30shift and month=@emonth and day30shift <>0 and day30shift<>-1
 end
  fetch emp_TempShift into @EmployeeId,@day1shift,@emonth,@day30shift
end   
deallocate emp_TempShift' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDuplicateData]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDuplicateData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[RemoveDuplicateData] 
as
declare @CLK_ID int
declare @clk_empID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_outDate datetime
update dbo.TA_Tbl_ProcessedData set processflag=0  where left(HrsWork,2) >23
declare RemoveDuplicate cursor for 
select CLK_ID,clk_empID,clk_indate,clk_outdate from View_Duplicatedata
open RemoveDuplicate
fetch RemoveDuplicate into @CLK_ID,@clk_empID,@clk_indate,@clk_outdate
while (@@fetch_status = 0 )
begin
	delete from  dbo.TA_Tbl_ClockDetails  where  CLK_ID=@CLK_ID
--if len(@clk_indate)>2
--begin
	 	update  dbo.TA_Tbl_ProcessedData set ProcessFlag =0 where  Date=@CLK_inDATE and Employee_Code_Id =@clk_empID
--end
--else
--begin
--		update  dbo.TA_Tbl_ProcessedData set ProcessFlag =0 where  Date=@CLK_outDATE and Employee_Code_Id =@CLK_CARDID
--
--end
  fetch RemoveDuplicate into  @CLK_ID,@clk_empID,@clk_indate,@clk_outdate
end   
deallocate RemoveDuplicate' 
END
GO
/****** Object:  StoredProcedure [dbo].[Temp_UpdateShift]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_UpdateShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Temp_UpdateShift] (@ShiftName varchar(10),@Shift_ShortName varchar(20) )
AS
  UPDATE TA_Tbl_Shift SET Shift_Name=@ShiftName,Shift_ShortName=@Shift_ShortName
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMobileClockIn]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMobileClockIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <05-08-2019 02:41 PM>
-- Description:	<Insert Mobile Clock in and Clock out time>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMobileClockIn]
(
	@EmployeeCodeID varchar(20),
	@ClockDate datetime,
	@Clock_Time varchar(15),
	@PunchType varchar(20),
	@Latitude_value varchar(20),
	@Longitude_value varchar(20),
	@Clock_Address varchar(500)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Insert into Ta_tbl_mobileClockInAndOut values(@EmployeeCodeID,@ClockDate,@Clock_Time,@PunchType,GETDATE(),@Latitude_value,@Longitude_value,@Clock_Address)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry_Group]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntry_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry_Group  
--  Author                 : Sashma  
--  Created On         : 03-May-2011  
--  Description         : This Procedure is used to insert the Manual Time Entry for a group of employees  
-- ================================================================================  
  --Proc_TA_InsertManualTimeEntry_Group ''06/06/2011 12:00:00 AM'',''2011/06/06'',''09:52:16 AM'',''In'','''','''','''',1,0,''IN entry'',0,''06/06/2011 13:52:30'',1,''2'',
CREATE PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry_Group]  
(  
	@ManualEntry_Date DATETIME,  
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@xml xml
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0  
	Declare @Index int
	Set @Index = 0;   
	IF(@InDate = '' '')  
	   BEGIN  
		 EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		 select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@OutTime,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,xm.Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0 
		 from OpenXML(@Index, ''/NewDataSet/Table'')
		 With (EmpID Bigint ''EmpID'',EmployeeId varchar(15) ''EmployeeId'',Status varchar(20) ''Status'') as xm 
		 Exec sp_xml_removedocument @Index
	   END  
	ELSE IF(@OutDate = '' '')  
	  BEGIN  
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,cast(@InReader_Id as nvarchar(10)),
		@Reason,xm.Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0  
		from OpenXML(@Index, ''/NewDataSet/Table'')
		With (EmpID Bigint ''EmpID'',EmployeeId varchar(15) ''EmployeeId'',Status varchar(20) ''Status'') as xm 
		Exec sp_xml_removedocument @Index
	  END  
	ELSE
	  BEGIN
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty)
		select xm.EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,@OutDate,@OutTime,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,xm.Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),0  
		from OpenXML(@Index, ''/NewDataSet/Table'')
		With (EmpID Bigint ''EmpID'',EmployeeId varchar(15) ''EmployeeId'',Status varchar(20) ''Status'') as xm 
		Exec sp_xml_removedocument @Index
	  END
	  Delete FROM TA_Tbl_TempShiftAllocation Where LoginEmployeeId = @UserId
  END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOtType]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_InsertOtType]
	@OtType as varchar(50),
	@OtValue as varchar(25),
	@CompanyID as int,
	@EmpId as int
AS
BEGIN	
	insert into TA_Tbl_OtType (OtType,OtValue,EmpID,IsDeleted,CompanyID) values (@OtType,@OtValue,@EmpID,0,@CompanyID)	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertorUpdateEmployeeLingual]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertorUpdateEmployeeLingual]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		S.Christopher
-- Create date: 28 Nov 07
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertorUpdateEmployeeLingual] 
	-- Add the parameters for the stored procedure here
	@LanguageId int,
    @EmployeeId int
AS
declare @RecordExisting as int
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	set @RecordExisting=(SELECT count(*) FROM TA_Tbl_EmployeeLingual WHERE EmployeeId=@EmployeeId)
    if (@RecordExisting=0)
       begin
           INSERT INTO TA_Tbl_EmployeeLingual(LanguageId, EmployeeId) VALUES(@LanguageId, @EmployeeId)
       end
    else
       begin
           UPDATE TA_Tbl_EmployeeLingual SET LanguageId = @LanguageId WHERE EmployeeId = @EmployeeId
       end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntryForTable]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOnDutyEntryForTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name		: Proc_TA_InsertOnDutyEntryForTable  
--  Author              : Karthikeyan.R
--  Created On			: 08-Mar-2016
--  Description         : This Procedure is used to insert and update the Onduty Entry
--	TableName			: TA_Tbl_OndutyEntry
-- [Proc_TA_InsertOnDutyEntryForTable] ''I'',''0'',''659'',''11-24-2017'',1,0,''11/24/2017'',''09:00'',''11/24/2017'',''14:00'',''اختبارات'',''Approved'',''48'','''',''''
-- ================================================================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntryForTable]
	-- Add the parameters for the stored procedure here
	@type nvarchar(2),
	@Onduty_ID int,
	@Onduty_EmployeeID nvarchar(20),
	@Onduty_EntryDate	datetime,
	@Onduty_Type int,
	@IncludeweekOff int,
	@Onduty_FromDate datetime,
	@Onduty_FromTime nvarchar(50),
	@Onduty_ToDate datetime,
	@Onduty_ToTime nvarchar(50),
	@Onduty_Reason nvarchar(Max),
	@Onduty_Status nvarchar(25),
	@Emp_Id int,
	@From_Session nvarchar(25),
	@To_Session nvarchar(25)
AS
BEGIN
	SET NOCOUNT ON;
	--print ''s''
	DECLARE @Isdel INT  
	SET @Isdel=0  
	declare @OndutyID as int
	DECLARE @sql nvarchar(4000)
	SET @sql = ''''  
	BEGIN
	if(@type=''I'')
	BEGIN
		Declare @YearSettings_Id  int
		select @YearSettings_Id =YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
		INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FromDate,Onduty_FromTime,Onduty_ToDate,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,From_Session,To_Session,YearSettings_Id) 
		VALUES (@Onduty_EmployeeID,cast(@Onduty_EntryDate as nvarchar(20)),CAST(@Onduty_Type as nvarchar(10)),CAST(@IncludeweekOff as nvarchar(10)) ,
		cast(@Onduty_FromDate as nvarchar(20) ), CAST(@Onduty_FromTime as nvarchar(50)),cast(@Onduty_ToDate as nvarchar(20)) ,
		 CAST(@Onduty_ToTime as nvarchar(50)) , CAST(@Onduty_Reason as nvarchar(max)) ,CAST(@Onduty_Status as nvarchar(25)) , CAST(@Isdel as nvarchar(2)) ,getdate(),CAST(@Emp_Id as nvarchar(10)) 
		 ,CAST(@From_Session as nvarchar(25)) ,CAST(@To_Session as nvarchar(25)),@YearSettings_Id)
		select @OndutyID=MAX(Onduty_ID) from TA_Tbl_OndutyEntry
	END
	else
		begin
			SET @sql = @sql + ''update TA_Tbl_OndutyEntry set IncludeWeekOff=N'''''' +CAST(@IncludeweekOff as nvarchar(10)) + '''''',Onduty_Type=N'''''' +CAST(@Onduty_Type as nvarchar(10)) + '''''',Onduty_FromDate=N'''''' +CAST(@Onduty_FromDate as nvarchar(20)) + '''''',Onduty_FromTime=N'''''' +CAST(@Onduty_FromTime as nvarchar(20)) +'''''',Onduty_ToDate=N'''''' +CAST(@Onduty_ToDate as nvarchar(20)) +'''''',Onduty_ToTime=N''''''+CAST(@Onduty_ToTime as nvarchar(20))+'''''',Onduty_Reason=N''''''+CAST(@Onduty_Reason as nvarchar(max)) +'''''',From_Session=N''''''+CAST(@From_Session as nvarchar(20)) +'''''',To_Session=N''''''+CAST(@To_Session as nvarchar(20)) +'''''',Onduty_Status=N''''''+CAST(@Onduty_Status as nvarchar(20)) +'''''',Emp_Id=N'''''' +CAST(@Emp_Id as nvarchar(25)) +'''''' where Onduty_ID=N'''''' +CAST(@Onduty_ID as nvarchar(25)) +''''''''
			EXEC (@sql)	
			set @OndutyID=@Onduty_ID
		end
		select @OndutyID as [Onduty_ID]
	End
	Declare @Onduty_EmployeeID_AutoID int
	select @Onduty_EmployeeID_AutoID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id =@Onduty_EmployeeID and Isdeleted=0 
	if((@Onduty_Status=''Forwarded'' or @Onduty_Status=''Approved'')and @Onduty_EmployeeID_AutoID!=@Emp_Id)
	BEGIN
		DECLARE @orderBy as int 
		DECLARE @OnDutyConversationCount as int 
		SELECT @OnDutyConversationCount=COUNT(*) FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @OndutyID
		SET @orderBy = @OnDutyConversationCount + 1
		INSERT INTO TA_Tbl_OnDutyConversation(OnDutyApplicationId,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@OndutyID, ''Ok'', @orderBy, @Emp_Id,GETDATE())	
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertOnDutyEntry]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertOnDutyEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : Gopinath.K
--  Created On         : 06-Jun-2014
--  Description         : This Procedure is used to insert the Onduty Entry
--	Descriptinos		:	Seperated from Manual Entry Insert due to adding of Shift ID and Shift date seperately
-- [Proc_TA_InsertOnDutyEntry] 787787,''20170817'',''20170817'',''09:00'',''Shift In'',''20170817'',''12:00'',''Shift Out'',0,0,''testing'',0,''Approved'',''20170817'',48,1,1,2,''20170817'',1
-- ================================================================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertOnDutyEntry]  
(  
@ManualEntry_EmployeeId NVARCHAR(20),  
@ManualEntry_Date DATETIME,  
@InDate NVARCHAR(15),  
@InTime NVARCHAR(20), 
@InPunchType NVARCHAR(25),
@OutDate NVARCHAR(15),  
@OutTime NVARCHAR(20),
@OutPunchType NVARCHAR(25),
@InReader_Id INT,  
@OutReader_Id INT,  
@Reason NVARCHAR(max),  
@RouteId INT, 
@Status nVarchar(25),
@UserId INT,
@YearSettings_Id NVARCHAR(25),
@IsOnDuty INT,
@ShiftId NVARCHAR(25),
@ShiftDate NVARCHAR(15),
@OndutyID int
)  
AS  
begin
	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=787
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=788
	END	
	
	
	DECLARE @Isdel INT  
	SET @Isdel=0  
	DECLARE @sql nvarchar(4000)
	SET @sql = ''''    
	IF(@InDate = '' '')  
	   BEGIN  
		 --SET @InDate = NULL  
		 SET @sql = ''''
		 SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)''
		 SET @sql = @sql + '' VALUES('''''' + @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @OutDate + '''''',N'''''' + @OutTime + '''''',N'''''' +@OutPunchType + '''''','''''' + cast(@OutReader_Id as nvarchar(10)) +  '''''',N'''''' 
		 SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(Getdate() as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''' ,'''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@ShiftId as nvarchar(10)) + '''''','''''' + cast(@ShiftDate as nvarchar(20)) + '''''',''''''+ cast(@OndutyID as nvarchar(20)) + '''''')'' 
	   END  
	ELSE IF(@OutDate = '' '')  
	  BEGIN  
	   --SET @OutDate = NULL  
		SET @sql = ''''
		SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)''
		SET @sql = @sql + '' VALUES(''''''+ @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @InDate + '''''',N'''''' + @InTime + '''''',N'''''' + @InPunchType + '''''','''''' + cast(@InReader_Id as nvarchar(10)) +  '''''',N'''''' 
		SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(Getdate() as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''','''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@ShiftId as nvarchar(10)) + '''''','''''' + cast(@ShiftDate as nvarchar(20)) + '''''',''''''+ cast(@OndutyID as nvarchar(20)) + '''''')''   
	  END  
	ELSE
	  BEGIN
		SET @sql = ''''
		SET @sql = @sql + ''INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,shift_ID,Shift_Date,Onduty_ID)''
		SET @sql = @sql + '' VALUES(''''''+ @ManualEntry_EmployeeId + '''''','''''' + cast(@ManualEntry_Date as nvarchar(20)) + '''''',N'''''' + @InDate + '''''',N'''''' + @InTime + '''''',N'''''' + @InPunchType + '''''',N'''''' + @OutDate + '''''',N'''''' + @OutTime + '''''',N'''''' +@OutPunchType + '''''','''''' + cast(@InReader_Id as nvarchar(10)) +  '''''','''''' + cast(@OutReader_Id as nvarchar(10)) +  '''''',N'''''' 
		SET @sql = @sql + @Reason + '''''',N'''''' +@Status + '''''','''''' + cast(@RouteId as nvarchar(20)) + '''''',''''N'''','''''' + cast(@Isdel as nvarchar(10)) + '''''','''''' + cast(Getdate() as nvarchar(20)) + '''''','''''' + cast(@UserId as nvarchar(10)) + '''''','''''' + cast(@YearSettings_Id as nvarchar(10)) + '''''','''''' + cast(@IsOnDuty as nvarchar(10)) + '''''','''''' + cast(@ShiftId as nvarchar(10)) + '''''','''''' + cast(@ShiftDate as nvarchar(20)) + '''''',''''''+ cast(@OndutyID as nvarchar(20)) + '''''')''   
	  END
	EXEC (@sql)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNews]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertNews]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
	created by : senthil
	created on : 10 Aug 2007
	Description : Inserting and updating news/Events
*/
CREATE procedure [dbo].[Proc_TA_InsertNews]
(
	@newsEventFromDate as datetime,
    @newsEventToDate as datetime,
	@newsEventTitle as nvarchar(254),
	@newsEventDescription as nvarchar(500),
	@newsEventActive as bit,
	@newsEventImage as nvarchar(254),
	@leftNewsEvent as bit,
	@rightNewsEvent as bit,
	@leftBanner as bit,
	@rightBanner as bit,
	@employeeId as decimal(18,0),
	@opr as nvarchar(1),
	@newsEventId as int
)
as 
Begin
	declare @sql as varchar(3000)
    declare @dotposition as varchar(25)
    declare @strreplace as varchar(25)
    declare @result as varchar(25)
    declare @nextId as int
	if @opr=''I''
		Begin
            insert into ta_tbl_newsEvents (newsEventFromDate,newsEventToDate,newsEventTitle,newsEventDescription,newsEventActive,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,Emp_Id,Isdeleted) values (@newsEventFromDate,@newsEventToDate,@newsEventTitle,@newsEventDescription,@newsEventActive,@leftNewsEvent,@rightNewsEvent,@leftBanner,@rightbanner,@employeeId,0)
            if (@newsEventImage <> '''')
             begin
               set @nextId = (select @@identity)
               set @dotposition = CHARINDEX(''.'',@newsEventImage)
               set @strreplace = SUBSTRING(@newsEventImage,1,@dotposition-1)
               set @result = REPLACE(@newsEventImage,@strreplace,@nextId)
			   update ta_tbl_newsEvents set newsEventImage=@result where newsEvent_Id=@nextId
             end
			--insert into ta_tbl_newsEvents (newsEventDate,newsEventTitle,newsEventDescription,newsEventActive,newsEventImage,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,employee_Id,Isdeleted) values (@newsEventDate,@newsEventTitle,@newsEventDescription,@newsEventActive,@newsEventImage,@leftNewsEvent,@rightNewsEvent,@leftBanner,@rightbanner,@employeeId,0)
		--	set @sql = ''insert into ta_tbl_newsEvents (newsEventDate,newsEventTitle,newsEventDescription,newsEventActive,newsEventImage,leftNewsEvent,rightNewsEvent,leftBanner,rightbanner,employee_Id,Isdeleted) values ('' + cast (@newsEventDate as nvarchar(25)) + '',N'''''' + @newsEventTitle + '','' + @newsEventDescription + '','' + cast(@newsEventActive as nvarchar(25)) + '','' + @newsEventImage + '','' + cast (@leftNewsEvent as nvarchar(25)) + '','' + cast (@rightNewsEvent as nvarchar(25))  + '','' +  cast (@leftBanner as nvarchar(25))  + '','' +  cast (@rightbanner as nvarchar(25))  + '','' +  cast (@employeeId as nvarchar(25)) + '',0)''
		--	exec(@sql)
		End
	else
		Begin
			update ta_tbl_newsEvents set newsEventFromDate=@newsEventFromDate,newsEventToDate=@newsEventToDate,newsEventTitle=@newsEventTitle,newsEventDescription=@newsEventDescription,newsEventActive=@newsEventActive,newsEventImage=@newsEventImage,leftNewsEvent=@leftNewsEvent,rightNewsEvent=@rightNewsEvent,leftBanner=@leftBanner,rightbanner=@rightBanner,Emp_Id=@employeeId,Isdeleted=0 where newsEvent_Id=@newsEventId
		End
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreAttandanceCode]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_RestoreAttandanceCode]
	@AttandanceID as int,	
	@EmpID as int
AS
BEGIN
	update  TA_Tbl_AttandanceCode set 
				IsDeleted=0,				
				EmpID=@EmpID where 
		AttandanceID=@AttandanceID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ResetPassword]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ResetPassword]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_ResetPassword](@EmpId varchar(10),@Password varchar(30))  
 -- Add the parameters for the stored procedure here  
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
UPDATE TA_Tbl_Employee SET Emp_password=@Password WHERE Employee_Code_Id=@EmpId  
select count(*)  as ResetCount from TA_Tbl_Employee WHERE Employee_Code_Id=@EmpId  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ResetBonusLeaveForService]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ResetBonusLeaveForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 07-11-2014
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ResetBonusLeaveForService]
	@Employee_Code_Id varchar(50),
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	--RETRY: -- Label RETRY
	--BEGIN TRANSACTION
	--	BEGIN TRY
	UPDATE TA_Tbl_ProcessedData SET  fnAttendanceCode=''Absent'', anAttendanceCode=''Absent'', Attendance = ''Absent'', Status = NULL 
	WHERE Employee_Code_Id = @Employee_Code_Id AND Status = ''BL'' AND Date > @dtmDate
	--	COMMIT TRANSACTION
	--	END TRY
	--BEGIN CATCH	
	--	ROLLBACK TRANSACTION
	--	IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
	--	BEGIN
	--		WAITFOR DELAY ''00:00:00.05'' -- Wait for 5 ms
	--		GOTO RETRY -- Go to Label RETRY
	--	END
	--END CATCH
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ReprocessEmpData]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ReprocessEmpData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_ReprocessEmpData]  
(   
	@FromDate Datetime,  
	@ToDate Datetime,  
	@EmployeeCodeId varchar(50)   
)  
AS  
BEGIN
	set nocount on
	Declare @SwipeCardNumber varchar(50)
	select @SwipeCardNumber=SwipeCardNo from ta_tbl_employee where Employee_Code_Id=@EmployeeCodeId and isdeleted=0
	--select @FromDate,@ToDate,@EmployeeCodeId
	DELETE PD FROM TA_Tbl_ProcessedData PD Where PD.Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) And PD.Employee_Code_Id=@SwipeCardNumber
	Update TA_Tbl_Clk_RawData Set CLK_FLAG=0,CLK_PROCESS=0 Where CLK_DATE BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	and CLK_CARDID=@SwipeCardNumber
	Delete CD from TA_Tbl_ClockDetails CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	Delete CD from ta_tbl_MatchedPunches CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN isnull(@FromDate,@Todate) AND isnull(@ToDate,@FromDate) 
	UPDATE MT SET MT.Clk_Process = ''N'' from TA_Tbl_ManualTimeEntry MT
	Inner join TA_Tbl_Employee E on E.Employee_Code_Id = MT.ManualTimeEntry_Employee_Id 
	AND ((MT.ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,isnull(@FromDate,@Todate)) AND DateAdd(d,1,isnull(@ToDate,@FromDate) )) 
	OR (MT.ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,isnull(@FromDate,@Todate)) AND DateAdd(d,1,isnull(@ToDate,@FromDate) )))  
	where MT.ManualTimeEntry_Employee_Id=@EmployeeCodeId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualTimeEntry]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualTimeEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_UpdateManualTimeEntry 329,''10101'',''09/01/2008'',''08/29/2008'',''08:11 AM'',''In'','''','''','''',28,0,''df'',''09/01/2008 10:41 AM'',''6''
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualTimeEntry] 
(
	@MID int,
	@ManualEntry_EmployeeId nvarchar(20),
	@ManualEntry_Date nvarchar(15),
	@InDate nvarchar(15),
	@InTime nvarchar(20),
	@InPunchType nvarchar(100),
	@OutDate nvarchar(15),
	@OutTime nvarchar(20),
	@OutPunchType nvarchar(100),
	@InReader_Id int,
	@OutReader_Id int,
	@Reason nvarchar(255),
	@TimeStamp DateTime,
	@UserId int
)  
AS  
BEGIN
	SET NOCOUNT ON;
	DECLARE @sql NVARCHAR(4000)
	SET @sql = '''' 
	IF(@InDate = '''')
	 BEGIN  
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId,
											ManualTimeEntry_Date= @ManualEntry_Date,
											ManualTimeEntry_InDate=NULL,
											ManualTimeEntry_InTime=NULL,
											ManualTimeEntry_InPunchType=NULL,
											ManualTimeEntry_OutDate= @OutDate ,
											ManualTimeEntry_OutTime= @OutTime ,
											ManualTimeEntry_OutPunchType=@OutPunchType,
											ManualTimeEntry_InReaderId=NULL,
											ManualTimeEntry_OutReaderId= cast(@OutReader_Id as nvarchar(20)),
											ManualTimeEntry_Reason=@Reason ,
											modify_date= cast(@TimeStamp as nvarchar(20)), 
											modify_By= cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id= cast(@MID as nvarchar(20))
	 END  
	ELSE IF(@OutDate = '''')  
	 BEGIN  
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId, 
											ManualTimeEntry_Date= @ManualEntry_Date ,
											ManualTimeEntry_InDate=@InDate ,
											ManualTimeEntry_InTime= @InTime,
											ManualTimeEntry_InPunchType= @InPunchType ,
											ManualTimeEntry_OutDate=NULL,
											ManualTimeEntry_OutTime=NULL,
											ManualTimeEntry_OutPunchType=NULL,
											ManualTimeEntry_InReaderId= cast(@InReader_Id as nvarchar(20)),
											ManualTimeEntry_OutReaderId=NULL,
											ManualTimeEntry_Reason=@Reason,
											modify_date= cast(@TimeStamp as nvarchar(20)),
											modify_By= cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id= cast(@MID as nvarchar(20))
	 END
	ELSE
	  BEGIN
		UPDATE TA_Tbl_ManualTimeEntry SET	ManualTimeEntry_Employee_Id= @ManualEntry_EmployeeId , 
											ManualTimeEntry_Date= @ManualEntry_Date ,
											ManualTimeEntry_InDate=@InDate,
											ManualTimeEntry_InTime=@InTime,
											ManualTimeEntry_InPunchType=@InPunchType,
											ManualTimeEntry_OutDate=@OutDate,
											ManualTimeEntry_OutTime=@OutTime,
											ManualTimeEntry_OutPunchType=@OutPunchType,
											ManualTimeEntry_InReaderId=cast(@InReader_Id as nvarchar(20)),
											ManualTimeEntry_OutReaderId=cast(@OutReader_Id as nvarchar(20)),
											ManualTimeEntry_Reason=@Reason,
											modify_date=cast(@TimeStamp as nvarchar(20)), 
											modify_By=cast (@UserId as nvarchar(20)) 
		WHERE ManualTimeEntry_Id=cast(@MID as nvarchar(20))
	  END
	EXEC(@sql)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateManualNotation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateManualNotation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Modified by:R.Manikandan
-- Create DATE:22-10-2015 12.50 PM
-- Description:This function will work above 2005 version only 
-- I am passing intime\outtime also into clkdate. This is major change. it wont support for previous versions
-- if sql server is above 2005 means, we can change the existing procedure like this, but we can''t use this procedure directly.
-- Proc_Ta_UPDATEManualNotation N''105'',''2015-10-20 02:11:00 AM'',''O'',''M''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateManualNotation]
	@inSwipeCardNo VARCHAR(50),
	@Clk_DATE VARCHAR(30),	
	@StrType CHAR(1),
	@strClk_Status CHAR(1)
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		DECLARE @ShIFtId INT
		DECLARE @ShIFtStartDATE DATETIME
		DECLARE @ShIFtEndDATE DATETIME
		DECLARE @isNightShIFt INT
		SET @isNightShIFt =0
		SELECT @ShIFtId=ShIFt_Id FROM TA_Tbl_ProcessedData WHERE CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE) AND Employee_Code_Id=@inSwipeCardNo
		SELECT @ShIFtStartDATE=CAST(ShIFt_StartTime as DATETIME),@ShIFtEndDATE=CAST(ShIFt_EndTime as DATETIME)FROM TA_Tbl_ShIFt WHERE ShIFt_Id=@ShIFtId AND Isdeleted=0
		IF( (DATEPART(HOUR,@ShIFtStartDATE) between 12 AND 23) AND DATEPART(HOUR,@ShIFtEndDATE) between 0 AND 11 )
		BEGIN
			SET @isNightShIFt=1
		END
		IF(@strType=''I'')
			BEGIN
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_InDATE+ManualTimeEntry_InTime) = CONVERT(DATETIME,@Clk_DATE,0) AND Isdeleted=0 AND ManualTimeEntry_Status=''Approved'')>0)
					BEGIN					
						UPDATE TA_Tbl_ProcessedData SET InNotation=@strClk_Status 
						WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
					END			
			END
		ELSE
			BEGIN
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_OutDATE+ManualTimeEntry_OutTime)=CONVERT(DATETIME,@Clk_DATE,0) AND Isdeleted=0 
				AND ManualTimeEntry_Status=''Approved'')>0)
				BEGIN
					UPDATE TA_Tbl_ProcessedData SET OutNotation=@strClk_Status 
					WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
				end
				IF((SELECT COUNT(*) FROM Ta_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Employee_Id = @inSwipeCardNo 
				AND (ManualTimeEntry_OutDATE+ManualTimeEntry_OutTime)=DATEADD(d,1,CONVERT(DATETIME,@Clk_DATE,0)) AND Isdeleted=0 AND ManualTimeEntry_Status=''Approved'')>0)
					BEGIN
						UPDATE TA_Tbl_ProcessedData SET OutNotation=@strClk_Status 
						WHERE Employee_Code_Id=@inSwipeCardNo AND CONVERT(DATE,DATE)= CONVERT(DATE,@Clk_DATE)
					END
			END
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
	END CATCH
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction_Group 
Description : Update Manual Time Entry Application Details for a group of Employees 
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Sashma.S 
Created On : 04-May-2011 
[Proc_TA_UpdateManualEntryApplicationSanction_Group] ''Approved'','''',1,''<DocumentElement>
  <Table>
    <ManualTimeEntry_Id>453</ManualTimeEntry_Id>
  </Table>
</DocumentElement>''
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction_Group] 
( 
	@Status NVARCHAR(250), 
	@Remarks NVARCHAR(250),
	@auEmpId INT,
	@xml xml 
)
AS 
BEGIN
SET NOCOUNT ON;
	DECLARE @Index int
	set @Index = 0 
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	declare @UpdateCount int
	-- updates the status of the manual entry if is not processed
	UPDATE TA_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@auEmpId as nvarchar(20))
	from OpenXML(@Index, ''/DocumentElement/Table'')
	with (ManualTimeEntry_Id bigint ''ManualTimeEntry_Id'') as xm
	inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
	--Added this new line after gettting scuf client requisition
	where Clk_Process = ''N''
	-- and @auEmpId!=1
	set @UpdateCount = @@ROWCOUNT
	Exec sp_xml_removedocument @Index
	set @Index = 0 
	EXEC sp_xml_preparedocument @Index OUTPUT, @xml
	declare @ProcessedDataCount int 
	--select the manual entry which is already processed.
	set @ProcessedDataCount = (select count(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
	from OpenXML(@Index, ''/DocumentElement/Table'')
	with (ManualTimeEntry_Id bigint ''ManualTimeEntry_Id'') as xm
	inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
	where Clk_Process = ''Y'')
	select @UpdateCount as UpdateCount,@ProcessedDataCount ProcessedDataCount
	Exec sp_xml_removedocument @Index 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateManualEntryApplicationSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction  
Description : Update Manual Time Entry Application Details of Employees Based on their ManualTimeEntry_Id  
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Kumuthini.L  
Created On : 09-Jan-09  
Modified By : Sashma   
Modified On : 04-May-2011  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_UpdateManualEntryApplicationSanction]  
(
@ManualTimeEntry_Id INT,  
@Status NVARCHAR(250),  
@Remarks NVARCHAR(250),
@auEmpId INT  
)
AS 
BEGIN
	SET NOCOUNT ON;
	if not exists(SELECT * FROM TA_Tbl_ManualTimeEntry WHERE ManualTimeEntry_Id = @ManualTimeEntry_Id AND Clk_Process = ''Y'')  
	BEGIN
			UPDATE TA_Tbl_ManualTimeEntry SET ManualTimeEntry_Status= @Status ,ManualTimeEntry_Remarks= @Remarks ,Emp_Id=cast(@auEmpId as nvarchar(20)) WHERE ManualTimeEntry_Id= cast (@ManualTimeEntry_Id  as nvarchar(10))
		return 0
	END
	else
	BEGIN
	   return 1
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_updateLevels]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_updateLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  senthil  
-- Create date: 08-Aug-2007  
-- Description: update level name  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_updateLevels]  
 @opr as varchar(1),  
 @lid as int,  
 @lName as nvarchar(100),
 @emp_id as nvarchar(25) 
AS  
BEGIN  
/*   
 if (@opr=''C'')  
  Begin  
   select count(*) as recCount from ta_tbl_level where levelId!=@lid and levelName=@lName and isDeleted=0  
  End  
 Else  
  Begin  
   update ta_tbl_level set levelname=@lName where levelId=@lid  
  End  
*/  
 declare @recCount as int  
 set @recCount = (select count(*) from ta_tbl_level where levelId!=@lid and levelName=@lName and isDeleted=0)  
 if (@recCount=0)  
  Begin  
   --update ta_tbl_level set levelname=@lName where levelId=@lid  
	declare @sql as nvarchar(1000)
	set @sql = ''update ta_tbl_level set emp_id=''+ @emp_id+'', levelname= N'''''' + @lName +'''''' where levelId=''+ cast(@lid as nvarchar(25))
	exec(@sql)
  End  
 select @recCount as recCount  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOvertimeHours]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOvertimeHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create PROCEDURE [dbo].[Proc_TA_UpdateOvertimeHours]
(
    @intOTHrs		int,
    @intWOFOTHrs	int,
    @intHDOTFrs		int,
    @OTHours		varchar(5),
    @WOFOTHours		varchar(5),
    @HDOTHours		varchar(5),
    @intUpOTHrs		int,
    @intUpWOFOTHrs	int,
    @intUpHDOTFrs	int,
    @UpOTHours		varchar(5),
    @UpWOFOTHours	varchar(5),
    @UpHDOTHours	varchar(5),
    @Pro_RecordID	bigint,
    @Employee_code_id varchar(50),
    @Date varchar(20),
    @Modified_Spec_NormOTMins1 int,
	@Modified_Spec_NormOTMins2 int,
	@Modified_Spec_OffOTMins1 int,
	@Modified_Spec_OffOTMins2 int,
	@Modified_Spec_HolOTMins1 int,
	@Modified_Spec_HolOTMins2 int,
	@Modified_Spec_NormOTHrs1 varchar(10),
	@Modified_Spec_NormOTHrs2 varchar(10),
	@Modified_Spec_OffOTHrs1 varchar(10),
	@Modified_Spec_OffOTHrs2 varchar(10),
	@Modified_Spec_HolOTHrs1 varchar(10),
	@Modified_Spec_HolOTHrs2 varchar(10),
	@uploadedEmpid bigInt
)
 AS
BEGIN
	UPDATE TA_Tbl_ProcessedData SET ActNormOTMins=@intOTHrs,ActOffOTMins=@intWOFOTHrs,
	ActHolOTMins=@intHDOTFrs,ActOTMins=(@intOTHrs + @intWOFOTHrs + @intHDOTFrs),ActHrsOT=''00:00'',
	ActNormOT=@OTHours,ActOffOT=@WOFOTHours,ActHolOT=@HDOTHours,
	NormOTMins=@intUpOTHrs,OffOTMins=@intUpWOFOTHrs,HolOTMins=@intUpHDOTFrs,
	OTMins=(@intUpOTHrs + @intUpWOFOTHrs + @intUpHDOTFrs),NormOT=@UpOTHours,OffOT=@UpWOFOTHours,
	HolOT=@UpHDOTHours WHERE Process_Rec_ID=@Pro_RecordID;
    --EXEC (@Query)
    IF NOT EXISTS(SELECT Modified_Spec_NormOTMins1 FROM Ta_tbl_specialOvertimeDetails where Employee_code_id=@Employee_code_id and DATE=@Date)
    BEGIN
		INSERT INTO Ta_tbl_specialOvertimeDetails 
		(Employee_code_id,Date,Modified_Spec_NormOTMins1,Modified_Spec_NormOTMins2,Modified_Spec_OffOTMins1,Modified_Spec_OffOTMins2,
		Modified_Spec_HolOTMins1,Modified_Spec_HolOTMins2,Modified_Spec_NormOTHrs1,
		Modified_Spec_NormOTHrs2,Modified_Spec_OffOTHrs1,Modified_Spec_OffOTHrs2,Modified_Spec_HolOTHrs1,Modified_Spec_HolOTHrs2,
		Inserted_By,Inserted_Date)
		VALUES
		(
			@Employee_code_id,
			@Date,
			@Modified_Spec_NormOTMins1,
			@Modified_Spec_NormOTMins2,
			@Modified_Spec_OffOTMins1,
			@Modified_Spec_OffOTMins2,
			@Modified_Spec_HolOTMins1,
			@Modified_Spec_HolOTMins2,
			@Modified_Spec_NormOTHrs1,
			@Modified_Spec_NormOTHrs2,
			@Modified_Spec_OffOTHrs1,
			@Modified_Spec_OffOTHrs2,
			@Modified_Spec_HolOTHrs1,
			@Modified_Spec_HolOTHrs2,
			@uploadedEmpid,
			GETDATE()			
		)
    END
    ELSE
    BEGIN
		UPDATE Ta_tbl_specialOvertimeDetails SET
			Modified_Spec_NormOTMins1	=@Modified_Spec_NormOTMins1,
			Modified_Spec_NormOTMins2	=@Modified_Spec_NormOTMins2,
			Modified_Spec_OffOTMins1	=@Modified_Spec_OffOTMins1,
			Modified_Spec_OffOTMins2	=@Modified_Spec_OffOTMins2,
			Modified_Spec_HolOTMins1	=@Modified_Spec_HolOTMins1,
			Modified_Spec_HolOTMins2	=@Modified_Spec_HolOTMins2,
			Modified_Spec_NormOTHrs1	=@Modified_Spec_NormOTHrs1,
			Modified_Spec_NormOTHrs2	=@Modified_Spec_NormOTHrs2,
			Modified_Spec_OffOTHrs1		=@Modified_Spec_OffOTHrs1,
			Modified_Spec_OffOTHrs2		=@Modified_Spec_OffOTHrs2,
			Modified_Spec_HolOTHrs1		=@Modified_Spec_HolOTHrs1,
			Modified_Spec_HolOTHrs2		=@Modified_Spec_HolOTHrs2,
			Modified_By=@uploadedEmpid,
			Modified_Date=GETDATE()
			WHERE Employee_code_id=@Employee_code_id and DATE=@Date
    END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOtType]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_UpdateOtType] 
	@OtTypeID as int,
	@OtType as varchar(25),
	@OtValue as varchar(25),
	@CompanyID as int,
	@EmpId as int
AS
BEGIN	
	update  TA_Tbl_OtType set 
			OtType=@OtType,
			OtValue=@OtValue,
			CompanyID=@CompanyID,
			EmpID=@EmpID
		where OtTypeID=@OtTypeID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOTRoundoffSettings]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOTRoundoffSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateOTRoundoffSettings]
	-- Add the parameters for the stored procedure here
	@shiftSettingId int, 
	@startTime nvarchar(5),
	@endTime nvarchar(5),
	@startMins float,
    @endMins float,
	@roundedAs nvarchar(5)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	INSERT INTO TA_Tbl_OTRoundoffSettings(ShiftSettingId,StartTime,EndTime,StartMins,EndMins,RoundedAs)  VALUES(@shiftSettingId,@startTime,@endTime,@startMins,@endMins,@roundedAs) 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateOnDutyApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateOnDutyApplicationConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Gopinath.k
-- Create date:16Jun2014
-- Description:	used for adding the OD conversation.
-- Proc_TA_UpdateOnDutyApplicationConversation 5,''Pending'',''Test Remarks'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateOnDutyApplicationConversation] 
	-- Add the parameters for the stored procedure here
	@ondutyApplicationId bigint,
	@status nvarchar(50),
	@remarks nvarchar(1050),
	@empAutoId int
AS
DECLARE @OnDutyConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	SET NOCOUNT ON;
	SELECT @OnDutyConversationCount=COUNT(*) FROM TA_Tbl_OnDutyConversation WHERE OnDutyApplicationId = @ondutyApplicationId
	SET @orderBy = @OnDutyConversationCount + 1
	INSERT INTO TA_Tbl_OnDutyConversation(OnDutyApplicationId,Comments,OrderBy,Emp_Id,TimeStamp) VALUES(@ondutyApplicationId, @remarks, @orderBy, @empAutoId,GETDATE())
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/* 
Procedure Name : Proc_TA_UpdateManualEntryApplicationSanction_Group 
Description : Update Manual Time Entry Application Details for a group of Employees 
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Sashma.S 
Created On : 04-May-2011 
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_UpdateODEntryApplicationSanction_Group_SA] 
( 
@Status NVARCHAR(250), 
@Remarks NVARCHAR(250),
@auEmpId INT,
@xml xml 
)
AS 
BEGIN
DECLARE @Index int
set @Index = 0 
EXEC sp_xml_preparedocument @Index OUTPUT, @xml
SET NOCOUNT ON;
declare @UpdateCount int
-- updates the status of the manual entry if is not processed
UPDATE TA_Tbl_ManualTimeEntry set ManualTimeEntry_Status=@Status,ManualTimeEntry_Remarks=@Remarks,Emp_Id=cast(@auEmpId as nvarchar(20))
from OpenXML(@Index, ''/DocumentElement/Table'')
with (ManualTimeEntry_Id bigint ''ManualTimeEntry_Id'') as xm
inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id
set @UpdateCount = @@ROWCOUNT
Exec sp_xml_removedocument @Index
set @Index = 0 
EXEC sp_xml_preparedocument @Index OUTPUT, @xml
declare @ProcessedDataCount int 
--select the manual entry which is already processed.
set @ProcessedDataCount = (select count(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
from OpenXML(@Index, ''/DocumentElement/Table'')
with (ManualTimeEntry_Id bigint ''ManualTimeEntry_Id'') as xm
inner join TA_Tbl_ManualTimeEntry on xm.ManualTimeEntry_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id)
select @UpdateCount as UpdateCount,@ProcessedDataCount ProcessedDataCount
Exec sp_xml_removedocument @Index 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAddlWeekoff]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAddlWeekoff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DeleteAddlWeekoff  
Description : delete additional week off - in activate
Tables Included : TA_Tbl_Additional_WeeklyOff  
Created By : Janakaraj.P 
Created On : 14-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAddlWeekoff]
(
	@type nvarchar(20),
	@AddlWeekoffID INT,
    @auditEmpId int
)
AS
IF(@type=''TemporaryDelete'')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Isdeleted=1, Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
ELSE IF(@type=''PermanentDelete'')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
		DELETE FROM TA_Tbl_Additional_WeeklyOff  WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
ELSE IF(@type=''Restore'')
	BEGIN
		UPDATE TA_Tbl_Additional_WeeklyOff SET Isdeleted=0, Emp_Id = @auditEmpId WHERE Addl_WeeklyOff_Id=@AddlWeekoffID
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Author : Kumuthini.L
-- Procedure Name : Proc_TA_DeleteAccessDeniedSettingEntries
-- Tables Used : TA_Tbl_AccessDeniedSettings
-- Created On : 13-Mar-2008
-- Purpose : Used to delete the Access Denied Entries
CREATE PROCEDURE [dbo].[Proc_TA_DeleteAccessDeniedSettingEntries]
(
    @AccessDeniedIds NVARCHAR(1000)
)
AS
BEGIN
    DELETE FROM TA_Tbl_AccessDeniedSettings WHERE AccessDenied_Id IN (@AccessDeniedIds)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Delete_CompanyDetailsForService]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Delete_CompanyDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: <22-09-2013,04.13 PM,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Delete_CompanyDetailsForService]
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM Ta_Tbl_DataProcessCompanyLevelTemp
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteCountry]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteCountry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DeleteCountry  
Description : delete country  
Tables Included : TA_Tbl_Lookup  
Created By : Arun Vinoth.T  
Created On : 16-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteCountry]
(
@Type CHAR(1),		
@Id INT=0,
@Ids NVARCHAR(25)
)
AS
DECLARE @del NVARCHAR
SET @del=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
		BEGIN
			UPDATE TA_Tbl_Lookup
			SET IsDeleted=@del 
			WHERE ID=@Id
		END
ELSE IF (@Type=''C'')
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_Lookup SET IsDeleted= '' + @del + '' WHERE ID IN (''+ @Ids +'')''
			EXEC (@Query)
		END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormatUpdation]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateandTimeFormatUpdation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_DateandTimeFormatUpdation  
Description : update the table TA_Tbl_DateandTimeFormat
Tables Included : TA_Tbl_DateandTimeFormat  
Created By : S.Christopher  
Created On : 10-Oct-07
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DateandTimeFormatUpdation]   
 -- Add the parameters for the stored procedure here  
    @DateFormat varchar(15),   
    @TimeFormat varchar(15),  
    @isDomain int,
    @DomainName nvarchar(500),
    @DomainAdminUserName nvarchar(500),
    @DomainAdminPassword nvarchar(1000),
    @EmpId int  
AS  
declare @sql as nvarchar(3000)
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
    -- Insert statements for procedure here  
 if(select count(*) from TA_Tbl_DateandTimeFormat)>0  
begin
     --update TA_Tbl_DateandTimeFormat set DateFormat = @DateFormat, TimeFormat = @TimeFormat, Time_Stamp = getdate(), EmpId = @EmpId  
set @sql=''update TA_Tbl_DateandTimeFormat set DateFormat =N'''''' +  @DateFormat + '''''', TimeFormat =N'''''' + @TimeFormat + '''''', Time_Stamp ='''''' + cast(getdate() as varchar(25)) + '''''', Emp_Id ='''''' + cast(@EmpId as varchar(25)) + '''''', isDomain=''+ cast(@isDomain as varchar(25)) +'', DomainName=N'''''' + @DomainName + '''''', DomainAdminUserName=N'''''' + @DomainAdminUserName + '''''', DomainAdminPassword=N'''''' + @DomainAdminPassword + '''''''' 
exec(@sql)
end
 else
begin  
   set @sql=''insert into TA_Tbl_DateandTimeFormat(DateFormat, TimeFormat, Time_Stamp, Emp_Id, isDomain, DomainName, DomainAdminUserName, DomainAdminPassword) values(N'''''' + @DateFormat + '''''',N'''''' + @TimeFormat + '''''','''''' + cast(getdate() as varchar(25)) + '''''','''''' + cast(@EmpId as varchar(25)) + '''''','''''' + cast(@isDomain as varchar(25)) + '''''' ,'''''' + @DomainName + '''''','''''' + @DomainAdminUserName + '''''','''''' + @DomainAdminPassword + '''''') ''
exec(@sql)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DateandTimeFormat]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DateandTimeFormat]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_DateandTimeFormat  
Description : select date and time format
Tables Included : TA_Tbl_DateandTimeFormat  
Created By : S.Christopher  
Created On : 10-Oct-07
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DateandTimeFormat] 
AS
BEGIN
	SET NOCOUNT ON;
	SELECT DateFormat, TimeFormat,isdomain,DomainName,DomainAdminUserName,DomainAdminPassword FROM TA_Tbl_DateandTimeFormat
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpType]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpType]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpType] 
(
	@todat datetime,@Employee_Code_Id varchar(50),@employeeType int
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	TypeId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '''')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + '' And SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
--		End
--	if not(@EmployeeId='''' or @EmployeeId=''0'')  
--		begin  
--			set @sqlCommon = @sqlCommon + '' and (Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
--		end 
if (@Employee_Code_Id<>'''')
		if(@employeeType<>0 and @employeeType!='''')
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	and EType.TypeId=@employeeType
		End
		else
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))
		End	
else 
	Begin
	if(@employeeType<>0 and @employeeType!='''')
		BEGIN	
		INSERT @Emptest
		select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
		and EType.TypeId=@employeeType
		End
		else 
		Begin
		INSERT @Emptest
	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null	
	end 
	End
RETURN
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpLevel]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpLevel]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpLevel] 
(
	@todat datetime,@Employee_Code_Id varchar(50)
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	LevelId int,
	EffectiveDate datetime,
	Employee_Code_Id varchar(50),
	SwipeCard varchar(50)
)
AS
BEGIN
if (@Employee_Code_Id<>'''')
	begin	
		INSERT @Emptest
		select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	
	End
else 
BEGIN
		INSERT @Emptest
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	END
RETURN
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpDesignation]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpDesignation]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpDesignation] 
(
	@todat datetime,@Employee_Code_Id varchar(50),@DesignationId varchar(50)
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	DesignationId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '''')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + '' And SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
--		End
--	if not(@EmployeeId='''' or @EmployeeId=''0'')  
--		begin  
--			set @sqlCommon = @sqlCommon + '' and (Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
--		end 
if (@Employee_Code_Id<>'''')
if(@DesignationId<>0 and @DesignationId!='''')
		BEGIN	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100)) and ED.DesignationId=@DesignationId
		End
		else
	begin	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))	
	End
else 
if(@DesignationId<>0 and @DesignationId!='''')
		BEGIN	
		INSERT @Emptest
			select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	    and ED.DesignationId=@DesignationId
		End
		else
	Begin
		INSERT @Emptest
		select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null		
	end 
RETURN
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_EmpCategory]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_EmpCategory]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 19/12/2013
-- Description:	Function done fro SQL Query optimization
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_EmpCategory] 
(
	@todat datetime,@Employee_Code_Id varchar(50), @employeeCategory int
)
RETURNS 
@Emptest TABLE 
(
	EmployeeId int,
	CategoryId int,
	EffectiveDate datetime,
	Employee_Code_Id nvarchar(50),
	SwipeCardNo nvarchar(50)
)
AS
BEGIN
--If Not (@EmpSwipeCard = '''')  
--		Begin  
--			Set @sqlCommon = @sqlCommon + '' And SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
--		End
--	if not(@EmployeeId='''' or @EmployeeId=''0'')  
--		begin  
--			set @sqlCommon = @sqlCommon + '' and (Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
--		end 
if (@Employee_Code_Id<>'''')
		if(@employeeCategory<>0 and @employeeCategory!='''')
		BEGIN	
		INSERT @Emptest
		select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100)) and ECategory.CategoryId=@employeeCategory
		End
		else
		BEGIN	
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and Employee_Code_Id =cast(@Employee_Code_Id as nvarchar(100))
		End	
else 
	Begin
	if(@employeeCategory<>0 and @employeeCategory!='''')
		BEGIN	
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
		and ECategory.CategoryId=@employeeCategory
		End
		else 
		Begin
		INSERT @Emptest
	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ECategory.CategoryId is not null
	end 
	End
RETURN
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_AbsentDate]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_AbsentDate]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 26-July-2010
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_AbsentDate] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @Absent as varchar(8000)
--set @Absent=''''
 SELECT @Absent = ISNULL(@Absent + '', '', '''') + 
 case when  FNAttendanceCode=''Absent'' and ANAttendanceCode=''Absent'' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+''(FS)'')
      when  FNAttendanceCode=''Absent'' and ANAttendanceCode <> ''Absent'' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+''(F)'')
      when FNAttendanceCode <> ''Absent'' and ANAttendanceCode=''Absent'' then replace(datepart(dd,Date),datepart(dd,Date),cast(datepart(dd,Date) as varchar(50))+''(S)'')
      else ''''
      end
 FROM TA_Tbl_ProcessedData pd
inner join ta_tbl_employee emp on emp.SwipeCardNo=pd.Employee_Code_Id
where emp.Employee_Code_Id = @empId 
and Date between CONVERT(DATETIME, cast(@fromDat as nvarchar(50))   , 102) and CONVERT(DATETIME, cast(@ToDat as nvarchar(50)) , 102)
and (FNAttendanceCode=''Absent'' or ANAttendanceCode=''Absent'')
and emp.Report_Exclude=0
return isnull(@Absent,'''')
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Fun_TA_GetDateFormat]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Fun_TA_GetDateFormat]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
/*
Select [Fun_TA_GetDateFormat] 
*/
-- =============================================
CREATE FUNCTION [dbo].[Fun_TA_GetDateFormat]()
RETURNS Varchar(3)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- Return the result of the function
	RETURN @dateFormat
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsentCount]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsentCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-2007
-- Description:	Absentess reports
-- Modified by :K.Gopinath
-- Modified on : 18-Dec-2013
-- Description : SQL Query Optimization
-- [Proc_Ta_rptAbsentCount] ''04/04/2007'',''05/30/2009'','''',0,'''','''',0,0,''SuperAdmin'',3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_rptAbsentCount]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
	/****** Object:  Index [IDX_Employee_Id] IDX_Employee_Code_Id IDX_SwipeCardNo    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Id] ON [dbo].[ta_tbl_employee] 
(
	[Employee_Id] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[ta_tbl_employee] 
(
	[Employee_Code_Id] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_SwipeCardNo]    Script Date: 12/18/2013  By Gopi ******/
CREATE NONCLUSTERED INDEX [IDX_SwipeCardNo] ON [dbo].[ta_tbl_employee] 
(
	[SwipeCardNo] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
Declare @sqlCommon nvarchar(4000)
set @sqlEmpLevel=
	''insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''''')''
Execute(@sqlEmpLevel)
	--Employee Designation insert in Temporary table
Declare @sqlEmpDesi nvarchar(4000)
set @sqlEmpDesi=
''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''''','''''''')''
Execute(@sqlEmpDesi)
--Employee Type insert in Temporary table
Declare @sqlEmpType nvarchar(4000)
set @sqlEmpType=
''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
Execute(@sqlEmpType)
--Employee Category insert in Temporary table
Declare @sqlEmpCategory nvarchar(4000)
set @sqlEmpCategory=
''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
Execute(@sqlEmpCategory)
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as nvarchar(4000)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT count(*) FROM TA_Tbl_ProcessedData INNER JOIN''
		set @sqlQuery = @sqlQuery + '' TA_Tbl_Employee ON TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
		set @sqlQuery = @sqlQuery + '' TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID  '' 	
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' WHERE (TA_Tbl_ProcessedData.fnAttendanceCode = ''''Absent'''' OR TA_Tbl_ProcessedData.AnAttendanceCode =''''Absent'''' OR TA_Tbl_ProcessedData.fnAttendanceCode = ''''LOP'''' OR TA_Tbl_ProcessedData.AnAttendanceCode =''''LOP'''') AND (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)''		
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
		set @sqlQuery = @sqlQuery + '' AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  '' And  Ta_Tbl_ProcessedData.Shift_Id = '' +  cast(@shift  as nvarchar(20))  
			end
		if not(@EmployeeName='''')
			begin
				set @sqlQuery = @sqlQuery + ''and (TA_Tbl_Employee.Employee_FirstName + '''' '''' +  isnull(TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' +cast(@employeeType as nvarchar(8))
			end		
		if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and (#EmpLevel.LevelId IN ('' + @LevelId + ''))'' 
			end			
		set @sqlQuery = @sqlQuery + '' order by TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date''
		exec(@sqlQuery)
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop index ta_tbl_employee.IDX_Employee_Id
drop index ta_tbl_employee.IDX_Employee_Code_Id 
drop index ta_tbl_employee.IDX_SwipeCardNo 
END
' 
END
GO
/****** Object:  View [dbo].[ta_view]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ta_view]'))
EXEC dbo.sp_executesql @statement = N'create view [dbo].[ta_view] 
 as
 select Shift_ShortName from ta_tbl_shift group by Shift_ShortName
'
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetRemarks]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetRemarks]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GetRemarks]
(
	@EmployeeID varchar(25),
	@StartDate datetime,
	@EndDate datetime,
	@Type varchar(100) -- Absent, Sick, Annual
	--@Day as varchar(3) -- 1.0 - full day , 0.5 - half day
)
RETURNS varchar(8000)
AS
BEGIN
	DECLARE @Remarks VARCHAR(8000)
	DECLARE @Remarks1 VARCHAR(8000)
	if (@Type=''Absent'')
		Begin
			SELECT @Remarks = ISNULL(@Remarks + '', '', '''') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where attendance = @type and employee_code_id= @EmployeeID and totaldays=''1.0''
			and (date >= @StartDate and date <= @EndDate)
			order by date
			SELECT @Remarks1 = ISNULL(@Remarks + '', '', '''') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where attendance = @type and employee_code_id= @EmployeeID and totaldays=''0.5''
			and (date >= @StartDate and date <= @EndDate)
			order by date
		End
	Else
		Begin
			SELECT @Remarks = ISNULL(@Remarks + '', '', '''') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where LeaveCode = @type and employee_code_id= @EmployeeID and totaldays=''1.0''
			and (date >= @StartDate and date <= @EndDate)
			order by date
			SELECT @Remarks1 = ISNULL(@Remarks + '', '', '''') + CONVERT(VARCHAR(11),date,113)
			FROM [dbo].[ta_tbl_processedData]
			where LeaveCode = @type and employee_code_id= @EmployeeID and totaldays=''0.5''
			and (date >= @StartDate and date <= @EndDate)
			order by date
		End
	set @Remarks1 = '' And '' + @Remarks1	+ '' is 0.5 day''
	return @Remarks +  '' '' + isnull(@Remarks1,'''')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_LateIn]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterReason_LateIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 August 2007
-- Description:	Enter Reason for Late entry in Processed data table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EnterReason_LateIn] 
	-- Add the parameters for the stored procedure here
	@Reason NVARCHAR(255),
	@ID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET LateEntryReason=@Reason WHERE Process_Rec_ID=@ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterReason_EarlyOut]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterReason_EarlyOut]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Arun vinoth
-- Create date: 04 August 2007
-- Description:	Enter Reason for Late entry in Processed data table
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EnterReason_EarlyOut] 
	-- Add the parameters for the stored procedure here
	@Reason NVARCHAR(255),
	@ID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	UPDATE TA_Tbl_ProcessedData SET EarlyOutReason=@Reason WHERE Process_Rec_ID=@ID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysTempWeekDay]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysTempWeekDay]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	: Proc_TA_CheckHolidaysTempWeekDay  ''G'',''09/25/2008'',''10/31/2008'',''test''  
Description 	: check weekday count  
Tables Included : TA_Tbl_TempWeekDay  
Created By 	: Prabakaran.P   
Created On 	: 09-Sep-2007  
Modified By	:    
Modified On :
*/  
CREATE    procedure [dbo].[Proc_TA_CheckHolidaysTempWeekDay]
(
	@HolidayFdate nvarchar(20),
	@HolidayTodate nvarchar(20)
)
AS
BEGIN
	SELECT COUNT(*) as TempWeekDayCount FROM TA_Tbl_TemWeekDay 
	where 
	(
		(TempWeekday_FromDate between @HolidayFdate and @HolidayTodate)
		or
		(TempWeekday_ToDate between @HolidayFdate and @HolidayTodate)
		or
		(@HolidayFdate between TempWeekday_FromDate and TempWeekday_ToDate)
		or
		(@HolidayTodate between TempWeekday_FromDate and TempWeekday_ToDate)
	)
	and Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Data is alread Exists or not for processing>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataExistsOrNotUsingPunchType]
	@PunchType char(1),
	@inClk_EmpId varchar(50),
	@inClk_Date varchar(20),
	@inClk_Time varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
    if @PunchType=''I''
    begin 
		select count(*) as RecordCount from  TA_Tbl_ClockDetails 
		where  Clk_EmpId= @inClk_EmpId and Clk_InDate =convert(datetime,@inClk_Date) 
		and Clk_InTime = CONVERT(datetime,@inClk_Time)
	end
	else
	begin
		select count(*) as RecordCount from  TA_Tbl_ClockDetails 
		where  Clk_EmpId= @inClk_EmpId and Clk_OutDate =CONVERT(datetime,@inClk_Date) 
		and Clk_OutTime =CONVERT(datetime,@inClk_Time)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_UpdateLeaveApplicationSanction  
Description : Update Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included : TA_Tbl_LeaveApplication   
Created By : Prabakaran  
Created On : 24-Jul-07  
Modified By		:	A.K.T.MOORTHI
Modified On		:	23-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:	A.K.T.MOORTHI
Modified On		:	30-Sep-2013
Description		:	Commented For Added/Updated Leave Id For Approvel Status. Bze Already We Have Updated Leave Id(Bug No: 0019153)
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
Proc_TA_UpdateLeaveApplicationSanction 71,''Rejected'',''NO'',1
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction]  
  --Proc_TA_UpdateLeaveApplicationSanction  '''','''',''''
@LeaveApplication_Id int,  
@Status nvarchar(250),  
@Remarks nvarchar(250),
@auEmpId int  
as  
BEGIN
	declare @sql nvarchar(4000)
	DECLARE @Type VARCHAR(20)
	declare @EmployeeId INT
	declare @NumberOfDays DECIMAL(18, 1)
set @sql=''''
set @sql = @sql + ''UPDATE TA_TBL_LeaveApplication set Status=N'''''' + @Status + '''''',Remarks= N'''''' + @Remarks + '''''',Emp_Id=''''''+ cast(@auEmpId as nvarchar(20))+'''''' Where LeaveApplication_Id= '' + cast (@LeaveApplication_Id  as nvarchar(10))
UPDATE TA_Tbl_LeaveApplicationExists SET status=@Status WHERE LeaveApplicationId = @LeaveApplication_Id
  exec (@sql)
	SELECT 
		@Type = [Type],
		@EmployeeId = Employee_Id,
		@NumberOfDays = NumberOfDays
	FROM TA_Tbl_LeaveApplication WHERE LeaveApplication_Id = @LeaveApplication_Id
	DECLARE @CompOffId BIGINT 
	set @CompOffId=0
	DECLARE  @RemainingDays NUMERIC(18,1)
	set @RemainingDays =0.0
	DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
	IF(@Type= ''Comp Off'' AND @Status = ''Rejected'')
	BEGIN
		INSERT INTO @TblRecord
		SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE ''%:'' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + ''%''
		ORDER BY [Date]
		declare @ValCount as int
		SELECT @ValCount=COUNT(*) FROM TA_Tbl_OverTimeStatus
			WHERE LeaveApplicationId LIKE ''%:'' + CAST(@LeaveApplication_Id AS VARCHAR(20)) + ''%''
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@ValCount=2) THEN @RemainingDays + 0.5 else case when (@ValCount>2) THEN CASE 
				WHEN (@NumberOfDays > NoOfDays) THEN NoOfDays
				ELSE (@RemainingDays + @NumberOfDays) end else NoOfDays end END),
				CompOffSatus = (CASE
					WHEN DateToExpired < GETDATE() THEN ''Expired''
					WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN ''Not Taken'' END),
				LeaveApplicationId = case	when @NumberOfDays>0.5 then REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''') 
								else	case	when (select COUNT(Value) from dbo.Split(LeaveApplicationId,'':'') where Value=@LeaveApplication_Id)=2 
								then '':''+CAST(@LeaveApplication_Id AS VARCHAR(20))
												else REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''') 
										end
					end
			WHERE ExtraTime_Id = @CompOffId
			SELECT @NumberOfDays = case when (@ValCount=2) then (@NumberOfDays - 0.5) else (@NumberOfDays - RemainingDays) end FROM TA_Tbl_OverTimeStatus
				WHERE ExtraTime_Id = @CompOffId
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
		--WHILE ((EXISTS(SELECT Process FROM @TblDRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		--BEGIN
		--	SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblDRecord WHERE Process = 0 ORDER BY Id)
		--	UPDATE TA_Tbl_OverTimeStatus SET
		--		@RemainingDays = RemainingDays,
		--		RemainingDays = (CASE 
		--			WHEN (@NumberOfDays > NoOfDays) THEN (@RemainingDays + @NumberOfDays) - NoOfDays
		--			ELSE (@RemainingDays + @NumberOfDays) END),
		--		CompOffSatus = (CASE
		--			WHEN DateToExpired < GETDATE() THEN ''Expired''
		--			WHEN (@RemainingDays <= @NumberOfDays) OR (@RemainingDays > @NumberOfDays) THEN ''Not Taken'' END),
		--		LeaveApplicationId = REPLACE(LeaveApplicationId, '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20)), '''')
		--	WHERE ExtraTime_Id = @CompOffId
		--	SELECT @NumberOfDays = (@NumberOfDays - RemainingDays) FROM TA_Tbl_OverTimeStatus
		--		WHERE ExtraTime_Id = @CompOffId
		--	UPDATE @TblDRecord SET Process = 1 WHERE CompOffId = @CompOffId
		--END
	END
	ELSE IF(@Type= ''Comp Off'' AND @Status = ''Approved'')
	BEGIN		
		UPDATE TA_Tbl_OverTimeStatus SET CompOffSatus = ''Expired''
		WHERE DateToExpired < GETDATE() AND
			ISNULL(CompOffSatus, ''Not Taken'') = ''Not Taken'' AND
			OverTimeStatus = ''Approved'' AND
			CompOffEligible = 1 AND
			Employee_Id = @EmployeeId 
		INSERT INTO @TblRecord
			SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE DateToExpired >= GETDATE() AND
				ISNULL(CompOffSatus, ''Not Taken'') = ''Not Taken'' AND
				OverTimeStatus = ''Approved'' AND
				CompOffEligible = 1 AND
				Employee_Id = @EmployeeId
			ORDER BY [Date]
		/*WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN 0.0 END),
				CompOffSatus = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN ''Not Taken''
					WHEN (@RemainingDays <= @NumberOfDays) THEN ''Taken'' END),
				LeaveApplicationId = ISNULL(LeaveApplicationId, '''') + '':'' + CAST(@LeaveApplication_Id AS VARCHAR(20))
			WHERE ExtraTime_Id = @CompOffId
			SET @NumberOfDays = (@NumberOfDays - @RemainingDays) (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN (@NumberOfDays - @RemainingDays) END)
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
		*/
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-11-2016 13:17>
-- Description:	Check in the TimeCheck Processed Data whether there are records for appropriate EmployeeId and Date
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataAlreadyExistsInProcessedData]
	@Clk_EmpId varchar(50),
	@ClockDate varchar(20),
	@Datafrom char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Datafrom=''I'')
	begin	
		Select Employee_Code_Id,CONVERT(varchar(25), Date,120) as Date,InTime,LateIn,InNotation 
		from TA_Tbl_ProcessedData where Employee_Code_Id = @Clk_EmpId and Date = CONVERT(datetime,@ClockDate)
	end
	else
	begin
		Select Employee_Code_Id,convert(varchar(25),Date,120) as Date,OutTime,OutNotation 
		from TA_Tbl_ProcessedData where Employee_Code_Id = @Clk_EmpId and Date = CONVERT(datetime,@ClockDate)
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Any non mapped in data is exists or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingAnyNonMappedInDataExists]
	@strInDateTime varchar(20),
	@strOutDateTime varchar(20),
	@inClk_EmpId varchar(50),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''I'')
	begin
		select count(*) as RecordCount from ta_tbl_clockdetails 
		where ((((Clk_InDate+Clk_InTime) > CONVERT(datetime,@strInDateTime) and ((Clk_InDate+Clk_InTime) < CONVERT(datetime,@strOutDateTime))) 
		or (((Clk_OutDate+Clk_OutTime) > CONVERT(datetime,@strInDateTime)) and ((Clk_OutDate+Clk_OutTime) < CONVERT(datetime,@strOutDateTime))))) 
		and Clk_EmpId = @inClk_EmpId AND IsVoid=0
	end
	else
	begin
		select count(*) as RecordCount from ta_tbl_clockdetails 
		where ((((Clk_InDate+Clk_InTime) > CONVERT(datetime,@strInDateTime) and ((Clk_InDate+Clk_InTime) < CONVERT(datetime,@strOutDateTime))) 
		or (((Clk_OutDate+Clk_OutTime) > CONVERT(datetime,@strInDateTime)) and ((Clk_OutDate+Clk_OutTime) < CONVERT(datetime,@strOutDateTime)))))
		and Clk_EmpId = @inClk_EmpId AND IsVoid=0
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingAllreadyExistsForservice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingAllreadyExistsForservice]
	-- Add the parameters for the stored procedure here
	@inClk_EmpId varchar(30),
	@inClk_Date  varchar(20),
	@inClk_Time  varchar(20),
	@strINorOUTEntry char(1)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @count int
    -- Insert statements for procedure here
    if (@strINorOUTEntry=''I'')
		begin
			select @count=count(*) from  TA_Tbl_ClockDetails where  Clk_EmpId= @inClk_EmpId and Clk_InDate = @inClk_Date
			and Clk_InTime = @inClk_Time
		end
	if (@strINorOUTEntry=''O'')
		begin
			select @count=count(*) from  TA_Tbl_ClockDetails where  Clk_EmpId= @inClk_EmpId and Clk_OutDate = @inClk_Date
			and Clk_OutTime = @inClk_Time
		end
	select @count  as RecordCount 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIndividualUser]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckIndividualUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: Proc_TA_CheckIndividualUser  
Description 	: Checking whether the user is individual user or not
Tables Included : ta_tbl_userRights  
Created By 	: Prabakaran.P  
Created On 	: 08-July-2008
Modified By 	:  
Modified On 	:  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckIndividualUser]
(
	@UserGroupName varchar(250)
)
AS
BEGIN
	select count(*) as IndUserCount from TA_Tbl_Usergroup where (groupName=@UserGroupName and IndividualUsers=1 and Isdeleted=0) 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckIgnoreDuplicatePunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 10.49 am>
-- Description:	<Checking ignore Duplicate punches point>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckIgnoreDuplicatePunches]
	-- Add the parameters for the stored procedure here
	@inShiftType bit, 
	@inClk_CardId varchar(50), 
	@inClk_Date varchar(50), 
	@inClk_Time varchar(50), 
	@strClockDate varchar(50), 
	@inClk_Type varchar(50),
	@gstrPunchInterval varchar(10)
AS
BEGIN
	SET NOCOUNT ON;
	if (@inShiftType=1) 	--Free Scan
    begin
        --Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for both IN & OUT Punches
		SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
        AND Clk_InDate=@inClk_Date
        AND ((@inClk_Time BETWEEN Clk_InTime AND Clk_InTime + @gstrPunchInterval)
        OR (@inClk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @gstrPunchInterval))
        AND Clk_Date=@strClockDate
	end
	else --Function Key
	begin
		if (@inClk_Type =''I'')
		begin
			--Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for IN Punches
			SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
			AND Clk_InDate=@inClk_Date
			AND (@inClk_Time BETWEEN Clk_InTime AND Clk_InTime + @gstrPunchInterval)
			AND Clk_Date=@strClockDate
		end
		else
		begin
			--Check whether the incoming punch lies between any [existing punch] and [existing punch + PunchInterval] for OUT Punches
			SELECT COUNT(*) AS DuplicateCount FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_CardId
			AND Clk_InDate=@inClk_Date
			AND (@inClk_Time BETWEEN Clk_OutTime AND Clk_OutTime + @gstrPunchInterval)
			AND Clk_Date=@strClockDate
		end
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBulkConfiguration]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeBulkConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- 
/*
Proc_TA_EmployeeBulkConfiguration
''<Dst_bulkimport>
  <EmployeeBulkImport>
    <Employee_Id>758</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress />
    <PermanentAddress />
    <PhoneNumber />
    <MobileNumber />
    <ReportingTo />
    <ApprovalAuthority />
    <InActive />
    <BasicSalary>5000</BasicSalary>
  </EmployeeBulkImport>
</Dst_bulkimport>'',17,1


Proc_TA_EmployeeBulkConfiguration 
''<Dst_bulkimport>
  <EmployeeBulkImport>
    <Employee_Id>787</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>1</ContactAddress>
    <PermanentAddress>100</PermanentAddress>
    <PhoneNumber>04222676867</PhoneNumber>
    <MobileNumber>9894159117</MobileNumber>
    <ReportingTo>758</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>788</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>2</ContactAddress>
    <PermanentAddress>101</PermanentAddress>
    <PhoneNumber>04222676868</PhoneNumber>
    <MobileNumber>9894159118</MobileNumber>
    <ReportingTo>758</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>789</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>3</ContactAddress>
    <PermanentAddress>102</PermanentAddress>
    <PhoneNumber>04222676869</PhoneNumber>
    <MobileNumber>9894159119</MobileNumber>
    <ReportingTo>789</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>790</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>4</ContactAddress>
    <PermanentAddress>103</PermanentAddress>
    <PhoneNumber>04222676870</PhoneNumber>
    <MobileNumber>9894159120</MobileNumber>
    <ReportingTo>788</ReportingTo>
    <ApprovalAuthority>758</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>791</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>5</ContactAddress>
    <PermanentAddress>104</PermanentAddress>
    <PhoneNumber>04222676871</PhoneNumber>
    <MobileNumber>9894159121</MobileNumber>
    <ReportingTo>790</ReportingTo>
    <ApprovalAuthority>788</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>792</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>6</ContactAddress>
    <PermanentAddress>105</PermanentAddress>
    <PhoneNumber>04222676872</PhoneNumber>
    <MobileNumber>9894159122</MobileNumber>
    <ReportingTo>788</ReportingTo>
    <ApprovalAuthority>4</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>793</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>7</ContactAddress>
    <PermanentAddress>106</PermanentAddress>
    <PhoneNumber>04222676873</PhoneNumber>
    <MobileNumber>9894159123</MobileNumber>
    <ReportingTo>787</ReportingTo>
    <ApprovalAuthority>4</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>794</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>8</ContactAddress>
    <PermanentAddress>107</PermanentAddress>
    <PhoneNumber>04222676874</PhoneNumber>
    <MobileNumber>9894159124</MobileNumber>
    <ReportingTo>4</ReportingTo>
    <ApprovalAuthority>2</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>795</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>9</ContactAddress>
    <PermanentAddress>108</PermanentAddress>
    <PhoneNumber>04222676875</PhoneNumber>
    <MobileNumber>9894159125</MobileNumber>
    <ReportingTo>1</ReportingTo>
    <ApprovalAuthority>1</ApprovalAuthority>
  </EmployeeBulkImport>
  <EmployeeBulkImport>
    <Employee_Id>796</Employee_Id>
    <UserGroup />
    <EmailID />
    <PersonalEmailID />
    <ContactAddress>10</ContactAddress>
    <PermanentAddress>109</PermanentAddress>
    <PhoneNumber>04222676876</PhoneNumber>
    <MobileNumber>9894159126</MobileNumber>
    <ReportingTo>795</ReportingTo>
    <ApprovalAuthority>1</ApprovalAuthority>
  </EmployeeBulkImport>
</Dst_bulkimport>'',14,0
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeBulkConfiguration]
	-- Add the parameters for the stored procedure here
	@Data XML=NULL, @Eligible int, @FromYesToNo int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @XMLParams INT	
	DECLARE @ErrMsg VARCHAR(MAX)
	Declare @ErrIds VARCHAR(MAX)
	Declare @SQLQuery varchar(max)
	Declare @SQLQuery1 varchar(max)
	BEGIN TRY
		BEGIN TRAN
			--Create table #TempEmployee(Employee_Code_Id varchar(50))			
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @Data
			--insert into #TempEmployee
			--select E.Employee_Code_Id 
			--FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
			--		(Employee_Code_Id VARCHAR(50)) Tbl
			--		inner JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			--		AND E.IsDeleted = 0 AND E.Employee_Status = 1			
			if(@Eligible=1)
				begin
					update TA_Tbl_Employee set OT_Eligible=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=2)
				begin
					update TA_Tbl_Employee set CompOff_Eligible=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=3)
				begin
					update TA_Tbl_Employee set CompOff_Eligible=case when @FromYesToNo=1 then 1 else 0 end,OT_Eligible=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
			else if(@Eligible=4)
				begin				
					update TA_Tbl_Employee set Report_Exclude=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end				
			else if(@Eligible=6)
				begin				
					update TA_Tbl_Employee set Hostel=case when @FromYesToNo=1 then 1 else 0 end
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=7)
				begin					
					update TA_Tbl_Employee set UserGroup_Id=ug.groupId
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'',2) WITH 
					(Employee_Id VARCHAR(50),UserGroup varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					inner join TA_Tbl_Usergroup ug on ug.groupName=Tbl.UserGroup
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end		
			else if(@Eligible=8)
				begin				
					update TA_Tbl_Employee set EmailId=Tbl.EmailID
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),EmailID varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end				 
			else if(@Eligible=9)
				begin				
					update TA_Tbl_Employee set Personal_mailid=Tbl.PersonalEmailID
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),PersonalEmailID varchar(250)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=10)
				begin				
					update TA_Tbl_Employee set Contact_Address=Tbl.ContactAddress
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),ContactAddress varchar(500)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=11)
				begin				
					update TA_Tbl_Employee set Permanent_Address=Tbl.PermanentAddress
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),PermanentAddress varchar(500)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=12)
				begin				
					update TA_Tbl_Employee set Phone_Number=Tbl.PhoneNumber
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),PhoneNumber varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=13)
				begin				
					update TA_Tbl_Employee set Mobile_Number=Tbl.MobileNumber
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),MobileNumber varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=14)
				begin				
					update TA_Tbl_Employee set Reporting_To=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=Tbl.ReportingTo)
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
						(Employee_Id VARCHAR(50),ReportingTo varchar(50)) Tbl
						LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
						AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=15)
				begin				
					update TA_Tbl_Employee set Leave_Sanc_Authority=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=Tbl.ApprovalAuthority)
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50),ApprovalAuthority varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			else if(@Eligible=16)
				begin				
					update TA_Tbl_Employee set	InActive_Status=case when @FromYesToNo=1 then 1 else 0 end,
												InActiveDate=case when @FromYesToNo=1 then tbl.InActive end,
												Employee_Status=case when @FromYesToNo=1 then 0 else 1 end
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50), InActive varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end
			   else if(@Eligible=17)
				begin				
					update E set	E.Basic_Salary=tbl.BasicSalary
					--select Tbl.*
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50), BasicSalary varchar(15)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
				--Code for vaigai--
				else if(@Eligible=18)
				begin
					update TA_Tbl_Employee set MobileClockInOUt=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end	
				
				else if(@Eligible=19)
				begin
					update TA_Tbl_Employee set SMSEnabled=case when @FromYesToNo=1 then 1 else 0 end 					
					FROM OPENXML (@XMLParams, ''/Dst_bulkimport/EmployeeBulkImport'', 2) WITH 
					(Employee_Id VARCHAR(50)) Tbl
					LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Id
					AND E.IsDeleted = 0 AND E.Employee_Status = 1
				end			
			   --Code for vaigai--

			EXEC SP_XML_RemoveDocument @XMLParams			
		COMMIT TRAN
	END TRY		
	BEGIN CATCH
		--SET @ErrMsg = ERROR_MESSAGE()
		--SET @ErrIds = @@ERROR
		ROLLBACK TRAN
		--RAISERROR(@ErrMsg, 16,@ErrIds, ''Error'')
	END CATCH	
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[SplitUpEmployeeName]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitUpEmployeeName]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'create function [dbo].[SplitUpEmployeeName]
(
	@String nvarchar (max),
	@Delimiter nvarchar (10)
 )
returns @ValueTable table (Id int identity, [Value] nvarchar(4000))
begin
	--To remove Duplicate Values if occured
	declare @S varchar(max)
	declare @T varchar(max)
	declare @W varchar(max)
	set @S = @String
	set @T = '',''
	while len(@S) > 0
		begin
			set @W = left(@S, charindex('','', @S+'','')-1)+'',''
			if charindex('',''+@W, @T) = 0
				set @T = @T + @W
				set @S = stuff(@S, 1, charindex('','', @S+'',''), '''')
		end
	set @String = substring(@T, 2, len(@T)-2)
	----
	declare @NextString nvarchar(4000)
	declare @Pos int
	declare @NextPos int
	declare @CommaCheck nvarchar(1)
	--Initialize
	set @NextString = ''''
	set @CommaCheck = right(@String,1)
	--Check for trailing Comma, if not exists, INSERT
	--if (@CommaCheck <> @Delimiter )
	set @String = @String + @Delimiter
	--Get position of first Comma
	set @Pos = charindex(@Delimiter,@String)
	set @NextPos = 1
	--Loop while there is still a comma in the String of levels
	while (@pos <>  0)  
		begin
			set @NextString = substring(@String,1,@Pos - 1)			
			insert into @ValueTable ( [Value]) 
			select Employee_Code_Id from ta_tbl_employee where employee_FirstName+'' ''+ Employee_LastName=@NextString
			and isdeleted=0
			set @String = substring(@String,@pos +1,len(@String))
			set @NextPos = @Pos
			set @pos  = charindex(@Delimiter,@String)
		end
	return
end' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[SplitupEmployeeCode]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitupEmployeeCode]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan.
-- Create date: 08-09-2014
-- Description:	To split up the comma separated values
-- select * from SplitupEmployeeCode(''787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,787,'')
-- =============================================
create FUNCTION [dbo].[SplitupEmployeeCode]
(	
	-- Add the parameters for the function here
	@EmployeeCodeID as varchar(max)
)
RETURNS @EmployeeID table (EmployeeID varchar(150))
AS
begin
	--To remove Duplicate Values if occured
	declare @S varchar(max)
	declare @T varchar(max)
	declare @W varchar(max)
	set @S = @EmployeeCodeID
	set @T = '',''
	while len(@S) > 0
		begin
			set @W = left(@S, charindex('','', @S+'','')-1)+'',''
			if charindex('',''+@W, @T) = 0
				set @T = @T + @W
				set @S = stuff(@S, 1, charindex('','', @S+'',''), '''')
		end
	set @EmployeeCodeID = substring(@T, 2, len(@T)-2)
	----
	Declare @RowCountEmployeeID int
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '''')
	begin
		if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = '','')
		begin
			set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
		end
			insert into @EmployeeID
			select value from dbo.split(@EmployeeCodeID,'','')
			select @RowCountEmployeeID=COUNT(EmployeeID) from @EmployeeID
	end
RETURN 
end
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_SancAuthority]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetMappedEmployees_SancAuthority]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
--select * from fn_TA_GetMappedEmployees (27)
CREATE FUNCTION [dbo].[fn_TA_GetMappedEmployees_SancAuthority] 
(
	@Employee_Id int
)
RETURNS 
@TA_Tbl_ReturnParentChild TABLE 
(
-- Add the column definitions for the TABLE variable here
ParentChildId int null
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
			declare @TA_Tbl_ParentChild TABLE 
			(
				-- Add the column definitions for the TABLE variable here
			ID int identity(1,1) NOT NULL,
			ParentChildId int null,
			tier_cnt int NULL,
			lineage_id varchar(50)
			)
			--declare @TA_Tbl_ParentChildTemp TABLE 
			--(
			--	-- Add the column definitions for the TABLE variable here
			--ParentChildId int null
			--)
			--set @parent_id=1
			/* declare our tier cnt integer, and set it to two (for the number of tiers existing in the temp tabel for for our Nth level loop */
			Declare @tier as int
			SET @tier = 2
			/* Let''s build the root level This inserts the root level into the temp table */
			INSERT INTO @TA_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)
			VALUES(@Employee_Id,1,''1'')
			/*
			Now we must go get for first batch of children (if there are any)
			*/
			--INSERT INTO @TA_Tbl_ParentChild
			--Select child_id,2,''1'' from tb_tree where parent_id = @parent_id
			INSERT INTO @TA_Tbl_ParentChild
			Select Employee_ID,2,''1'' from TA_Tbl_Employee where Leave_Sanc_Authority = @Employee_Id
			/*
			Now comes the magic- believe it or not. We need to stamp our newly added children with their genetic code, so to speak. Each line item is given a map back to its the top level parent via the lineage_id
			*/
			UPDATE @TA_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt
			/*Now the table is initalized and ready for the Nth level iterations. So we start a while loop using the SQL Server''s @@rowcount (i''m not sure what this variable is called in other platforms but I''m sure a rows affected variable should be available) . We also have our @tier int set to 2 (we''ve added two other tiers already, so that''s the current tier).*/
			--While Enable the below point are implement the Angler
			--WHILE @@rowcount > 0
			--BEGIN
			--	SET @tier = @tier+1
			--	/*Go get children nodes for the next tier that are not already accounted for */
			--	--INSERT INTO @TA_Tbl_ParentChildTemp (ParentChildId)
			--	--select ParentChildId from @TA_Tbl_ParentChild
			--	INSERT INTO @TA_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)
			--	SELECT Employee_Id, @tier,(select lineage_id from @TA_Tbl_ParentChild where ParentChildId = Leave_Sanc_Authority)
			--	FROM TA_Tbl_Employee
			--	--inner join @TA_Tbl_ParentChildTemp PC on PC.ParentChildId in (ta_tbl_leveldetails.parentid)
			--	--and PC.ParentChildId NOT in (ta_tbl_leveldetails.id)
			--	WHERE Leave_Sanc_Authority IN (select ParentChildId from @TA_Tbl_ParentChild)
			--	AND Employee_Id NOT in (select ParentChildId from @TA_Tbl_ParentChild)
			--	--delete from @TA_Tbl_ParentChildTemp
			--	/* Now stamp the lineage ID with last numeral, the ID field asigned to the new nodes */
			--	UPDATE @TA_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt
			--END
			insert into @TA_Tbl_ReturnParentChild
			select ParentChildId from @TA_Tbl_ParentChild
			--select * from @TA_Tbl_ReturnParentChild
			/* The loop end once no more related children can be found. So, with all the children added we need only select the temp table ordered by the lineage_id for teh SP''s result*/
			--select ParentChildId from @TA_Tbl_ParentChild 
			--order by ParentChildId
	RETURN 
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetDateTimeFormat]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetDateTimeFormat]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 21-11-2016
-- Description:	GetDate And Time Format
-- Select * from [Func_TA_GetDateTimeFormat]()
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_GetDateTimeFormat]()
RETURNS 
@DatetimeFormat TABLE 
(
	DateFormat int,
	TimeFormat nvarchar(50)
)
AS
BEGIN
	DECLARE @dateFormat as INT
	DECLARE @date as nVARCHAR(25)			
	DECLARE @TimeFormat as nvarchar(25)
	SELECT @TimeFormat=TimeFormat,@date = DateFormat FROM TA_Tbl_DateandTimeFormat
	IF(@date=''dd/MM/yyyy'')
	BEGIN
		SET @dateFormat = 103
	END
	ELSE IF(@date=''MM/dd/yyyy'')
	BEGIN
		SET @dateFormat = 101
	END
	ELSE
	BEGIN
		SET @dateFormat = 106
	END	
	insert into @DatetimeFormat values (@dateFormat,@TimeFormat)
	RETURN
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetMappedEmployees_ReportingTo]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetMappedEmployees_ReportingTo]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'--select * from fn_TA_GetMappedEmployees_ReportingTo (2)
CREATE FUNCTION [dbo].[fn_TA_GetMappedEmployees_ReportingTo] 
(
	@Employee_Id int
)
RETURNS @TA_Tbl_ReturnParentChild TABLE 
(
	ParentChildId int null
)
AS
BEGIN
	declare @TA_Tbl_ParentChild TABLE 
	(
		ID int identity(1,1) NOT NULL,
		ParentChildId int null,
		tier_cnt int NULL,
		lineage_id varchar(50)
	)
	Declare @tier as int
	SET @tier = 2
	INSERT INTO @TA_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)
	VALUES(@Employee_Id,1,''1'')
	INSERT INTO @TA_Tbl_ParentChild
	Select Employee_ID,2,''1'' from TA_Tbl_Employee where Reporting_To = @Employee_Id
	UPDATE @TA_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt
	insert into @TA_Tbl_ReturnParentChild
	select ParentChildId from @TA_Tbl_ParentChild
	RETURN 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicy]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[Proc_TA_EmpLeavePolicy] 
(
	@PolicyID INT
)
as
Begin
	SET NOCOUNT ON;
	select LP.Policy_Id,PolicyName,LT.LeaveType_Id,LeaveType,MaxDays_applicable,MaxDays_Month,LeaveDescription=LeaveDescription + '' (''+LeaveType+'')'' from TA_Tbl_LeavePolicyDetails LP 
	INNER JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id=LP.LeaveType_Id 
	INNER JOIN TA_Tbl_LeavePolicy L ON L.Policy_Id=LP.Policy_Id 
	where LP.policy_id=@PolicyID
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaysUpdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaysUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckHolidaysUpdate  
Description : check holidays updation
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
Proc_TA_CheckHolidaysUpdate  26,''Y'',''2013/12/06'',''2013/12/06'',''Dec 06'',0
*/  
CREATE   procedure [dbo].[Proc_TA_CheckHolidaysUpdate]      
(    
	@HolidayId int,    
	@HolidayType nvarchar(2),    
	@HolidayFdate nvarchar(20),  
	@HolidayTodate nvarchar(20),   
	@HolidayDescription nvarchar(50),
	@LevelId int
)      
AS      
BEGIN 
	DECLARE @yearSetingId int      
	SET @yearSetingId = 0
	DECLARE @count1 int
	DECLARE @count2 int 
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	IF(@LevelId = 0)
		BEGIN
			SELECT @count1=COUNT(Holiday_Id) FROM TA_Tbl_Holiday 
			INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
			where     
			(((Holiday_FromDate between @HolidayFdate and @HolidayTodate) or (Holiday_ToDate between @HolidayFdate and @HolidayTodate) ) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId)  
			  or 
			  (Holiday_Description= @HolidayDescription and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
			or 
			(((@HolidayFdate between Holiday_FromDate and Holiday_ToDate) or (@HolidayTodate between Holiday_FromDate and Holiday_ToDate)) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
			SELECT @count2=COUNT(LeaveApplication_Id) FROM TA_Tbl_LeaveApplication where LeaveType_Id=@HolidayId and Type=''Restricted Holiday'' and Isdeleted=0 and Status <> ''Rejected''
			select @count1+@count2 as HCount 
		END
	ELSE
		BEGIN
			SELECT @count1=COUNT(Holiday_Id) FROM TA_Tbl_Holiday 
			INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
			where     
			(((Holiday_FromDate between @HolidayFdate and @HolidayTodate) or (Holiday_ToDate between @HolidayFdate and @HolidayTodate) ) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0))  
			  or 
			  (Holiday_Description= @HolidayDescription and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0)) 
			or 
			(((@HolidayFdate between Holiday_FromDate and Holiday_ToDate) or (@HolidayTodate between Holiday_FromDate and Holiday_ToDate)) and Isdeleted=0 and Holiday_Id<>@HolidayId and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (LevelId = @LevelId or LevelId = 0)) 
			SELECT @count2=COUNT(LeaveApplication_Id) FROM TA_Tbl_LeaveApplication where LeaveType_Id=@HolidayId and Type=''Restricted Holiday'' and Isdeleted=0 and Status <> ''Rejected''
			select @count1+@count2 as HCount 
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationPrivateNotes] 
	-- Add the parameters for the stored procedure here
	@leaveApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int,
	@ToMailIds nvarchar(4000),
	@CcMailIds nvarchar(4000)
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	-- inert intto TA_Tbl_LeaveConversation
	SET @leaveConversationCount = (SELECT COUNT(*) FROM TA_Tbl_LeavePrivateNotes WHERE LeaveApplicationId = @leaveApplicationId)
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_LeavePrivateNotes(LeaveApplicationId,NotesBy,Notes,OrderBy,Emp_Id,ToMailIds,CcMailIds) 
	VALUES(@leaveApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId,@ToMailIds,@CcMailIds)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays_GlobalDate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidays_GlobalDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--sp_helptext N''Proc_TA_CheckHolidays_GlobalDate''
/*  
Created By  : Manjula.P  
Created Date : 11-Jun-2013  
Descriptions : For checking global holiday with global holiday date   
Proc_TA_CheckHolidays_GlobalDate ''06/26/2013'',''06/26/2013'',''S''  
*/    
CREATE procedure [dbo].[Proc_TA_CheckHolidays_GlobalDate]  
(  
	@HolidayFdate nvarchar(20),  
	@HolidayTodate nvarchar(20),  
	@Mode varchar(10),  
	@HolidayId int  
)  
AS 
Begin
	DECLARE @yearSetingId int  
	SET @yearSetingId = 0  	
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	if(@Mode=''S'')  
	BEGIN  
		SELECT *  FROM TA_Tbl_Holiday   
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id  
		where Holiday_Type=''G''  
		and Holiday_FromDate = @HolidayFdate and  Holiday_ToDate=@HolidayTodate    
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and Isdeleted=0  
		and Holiday_Id<>@HolidayId  
	END  
	else if(@Mode=''M'')  
	BEGIN  
		SELECT *  FROM TA_Tbl_Holiday   
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id  
		where Holiday_Type=''G''  
		and  Holiday_FromDate between @HolidayFdate and  @HolidayTodate  
		and  Holiday_ToDate between @HolidayFdate and  @HolidayTodate  
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and Isdeleted=0  
		and Holiday_Id<>@HolidayId  
	END  	
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDataExistsAlready]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDataExistsAlready]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Data is already available in clockdetails or not>
-- Proc_TA_CheckingDataExistsAlready 1053,''54391,57794,57679,57789,787'',''11/03/2016 04:35 PM'',''11/03/2016'',''o''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDataExistsAlready]
	@inClk_EmpId varchar(50),
	@strOutDeviceId varchar(max),
	@strInDateTime varchar(20),
	@gstrClockDate varchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
    if @Type=''I''
    begin
		SELECT Top 1 Clk_Id,Clk_EmpId,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
		AND (Clk_InTime = '''' OR Clk_InTime IS NULL) AND Clk_OutDate <> '''' AND Clk_OutDate IS NOT NULL AND Clk_OutDeviceId IN (select * from SplitupEmployeeCode(@strOutDeviceId)) 
		AND (Clk_OutDate+Clk_OutTime) >= Cast(@strInDateTime as DateTime) AND Clk_Date= CONVERT(datetime,@gstrClockDate) AND IsVoid=0 
		ORDER BY (Clk_OutDate+Clk_OutTime) ASC
	end
	else if @Type=''O''
	begin
		SELECT Top 1 Clk_Id,Clk_Date,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId = @inClk_EmpId
		AND (Clk_OutTime = '''' OR Clk_OutTime IS NULL) AND Clk_InDate <> '''' AND Clk_InDate IS NOT NULL AND Clk_InDeviceId IN (select * from SplitupEmployeeCode(@strOutDeviceId))
		AND (Clk_InDate+Clk_InTime) <= Cast(@strInDateTime as DateTime) and Clk_Date=CONVERT(datetime,@gstrClockDate) AND IsVoid=0
		ORDER BY (Clk_InDate+Clk_InTime) DESC
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateTrigger]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CreateTrigger]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Senthil Kumar NP
-- Create date: 04.Jan.08
-- Description:	creating trigger dynamically for specified tables and fields
--<Description,,> Proc_TA_CreateTrigger ''TA_Tbl_Entrance'',''Entrance_Name,Entrance_Description'',''Entrance_Description'',''Entrance_Description''
--Proc_TA_CreateTrigger ''TA_Tbl_NewsEvents'',''NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id'',''LeftNewsEvent,RightNewsEvent'',''NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent''
--Proc_TA_CreateTrigger ''TA_Tbl_NewsEvents'',''NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id'',''NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id'',''NewsEvent_Id,NewsEventFromDate,NewsEventToDate,NewsEventTitle,NewsEventDescription,NewsEventActive,NewsEventImage,LeftNewsEvent,RightNewsEvent,LeftBanner,RightBanner,IsDeleted,TimeStamp,Employee_Id''
--	Modified By		:	Manjula.P
--	Modified On		:	05-Sep-2013
--	Descriptions	:	Adding if(@NewId is not null and @NewId<>'''''''') Condition in dynamiz query for checking whether the Identity value is null or not :
--					:	To avoid insert statement fails error while importing a file when checking audit trail 
--					:	2.to avoiding the subquery returns more than one value error when enabling audit trail Changing in Dynamic query
--					:	  For Inser Trigger
--					:	Proc_TA_CreateTrigger ''TA_Tbl_Terminal'', ''Terminal_ReaderID,Terminal_Name'', ''Terminal_ReaderID,Terminal_Name'', ''Terminal_ReaderID,Terminal_Name''
--	Modified By		:	K.Gopinath
--	Modified On		:	03-Jan-2014 & 10-Jan-2014
--	Descriptions	:	To avoid redudant data while inserting operation in Audit Trial and Fieldsizes of inserting data and added query for check employeeID
--	Proc_TA_CreateTrigger ''TA_Tbl_EmployeeShiftId_ForShiftReAllocation'',''EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift'',''EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift'',''EmployeeAutoId,Date,CurrentShiftId,PreviousDayShift,NextDayShift''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CreateTrigger]
	@tableName as nvarchar(100),
	--@fieldName as nvarchar(3000),	
	@InsertFields as nvarchar(3000)=null,
	@UpdateFields as nvarchar(3000)=null,
	@DeleteFields as nvarchar(3000)=null
AS
BEGIN
	declare @sql as varchar(8000)
	declare @sql1 as varchar(8000)
	declare @triggerName as nvarchar(100)
	declare @idColumn as nvarchar(50)
	declare @concat as nvarchar(100)
	declare @pos as int
	declare @flag as int
	declare @tableId as int
	declare @fieldId as int
	set @idColumn = ''''
	set @idColumn = (select name from syscolumns where colstat=1 and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
	set @sql1=''''
	set @sql =''''
--Delete Insert Trigger
	set @triggerName = ''InsertTrig'' + @tableName  
	set @sql = ''if exists (select * from dbo.sysobjects where id = object_id(N''''[dbo].['' + @triggerName + '' ]'''') and OBJECTPROPERTY(id, N''''IsTrigger'''') = 1)''
	set @sql = @sql + '' drop trigger [dbo].['' + @triggerName + '']''
	exec(@sql)
--Delete Update Trigger
	set @triggerName = ''UpdateTrig'' + @tableName  
	set @sql = ''if exists (select * from dbo.sysobjects where id = object_id(N''''[dbo].['' + @triggerName + '' ]'''') and OBJECTPROPERTY(id, N''''IsTrigger'''') = 1)''
	set @sql = @sql + '' drop trigger [dbo].['' + @triggerName + '']''
	exec(@sql)
--Delete Delete Trigger
	set @triggerName = ''DeleteTrig'' + @tableName  
	set @sql = ''if exists (select * from dbo.sysobjects where id = object_id(N''''[dbo].['' + @triggerName + '' ]'''') and OBJECTPROPERTY(id, N''''IsTrigger'''') = 1)''
	set @sql = @sql + '' drop trigger [dbo].['' + @triggerName + '']''
	exec(@sql)
	set @tableId = (select TableID from ta_tbl_AuditTable where TableName=@tableName)	
--set Employee Id
declare @empCount as int
declare @empField as nvarchar(25)
set @empField = ''''
set @empCount =0
set @empCount = (select count(*) as tot from syscolumns where name=''emp_id'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
if (@empCount>0)
	Begin
		set @empField = ''emp_id''
	End
Else
	Begin
		set @empCount = (select count(*) as tot from syscolumns where name=''empid'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
		if (@empCount>0)
			Begin
				set @empField = ''empid''
			End
-- Added by Gopinath for Check field as name=''employeeid'' on Jan10th
		Else
		Begin
			set @empCount = (select count(*) as tot from syscolumns where name=''employeeid'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
            if (@empCount>0)
				Begin
					set @empField = ''employeeid''
				End
			Else
			-- Added by Gopinath for Check field as name=''EmployeeAutoId'' on April14th
			Begin
			set @empCount = (select count(*) as tot from syscolumns where name=''EmployeeAutoId'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
            if (@empCount>0)
				Begin
					set @empField = ''EmployeeAutoId''
				End
		End
		End
	End
--set @empField = ''emp_id''
--set @empCount = (select count(*) as tot from syscolumns where name=''employee_id'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
--if (@empCount>0)
--	Begin
--		set @empField = ''employee_id''
--	End
--Else
--	Begin
--		set @empCount = (select count(*) as tot from syscolumns where name=''employeeid'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
--		if (@empCount>0)
--			Begin
--				set @empField = ''employeeid''
--			End
--		Else
--			Begin
--					set @empCount = (select count(*) as tot from syscolumns where name=''empid'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
--					if (@empCount>0)
--						Begin
--							set @empField = ''empid''
--						End
--					Else
--						Begin
--							set @empCount = (select count(*) as tot from syscolumns where name=''emp_id'' and id=(select id from sysobjects WHERE xtype=''U'' and name = @tableName ))
--							if (@empCount>0)
--								Begin
--									set @empField = ''emp_id''
--								End
--							Else
--								Begin
--									set @empField=''''
--								End
--						End
--			End
--	End
--End of set Employee Id
	if (@InsertFields Is not null and @InsertFields != '''')
	Begin
	--create Insert Trigger	
		set @triggerName = ''InsertTrig'' + @tableName		
		set @sql = '' CREATE TRIGGER '' + @triggerName + '' ON ''+ @tableName
		set @sql = @sql + '' FOR INSERT AS ''
		--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
		--set @sql = @sql + '' DECLARE @newValue as nVARCHAR(3000)''
		--set @sql = @sql + '' DECLARE @newId as int''
		--set @sql = @sql + '' DECLARE @employeeId as int''
		--set @sql = @sql + '' SELECT @newId = (SELECT '' + @idColumn + '' FROM Inserted)''	
		if (@InsertFields is null or @InsertFields='''')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX('','',@InsertFields)
				if (@pos=0)
					Begin
						select @concat = @InsertFields
						set @InsertFields=''''
					End
				else
					Begin
						select @concat = substring(@InsertFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
				--set @sql1 = @sql1 + '' SELECT @newValue = (SELECT ''+ @concat +'' FROM Inserted)''		
				if (@empField !='''')
					Begin
						--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
						--set @sql1 = @sql1 + '' SELECT @employeeId = (SELECT ''+ @empField +'' FROM Inserted)''
						--set @sql1 = @sql1 + '' if(@NewId is not null and @NewId<>'''''''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr,EmployeeID) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@newValue,''''Insert'''',@employeeId)''
						--Adding By Manjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail 
						set @sql1=@sql1+'' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr,EmployeeID) select ''+ cast(@tableID as nvarchar(50)) +'','' + cast(@FieldID as nvarchar(50)) + '','' + cast(@idColumn as nvarchar(50)) + '','' + cast(@concat as nvarchar(50)) + '',''''Insert'''','' + cast(@empField as nvarchar(50)) + '' from inserted ''
						-- Commented By K.Gopinath on 03-Jan-2014 To avoid redudant data while inserting operation in Audit Trial
						-- I left join TA_Tbl_AuditOperation A on A.RecordID=''+ cast(@idColumn as nvarchar(25))
					End
				Else
					Begin
						--Commented By MAnjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail
						--set @sql1 = @sql1 + '' if(@NewId is not null and @NewId<>'''''''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@newValue,''''Insert'''')''
						--Adding By Manjula.P on 05-Sep-2013 to avoiding the subquery returns more than one value error when enabling audit trail 
						set @sql1=@sql1+'' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,NewValue,Opr) select ''+ cast(@tableID as nvarchar(50)) +'','' + cast(@FieldID as nvarchar(50)) + '','' + cast(@idColumn as nvarchar(50)) + '','' + cast(@concat as nvarchar(50)) + '',''''Insert'''' from inserted ''
						-- Commented By K.Gopinath on 03-Jan-2014 To avoid redudant data while inserting operation in Audit Trial
						--I left join TA_Tbl_AuditOperation A on A.RecordID=''+ cast(@idColumn as nvarchar(25))
					End
				set @InsertFields = substring(@InsertFields,@pos+1,len(@InsertFields))
				if (@InsertFields is null or @InsertFields='''')
					set @flag=0
				else
					set @flag=1			
			End		
		exec(@sql + '' '' + @sql1 )
	End
	if (@UpdateFields Is not null and @UpdateFields != '''')
	Begin
	--create Update Trigger
		set @sql=''''
		set @sql1=''''
		declare @sql2 as varchar(8000)
		set @sql2=''''
		set @triggerName = ''UpdateTrig'' + @tableName
		set @sql = ''if exists (select * from dbo.sysobjects where id = object_id(N''''[dbo].['' + @triggerName + '' ]'''') and OBJECTPROPERTY(id, N''''IsTrigger'''') = 1)''
		set @sql = @sql + '' drop trigger [dbo].['' + @triggerName + '']''
		exec(@sql)
		set @sql = '' CREATE TRIGGER '' + @triggerName + '' ON ''+ @tableName
		set @sql = @sql + '' FOR Update AS ''
		set @sql = @sql + '' DECLARE @newValue as nVARCHAR(3000)''
		set @sql = @sql + '' DECLARE @oldValue as nVARCHAR(3000)''
		set @sql = @sql + '' DECLARE @newId as int''
		set @sql = @sql + '' DECLARE @employeeId as int''
		--set @sql = @sql + '' SELECT @newId = (SELECT '' + @idColumn + '' FROM Inserted)''
		if (@UpdateFields is null or @UpdateFields='''')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX('','',@UpdateFields)
				if (@pos=0)
					Begin
						select @concat = @UpdateFields
						set @UpdateFields=''''
					End
				else
					Begin
						select @concat = substring(@UpdateFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				set @sql2= ''''
				--set @sql2 = @sql2 + '' SELECT @oldValue = (SELECT ''+ @concat +'' FROM Deleted)''
				--set @sql2 = @sql2 + '' SELECT @newValue = (SELECT ''+ @concat +'' FROM Inserted)''
				if (@empField !='''')
					Begin
						set @sql2 = @sql2 + '' SELECT @employeeId = (SELECT distinct ''+ @empField +'' FROM Inserted)''
						--set @sql2 = @sql2 + '' if (@oldValue <> @newValue)''
						--set @sql2 = @sql2 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@oldValue,@newValue,''''Update'''',@employeeId)''
						set @sql2 = @sql2 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID)  select ''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',b.'' + @idColumn + '', a.'' + @concat + '',b.'' + @concat + '',''''Update'''',@employeeId from Deleted a, Inserted b''
					End
				Else
					Begin
						--set @sql2 = @sql2 + '' if (@oldValue <> @newValue)''
						set @sql2 = @sql2 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',b.'' + @idColumn + '',@oldValue,@newValue,''''Update'''')''
					End
				set @UpdateFields = substring(@UpdateFields,@pos+1,len(@UpdateFields))
				if (@UpdateFields is null or @UpdateFields='''')
					set @flag=0
				else
					set @flag=1	
				set @sql1 = @sql1 + @sql2
			End			
		exec(@sql + '' '' + @sql1)
	End
	if (@DeleteFields Is not null and @DeleteFields != '''')
	Begin
	--create Delete Trigger
		set @sql=''''
		set @sql1=''''
		declare @sql3 as varchar(8000)
		set @sql3=''''
		set @triggerName = ''DeleteTrig'' + @tableName 		
		set @sql = ''if exists (select * from dbo.sysobjects where id = object_id(N''''[dbo].['' + @triggerName + '' ]'''') and OBJECTPROPERTY(id, N''''IsTrigger'''') = 1)''
		set @sql = @sql + '' drop trigger [dbo].['' + @triggerName + '']''
		exec(@sql)
		set @sql = '' CREATE TRIGGER '' + @triggerName + '' ON ''+ @tableName
		set @sql = @sql + '' FOR Delete AS ''		
		set @sql = @sql + '' DECLARE @oldValue as nVARCHAR(3000)''
		set @sql = @sql + '' DECLARE @newId as int''
		set @sql = @sql + '' DECLARE @employeeId as int''
		if (@DeleteFields is null or @DeleteFields='''')	
			set @flag=0
		else
			set @flag=1			
		while (@flag=1)
			Begin
				set @pos = charINDEX('','',@DeleteFields)
				if (@pos=0)
					Begin
						select @concat = @DeleteFields
						set @DeleteFields=''''
					End
				else
					Begin
						select @concat = substring(@DeleteFields,0,@pos)
					End
				set @FieldId = (select FieldID from ta_tbl_AuditField where FieldName=@concat and TableID=@tableId)	
				set @sql3 = ''''
				--set @sql3 = @sql3 + '' SELECT @newId = (SELECT '' + @idColumn + '' FROM Deleted)''
				--set @sql3 = @sql3 + '' SELECT @oldValue = (SELECT [''+ @concat +''] FROM Deleted)''				
				if (@empField !='''')
					Begin
						set @sql3 = @sql3 + '' SELECT @employeeId = (SELECT distinct ''+ @empField +'' FROM Deleted)''
						--set @sql3 = @sql3 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr,EmployeeID) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@oldValue,''''Delete'''',@employeeId)''
--						set @sql2 = @sql2 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,NewValue,Opr,EmployeeID)  select ''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',b.'' + @idColumn + '', a.'' + @concat + '',b.'' + @concat + '',''''Update'''',@employeeId from Deleted a, Inserted b''
						set @sql3 = @sql3 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr,EmployeeID)           select ''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '','' + @idColumn + '',''+ @concat+ '',''''Delete'''',@employeeId from Deleted''
					End
				Else
					Begin
						--set @sql3 = @sql3 + '' Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@oldValue,''''Delete'''')''
						set @sql3 = @sql3 + ''if(@NewId is not null and @NewId<>'''''''') Insert into TA_Tbl_AuditOperation (tableid,fieldID,RecordID,OldValue,Opr) values (''+ cast(@tableID as nvarchar(25)) +'','' + cast(@FieldID as nvarchar(25)) + '',@NewId,@oldValue,''''Delete'''')''
					End
				set @DeleteFields = substring(@DeleteFields,@pos+1,len(@DeleteFields))
				if (@DeleteFields is null or @DeleteFields='''')
					set @flag=0
				else
					set @flag=1			
			set @sql1 = @sql1 + @sql3
			End				
			exec(@sql + '' '' + @sql1 )
	End
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_GetParentIds]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_GetParentIds]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'create function [dbo].[Func_TA_GetParentIds]
(
@LevelId as varchar(500)
)
returns varchar(500)
as
begin
	declare @ParentLevelId as varchar(250)
	declare @LevelIdFinal as varchar(250)
	declare @Pos as int
	declare @Id as int
	declare @TableCount as int
	declare @OrgninId as int;
	set @LevelId=@LevelId;
	declare @TempLevelId table 
	(
	SlNo int identity(1,1) not null,
	LevelId int
	)
	insert into @TempLevelId
	select Value from dbo.Split(@LevelId,'','')
	set @TableCount=(select COUNT(*) from @TempLevelId)
	set @Pos=1;
	while (@Pos<=@TableCount)
	begin
		set @Id=(select LevelId from @TempLevelId where SlNo=@Pos)
		while (@Id>0)
		begin
			set @ParentLevelId=(select isnull(parentId,0) from Ta_Tbl_levelDetails where id in (@Id));
			set @OrgninId=@Id;
			set @Id=@ParentLevelId;		
		end
		set @LevelIdFinal= COALESCE(@LevelIdFinal + '','', '''')+cast(@OrgninId as varchar(100));
		set @Pos=@Pos+1;
	end
	RETURN @LevelIdFinal
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header_Email]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_header_Email]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create PROCEDURE [dbo].[Proc_TA_Rpt_header_Email]  
(      
 @LevelId int     
)
AS      
BEGIN        
	IF @LevelId <> 0
		BEGIN  
			DECLARE @LevelName table (LevelID int,LevelName nvarchar(250))    
			DECLARE @string nvarchar(2000) 
			WHILE((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '''')    
				BEGIN    
					INSERT INTO @LevelName select id,replace(name,''&amp;'',''&'') from TA_tbl_LevelDetails where id=@LevelId    
					SET @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId)
				END    
			SET @string = (select LevelName + '' / '' from @LevelName order by LevelID asc for xml path(''''))    
			SET @string = LEFT(@string,LEN(@string) - 1)     
			SELECT isnull(@string,'''') as name,city,logo from  TA_tbl_LevelDetails where id=(select min(LevelID) from @LevelName)    
		END  
	ELSE   
		BEGIN  
			SELECT logo from TA_tbl_LevelDetails where id=1
		END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_header]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_header]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================      
-- Author:  <Author,,Name>      
-- ALTER  date: <Create Date,,>      
-- Description: <Description,,>      
-- =============================================      
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_header]  
(      
 @LevelId int    
)
AS      
BEGIN        
	IF @LevelId <> 0
		BEGIN  
			DECLARE @LevelName table (LevelID int,LevelName nvarchar(250))    
			DECLARE @string nvarchar(2000) 
			WHILE((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '''')    
				BEGIN    
					INSERT INTO @LevelName select id,replace(name,''&amp;'',''&'') from TA_tbl_LevelDetails where id=@LevelId    
					SET @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId)
				END    
			SET @string = (select LevelName + '' / '' from @LevelName order by LevelID asc for xml path(''''))    
			SET @string = LEFT(@string,LEN(@string) - 1)     
			SELECT isnull(@string,'''') as name,city,logo from  TA_tbl_LevelDetails where id=(select min(LevelID) from @LevelName)    
		END  
	ELSE   
		BEGIN  
			SELECT logo from TA_tbl_LevelDetails where id=1
		END  
END      
    ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntryWithLocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : KUMUTHINI. L  
--  Created On         : 03-Sep-2007  
--  Modified On        : 22-Nov-2007  
--  Description         : This Procedure is used to insert the Manual Time Entry  
--  [Proc_TA_InsertManualTimeEntry] 787,''04-03-2019 14:00:22'',''04-03-2019 14:00:22'',''04-03-2019 14:00:22'',''Shift In'','''','''','''',0,0,''Shift In'',0,''Approved'',''04-03-2019 14:00:22'',4,3,0
-- ================================================================================    
create  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntryWithLocation]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),
	@ManualEntry_Date DATETIME,
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImported int,
	@Latitude_value varchar(20),
	@Longitude_value varchar(20),
	@Clock_Address varchar(500)
)  
AS  
begin
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0
	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=787
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReader_Id
		if(@CountReader>1)
		begin			
			set @OutReader_Id=@InReader_Id
		end		
		--if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType=@InPunchType)
		--begin
		--	select Top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType in(''In'',''Shift In'')
		--end
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=788
	END		
	IF(@InDate = '' '')
	   BEGIN    
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,
		 ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,
		 Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported,
		 Latitude_value,Longitude_value,Clock_Address)
		 VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@OutTime,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,@Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10))
		 ,cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)),@Latitude_value,@longitude_value,@Clock_Address) 
	   END
	ELSE IF(@OutDate = '' '')  
	  BEGIN
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported,
		Latitude_value,Longitude_value,Clock_Address)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,cast(@InReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1))
		,@Latitude_value,@longitude_value,@Clock_Address) 
	  END
	ELSE
	  BEGIN    
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,@OutDate,@OutTime,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),''N'', cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent_Email]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsent_Email]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
 Proc_Ta_rptAbsent ''2014-07-07'',''2014-07-07'','''',0,'''','''',0,0,''SuperAdmin'',0,'''',0
*/
CREATE  PROCEDURE [dbo].[Proc_Ta_rptAbsent_Email]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@DesignationID int,
	@Gender varchar(10),
	@ParentID bigint		
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
create table #LevelRights(LevelId int)
if(@ParentId=''124'')
Begin
insert into  #LevelRights values (124)
insert into  #LevelRights values (125)
insert into  #LevelRights values (129)
insert into  #LevelRights values (131)
insert into  #LevelRights values (130) 
End
--Employee Level Indexes
Else
Begin
insert into  #LevelRights values (107)
insert into  #LevelRights values (123)
insert into  #LevelRights values (108)
insert into  #LevelRights values (109)
insert into  #LevelRights values (110)
insert into  #LevelRights values (111)
insert into  #LevelRights values (112)
insert into  #LevelRights values (113)
insert into  #LevelRights values (114)
insert into  #LevelRights values (115)
end
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
--create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
create table #TempProcesseddata(FirstSession varchar(100),SecondSession varchar(100),LevelID int,DesignationId int,Employee_Code_Id varchar(25),
date Datetime,empname varchar(150),Attendance varchar(25),TitleName varchar(50),name varchar(150),Shift_ShortName varchar(50),Gender varchar(20))
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''		
		set @sqlQuery = @sqlQuery + ''SELECT TA_Tbl_ProcessedData.fnAttendanceCode as FirstSession,TA_Tbl_ProcessedData.anAttendanceCode as SecondSession,   TA_Tbl_EmployeeLevel.LevelID, TA_Tbl_EmployeeDesignation.DesignationId, TA_Tbl_Employee.Employee_Code_Id,''
		set @sqlQuery = @sqlQuery + '' TA_Tbl_ProcessedData.Date AS date, isnull(TA_Tbl_Employee.Employee_FirstName,'''''''') + SPACE(1)'' 
		set @sqlQuery = @sqlQuery + '' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''') AS empname, TA_Tbl_ProcessedData.Attendance, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName ,'' 
		set @sqlQuery = @sqlQuery + '' replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, ta_tbl_shift.Shift_ShortName, TA_Tbl_Employee.Gender''
		set @sqlQuery = @sqlQuery + '' FROM TA_Tbl_ProcessedData INNER JOIN''
		set @sqlQuery = @sqlQuery + '' TA_Tbl_Employee ON TA_Tbl_ProcessedData.Employee_Code_Id = TA_Tbl_Employee.SwipeCardNo''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
		set @sqlQuery = @sqlQuery + '' TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID  '' 	
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId ''
		set @sqlQuery = @sqlQuery + '' WHERE (TA_Tbl_ProcessedData.fnAttendanceCode = ''''Absent'''' OR TA_Tbl_ProcessedData.AnAttendanceCode =''''Absent'''') AND (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)''		
        --set @sqlQuery = @sqlQuery + '' or (TA_Tbl_ProcessedData.fnAttendanceCode = ''''LOP'''' OR TA_Tbl_ProcessedData.AnAttendanceCode =''''LOP'''')''
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
		set @sqlQuery = @sqlQuery + '' AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 
		set @sqlQuery = @sqlQuery + '' AND (TA_Tbl_ProcessedData.Intime is null and TA_Tbl_ProcessedData.Outtime is null) and cast(convert(varchar, TA_Tbl_ProcessedData.Date, 111) + '''' '''' +  convert(varchar,cast(Shift_StartTime as datetime),114) as datetime) <= getdate() ''
		if(@UserGroupName<>''SuperAdmin'')
		begin
			--if(@EmpAutoId<>0)
			--	BEGIN
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		--+ '' AND (ta_tbl_Employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or ta_tbl_Employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''' or ta_tbl_Employee.Employee_Id='''''' + cast(@EmpAutoId as varchar(30)) +'''''')''
			--	END
			--else
			--	 BEGIN
			--		SET @sqlQuery = @sqlQuery + '' AND (TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  + '' or ta_tbl_Employee.Employee_code_Id='''''' + isnull(cast(@empId as varchar(50)),'''') +'''''')''
			--	 END 
			--SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  + '' AND (ta_tbl_Employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or ta_tbl_Employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''' or ta_tbl_Employee.Employee_Id='''''' + cast(@EmpAutoId as varchar(30)) +'''''')''
		end
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  '' And  Ta_Tbl_ProcessedData.Shift_Id = '' +  cast(@shift  as nvarchar(20))  
			end
		if not(@EmployeeName='''')
			begin
				set @sqlQuery = @sqlQuery + ''and (TA_Tbl_Employee.Employee_FirstName + isnull(TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
			end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End
		if not (@empId='''')
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
			end
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryId = '' +cast(@employeeCategory as nvarchar(8))
			end
		if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		if(@DesignationID<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' +cast(@employeeType as nvarchar(8))
			end		
		--if(@EmpAutoId = 0)
		--BEGIN
		--	if not(@LevelID='''' or @LevelID=''0'')
		--		begin
		--			set @sqlQuery = @sqlQuery + '' and (#EmpLevel.LevelId IN ('' + @LevelId + ''))'' 
		--		end	
		--END
		if(@EmpAutoId > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END	
		set @sqlQuery = @sqlQuery + '' order by TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date''
	insert into #TempProcesseddata 
		exec(@sqlQuery)
		--select * from #TempProcesseddata
update #TempProcesseddata set FirstSession=FirstSession + '' (L-''+ L.Status+'')''  from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_leaveApplication L on L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
where L.isdeleted=0 and L.Leave_SessionFrom=''First Half'' and L.Status <> ''Approved''
update #TempProcesseddata set FirstSession=FirstSession + '' (P-''+PER.Permission_status+'')'' from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_permission PER on PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
where PER.isdeleted=0 and PER.Permission_status<> ''Approved''
update #TempProcesseddata set SecondSession=SecondSession + '' (L-''+ L.Status+'')''  from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_leaveApplication L on L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
where L.isdeleted=0 and L.Leave_SessionTo=''Second Half'' and L.Status <> ''Approved''
update #TempProcesseddata set SecondSession=SecondSession + '' (P-''+PER.Permission_status+'')'' from #TempProcesseddata P
inner join ta_tbl_employee E on P.employee_code_Id=E.swipecardNo
inner join ta_tbl_permission PER on PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
where PER.isdeleted=0 and PER.Permission_status<> ''Approved''
select * from #TempProcesseddata
--select * from ta_tbl_permission
--select * from ta_tbl_leaveApplication where Leave_FromDate=''2011-04-13'' between ''04/04/2011'' and ''08/30/2011''
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
drop table #TempProcesseddata 
drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingEachDropDown]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingEachDropDown]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingEachDropDown]
	-- Add the parameters for the stored procedure here
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT count(*) from Ta_Tbl_levelDetails where parentId=@ParentId and isDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingDeviceMappingInEntrance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016 12.05 PM>
-- Description:	<Checking Device Mapping in Entrance>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingDeviceMappingInEntrance]
	-- Add the parameters for the stored procedure here
	@Clk_DeviceId nvarchar(20),
	@Type char(1)
AS
BEGIN
	SET NOCOUNT ON;
	if(@Type=''C'')
	begin
		select count(TYPE)as count from ta_tbl_entrance_inoutdetails EIO 
		inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
		where T.Terminal_ReaderID=@Clk_DeviceId
	end
	else
	begin
		select TYPE from ta_tbl_entrance_inoutdetails EIO 
		inner join ta_tbl_terminal T On EIO.reader_id=T.Terminal_ID 
		where T.Terminal_ReaderID=@Clk_DeviceId
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DataBaseArcheive]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DataBaseArcheive]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <12-Mar-2012>
-- Description:	<Move the Data to database archive>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DataBaseArcheive]
	-- Add the parameters for the stored procedure here
	@Month INT,
	@Year INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupProcesseddata'')
		BEGIN
			CREATE TABLE [dbo].[TA_Tbl_ProcessedData](
			[Process_Rec_ID] [bigint] IDENTITY(1,1) NOT NULL,
			[Employee_Code_Id] [nvarchar](20) NULL,
			[Date] [datetime] NULL,
			[Shift_Id] [int] NULL,
			[InTime] [nvarchar](25) NULL,
			[OutTime] [nvarchar](25) NULL,
			[HrsWork] [nvarchar](10) NULL,
			[HrsOT] [nvarchar](10) NULL,
			[NormOT] [nvarchar](10) NULL,
			[OffOT] [nvarchar](10) NULL,
			[HolOT] [nvarchar](10) NULL,
			[EarlyOut] [nvarchar](10) NULL,
			[LateIn] [nvarchar](10) NULL,
			[Attendance] [nvarchar](20) NULL,
			[WorkHrs] [nvarchar](10) NULL,
			[HrsLess] [nvarchar](10) NULL,
			[HrsExtra] [nvarchar](10) NULL,
			[LateInMins] [float] NULL,
			[EarlyOutMins] [float] NULL,
			[ExtraMins] [float] NULL,
			[OtMins] [float] NULL,
			[OvertimeStatus] [nvarchar](50) NULL,
			[TotalDays] [numeric](18, 1) NULL,
			[LeaveCode] [nvarchar](20) NULL,
			[LateEntryReason] [nvarchar](260) NULL,
			[EarlyOutReason] [nvarchar](260) NULL,
			[ProcessFlag] [bit] NULL,
			[Status] [nvarchar](50) NULL,
			[FNAttendanceCode] [nvarchar](15) NULL,
			[ANAttendanceCode] [nvarchar](15) NULL)
			IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupClk_RawData'')
				begin
					CREATE TABLE [dbo].[TA_Tbl_Clk_RawData](
					[CLK_ID] [bigint] IDENTITY(1,1) NOT NULL,
					[CLK_CARDID] [nvarchar](20) NULL,
					[CLK_DEVICEID] [nvarchar](20) NULL,
					[CLK_DATE] [datetime] NULL,
					[CLK_TIME] [nvarchar](25) NULL,
					[CLK_TYPE] [nvarchar](15) NULL,
					[CLK_FLAG] [int] NULL,
					[CLK_PROCESS] [int] NULL,
					[TimecheckDateTime] [datetime] NULL,
					[TimeStamp] [datetime] NOT NULL)
					IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupClockDetails'')
						begin
						CREATE TABLE [dbo].[TA_Tbl_ClockDetails](
						[Clk_Id] [int] IDENTITY(1,1) NOT NULL,
						[Clk_CompId] [nvarchar](10) NULL,
						[Clk_EmpId] [nvarchar](20) NULL,
						[Clk_InDeviceId] [nvarchar](20) NULL,
						[Clk_InDate] [datetime] NULL,
						[Clk_InTime] [datetime] NULL,
						[Clk_InPunchType] [nvarchar](25) NULL,
						[Clk_OutDeviceId] [nvarchar](20) NULL,
						[Clk_OutDate] [datetime] NULL,
						[Clk_OutTime] [datetime] NULL,
						[Clk_OutPunchType] [nvarchar](25) NULL,
						[Clk_Process] [nvarchar](1) NULL,
						[Clk_Remarks] [nvarchar](100) NULL,
						[Clk_User] [nvarchar](20) NULL,
						[Clk_Date] [datetime] NULL,
						[Clk_Status] [nvarchar](1) NULL,
						[IsVoid] [bit] NULL)
							IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupManualTimeEntry'')
								begin
									CREATE TABLE [dbo].[Ta_Tbl_ManualTimeEntry](
									[ManualTimeEntry_Id] [int] IDENTITY(1,1) NOT NULL,
									[ManualTimeEntry_Employee_Id] [nvarchar](20) NULL,
									[ManualTimeEntry_Date] [datetime] NULL,
									[ManualTimeEntry_InDate] [datetime] NULL,
									[ManualTimeEntry_InTime] [nvarchar](50) NULL,
									[ManualTimeEntry_InPunchType] [nvarchar](25) NULL,
									[ManualTimeEntry_OutDate] [datetime] NULL,
									[ManualTimeEntry_OutTime] [nvarchar](50) NULL,
									[ManualTimeEntry_OutPunchType] [nvarchar](25) NULL,
									[ManualTimeEntry_InReaderID] [int] NULL,
									[ManualTimeEntry_OutReaderID] [int] NULL,
									[ManualTimeEntry_Reason] [nvarchar](255) NULL,
									[ManualTimeEntry_Remarks] [nvarchar](255) NULL,
									[Route_Id] [int] NULL,
									[Clk_Process] [nvarchar](1) NULL,
									[ManualTimeEntry_Status] [nvarchar](25) NULL,
									[Isdeleted] [bit] NULL,
									[TimeStamp] [datetime] NULL,
									[Emp_Id] [int] NULL,
									[YearSettings_Id] [int] NULL,
									[IsDiscrepancyEntry] [bit] NULL,
									[IsOnDuty] [bit] NULL
								)
									IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupLeaveApplication'')
										begin
											CREATE TABLE [dbo].[TA_Tbl_LeaveApplication](
											[LeaveApplication_Id] [int] IDENTITY(1,1) NOT NULL,
											[Employee_Id] [nvarchar](20) NOT NULL,
											[Leave_ApplicationDate] [datetime] NOT NULL,
											[LeaveType_id] [int] NOT NULL,
											[Type] [nvarchar](50) NOT NULL,
											[Leave_FromDate] [datetime] NOT NULL,
											[Leave_ToDate] [datetime] NOT NULL,
											[Leave_SessionFrom] [nvarchar](50) NOT NULL,
											[Leave_SessionTo] [nvarchar](50) NOT NULL,
											[NumberOfDays] [decimal](18, 1) NOT NULL,
											[Reason] [nvarchar](250) NULL,
											[Status] [nvarchar](50) NULL,
											[IsDeleted] [bit] NOT NULL,
											[Remarks] [nvarchar](250) NULL,
											[IsBorrow] [bit] NULL,
											[Emp_Id] [int] NULL,
											[YearSettings_Id] [int] NULL,
											[CompanyId] [int] NULL,
											[Successiveyear] [bit] NULL)
											IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_BackupPermission'')	
												begin
												CREATE TABLE [dbo].[TA_Tbl_Permission](
												[Permission_Id] [int] IDENTITY(1,1) NOT NULL,
												[Employee_Id] [int] NOT NULL,
												[Permission_AppliedDate] [datetime] NOT NULL,
												[Permission_Date] [datetime] NOT NULL,
												[Permission_Type] [nvarchar](50) NULL,
												[Permission_FromTime] [datetime] NOT NULL,
												[Permission_ToTime] [datetime] NOT NULL,
												[Permission_Reason] [nvarchar](250) NOT NULL,
												[Permission_Status] [nvarchar](50) NULL,
												[Emp_Id_Sanction] [int] NULL,
												[Remarks] [nvarchar](250) NULL,
												[IsDeleted] [bit] NOT NULL,
												[TimeStamp] [datetime] NOT NULL,
												[Emp_Id] [int] NULL,
												[YearSettings_Id] [int] NULL,
												[No_Of_Hours] [nvarchar](10) NULL)
													IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_Backup_PermanentShiftAllocation'')			
														begin
															CREATE TABLE [dbo].[TA_Tbl_PermanentShiftAllocation](
															[EmployeeId] [int] NOT NULL,
															[Year] [int] NOT NULL,
															[Month] [int] NOT NULL,
															[Day1Shift] [int] NOT NULL,
															[Day2Shift] [int] NOT NULL,
															[Day3Shift] [int] NOT NULL,
															[Day4Shift] [int] NOT NULL,
															[Day5Shift] [int] NOT NULL,
															[Day6Shift] [int] NOT NULL,
															[Day7Shift] [int] NOT NULL,
															[Day8Shift] [int] NOT NULL,
															[Day9Shift] [int] NOT NULL,
															[Day10Shift] [int] NOT NULL,
															[Day11Shift] [int] NOT NULL,
															[Day12Shift] [int] NOT NULL,
															[Day13Shift] [int] NOT NULL,
															[Day14Shift] [int] NOT NULL,
															[Day15Shift] [int] NOT NULL,
															[Day16Shift] [int] NOT NULL,
															[Day17Shift] [int] NOT NULL,
															[Day18Shift] [int] NOT NULL,
															[Day19Shift] [int] NOT NULL,
															[Day20Shift] [int] NOT NULL,
															[Day21Shift] [int] NOT NULL,
															[Day22Shift] [int] NOT NULL,
															[Day23Shift] [int] NOT NULL,
															[Day24Shift] [int] NOT NULL,
															[Day25Shift] [int] NOT NULL,
															[Day26Shift] [int] NOT NULL,
															[Day27Shift] [int] NOT NULL,
															[Day28Shift] [int] NOT NULL,
															[Day29Shift] [int] NOT NULL,
															[Day30Shift] [int] NOT NULL,
															[Day31Shift] [int] NOT NULL,
															[Emp_Id] [int] NOT NULL,
															[TimeStamp] [datetime] NOT NULL,
															[DateShift] [datetime] NOT NULL)
															IF NOT EXISTS(select * from sys.tables WHERE NAME=''TA_Tbl_Backup_TemporaryShiftAllocation'')	
																begin
																	CREATE TABLE [dbo].[TA_Tbl_TemporaryShiftAllocation](
																	[EmployeeId] [int] NOT NULL,
																	[Year] [int] NOT NULL,
																	[Month] [int] NOT NULL,
																	[Day1Shift] [int] NOT NULL,
																	[Day2Shift] [int] NOT NULL,
																	[Day3Shift] [int] NOT NULL,
																	[Day4Shift] [int] NOT NULL,
																	[Day5Shift] [int] NOT NULL,
																	[Day6Shift] [int] NOT NULL,
																	[Day7Shift] [int] NOT NULL,
																	[Day8Shift] [int] NOT NULL,
																	[Day9Shift] [int] NOT NULL,
																	[Day10Shift] [int] NOT NULL,
																	[Day11Shift] [int] NOT NULL,
																	[Day12Shift] [int] NOT NULL,
																	[Day13Shift] [int] NOT NULL,
																	[Day14Shift] [int] NOT NULL,
																	[Day15Shift] [int] NOT NULL,
																	[Day16Shift] [int] NOT NULL,
																	[Day17Shift] [int] NOT NULL,
																	[Day18Shift] [int] NOT NULL,
																	[Day19Shift] [int] NOT NULL,
																	[Day20Shift] [int] NOT NULL,
																	[Day21Shift] [int] NOT NULL,
																	[Day22Shift] [int] NOT NULL,
																	[Day23Shift] [int] NOT NULL,
																	[Day24Shift] [int] NOT NULL,
																	[Day25Shift] [int] NOT NULL,
																	[Day26Shift] [int] NOT NULL,
																	[Day27Shift] [int] NOT NULL,
																	[Day28Shift] [int] NOT NULL,
																	[Day29Shift] [int] NOT NULL,
																	[Day30Shift] [int] NOT NULL,
																	[Day31Shift] [int] NOT NULL,
																	[Emp_Id] [int] NOT NULL,
																	[TimeStamp] [datetime] NOT NULL,
																	[DateShift] [datetime] NOT NULL
																) 
																enD			
														end
												end
										end
								end
						end
				end
		END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupProcesseddata WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year AND PROCESSFLAG=0)
					BEGIN
						select ''UnProcesseddataExists'' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupProcesseddata 
						SELECT * FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year
						DELETE FROM TA_TBL_PROCESSEDDATA WHERE MONTH(DATE)=@Month AND YEAR(DATE)=@Year
						SELECT ''Success''
					END
			END
		ELSE
			BEGIN
				SELECT ''ProcesseddataExists''
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupClk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year AND CLK_FLAG = 0 AND CLK_PROCESS =0)
					BEGIN
						SELECT ''UnProcessed_Clk_Dataexists'' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupClk_RawData
						SELECT * FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
						DELETE FROM TA_Tbl_Clk_RawData WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
						SELECT ''Success''
					END
			END
		ELSE
			BEGIN
				SELECT ''Clk_RawdataExists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year)
			BEGIN
				INSERT INTO TA_Tbl_BackupClockDetails
				SELECT * FROM TA_Tbl_ClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
				DELETE FROM TA_Tbl_ClockDetails WHERE MONTH(CLK_DATE)=@Month AND YEAR(CLK_DATE)=@Year
				SELECT ''Success''
			END
		ELSE
			BEGIN
				SELECT ''ClockDetailsExists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
		AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
				AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year AND CLK_PROCESS <> ''N'' AND (ManualTimeentry_status <> ''Approved'' or 
				ManualTimeentry_status <> ''Rejected''))
					BEGIN
						SELECT ''UnprocessedManualEntryExists'' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupManualTimeEntry
						SELECT * FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
						AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year
						DELETE FROM TA_Tbl_ManualTimeEntry WHERE MONTH(ManualTimeEntry_InDate)=@Month and YEAR(ManualTimeEntry_InDate)=@Year 
						AND MONTH(ManualTimeEntry_OutDate)=@Month AND YEAR(ManualTimeEntry_OutDate)=@Year
						SELECT ''Success''
					END
			END
		ELSE
			BEGIN
				SELECT ''ManualEntryExists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_BackupLeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year AND (STATUS<>''Approved'' OR STATUS<> ''Rejected''))
					begin
						SELECT ''UnProcessedLeaveExists'' as Alert
					END
				ELSE
					BEGIN
						INSERT INTO TA_Tbl_BackupLeaveApplication
						SELECT * FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year
						DELETE FROM TA_Tbl_LeaveApplication WHERE MONTH(Leave_FromDate)=@Month AND YEAR(Leave_FromDate)=@Year AND MONTH(Leave_ToDate)=@Month AND YEAR(Leave_ToDate)=@Year
						SELECT ''Success''
					END
			END	
		ELSE
			BEGIN
				SELECT ''Leavedataexists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year)
			BEGIN
				IF EXISTS(SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year AND (Permission_Status <> ''Approved'' or Permission_Status <> ''Rejected''))
					begin
						select ''UnprocessedPermissionExists'' as Alert
					end
				else	
					begin
						INSERT INTO TA_Tbl_BackupPermission
						SELECT * FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year
						DELETE FROM TA_Tbl_Permission WHERE MONTH(Permission_Date)=@Month AND YEAR(Permission_Date)=@Year
						SELECT ''Success''
					end
			END	
		ELSE
			BEGIN
				SELECT ''PermissionExists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Backup_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month)
			BEGIN
				INSERT INTO TA_Tbl_BackupPermission
				SELECT * FROM TA_Tbl_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				DELETE FROM TA_Tbl_PermanentShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				SELECT ''Success''
			END
		ELSE
			BEGIN
				SELECT ''PermanentShiftallocatioExists'' as Alert
			END
		IF NOT EXISTS(SELECT * FROM TA_Tbl_Backup_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month)
			BEGIN
				INSERT INTO TA_Tbl_Backup_TemporaryShiftAllocation
				SELECT * FROM TA_Tbl_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				DELETE FROM TA_Tbl_TemporaryShiftAllocation WHERE YEAR(Year)=@Year and MONTH(Month)=@Month
				SELECT ''Success''
			END
		ELSE
			BEGIN
				SELECT ''TemporaryShiftallocatioExists'' as Alert
			END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteChildrenDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteChildrenDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_DeleteChildrenDetails  
Description : delete children details  
Tables Included : TA_Tbl_EmpChildrenDetails  
Created By : Arun Vinoth.T  
Created On : 27-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_DeleteChildrenDetails]
		@EmployeeId INT
	AS
	BEGIN
		DELETE FROM  TA_Tbl_EmpChildrenDetails  WHERE Emp_ID=@EmployeeId AND Spouse_Child=''C''
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delEmployee]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_delEmployee]
(    
	@EmpID int    
)    
as    
begin    
	declare @checkFlag  int    
	set @checkFlag = 0    
	declare @recCount as int    
	declare @recCount1 as int  
	declare @recCount2 as int  
	declare @recCount3 as int  
	declare @recCount5 as int
	declare @recCount6 as int 
	declare @recCount7 as int 
	select @recCount=count(*) from Ta_Tbl_Employee where Reporting_to=@EmpID and isdeleted=0
	select @recCount1 = count(*) from Ta_Tbl_Employee where Leave_Sanc_Authority=@EmpID and isdeleted=0
	select @recCount2 = count(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmpID and isdeleted=0
	select @recCount3 = count(*) from TA_Tbl_Permission where Employee_Id=@EmpID and isdeleted=0
	select @recCount5 = count(*) from ta_Tbl_permanentshiftallocation where employeeid=@EmpID
	select @recCount6 = count(*) from ta_Tbl_temporaryshiftallocation where employeeid=@EmpID
	select @recCount7= count(*) from TA_Tbl_EmployeeBonusLeave where EmployeeId=@EmpID
	if (@recCount>0 or @recCount1>0 or @recCount2>0 or @recCount3>0 or @recCount5>0 or @recCount6>0 or @recCount7>0)
		Begin    
			set @checkFlag=1    
		End
	select @checkFlag as checkFlag    
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateMasterDataLevelsParent]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateMasterDataLevelsParent]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateMasterDataLevelsParent]
AS
BEGIN
update Ta_Tbl_ImportMasterData 
set Level1_Id= t2.id
from TA_Tbl_LevelDetails t2
inner join Ta_Tbl_ImportMasterData t1
on t2.name=t1.Level1
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertNearingShiftDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertNearingShiftDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <17-03-2017 02.54 pm>
-- Description:	<Update shift details through Nearest shift allocation screen>
-- Proc_TA_InsertNearingShiftDetails 3,''04/01/2017 12:00:00 AM'',3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertNearingShiftDetails]
	@Empid bigint,
	@ShiftDate datetime,
	@ShiftID int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @year INT
	DECLARE @month INT
	DECLARE @day INT
	DECLARE @DynamicQuery VARCHAR(MAX)
	SET @DynamicQuery =''''	
	SELECT @year=DATEPART(YEAR,@ShiftDate),@month=DATEPART(MONTH,@ShiftDate),@day=DATEPART(DAY,@ShiftDate)
	--select @year,@month,@day
	IF(@year is not null and @month is not null and @day is not null)
	BEGIN
		if exists(select * from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@Empid)
		begin
			SET @DynamicQuery =@DynamicQuery +''update TA_Tbl_PermanentShiftAllocation set day''+CONVERT(VARCHAR(2),@day)+''shift=''+CONVERT(VARCHAR(2),@ShiftID)+ '' where
			month=''+CONVERT(VARCHAR(20),@month)+'' and year=''+CONVERT(VARCHAR(20),@year)+'' and employeeid=''+CONVERT(VARCHAR(20),@Empid)
		end
		else
		begin
			SET @DynamicQuery =@DynamicQuery +''insert into TA_Tbl_PermanentShiftAllocation (day''+CONVERT(VARCHAR(2),@day)+''shift,month,year,employeeid,Emp_id,dateshift)
			values(''+CONVERT(VARCHAR(2),@ShiftID)+ '',''+CONVERT(VARCHAR(20),@month)+'',''+CONVERT(VARCHAR(20),@year)+'',''+CONVERT(VARCHAR(20),@Empid)+'',1,''''''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+'''''')''
		end
		--print(@DynamicQuery)			
		EXECUTE(@DynamicQuery)
		Declare @SwipeCardNumber varchar(50)
		select @SwipeCardNumber=SwipeCardNo from ta_tbl_employee where Employee_Id=@Empid and isdeleted=0
		--select @ShiftDate,@ShiftDate,@EmployeeCodeId
		DELETE PD FROM TA_Tbl_ProcessedData PD Where PD.Date BETWEEN @ShiftDate AND @ShiftDate And PD.Employee_Code_Id=@SwipeCardNumber
		Update TA_Tbl_Clk_RawData Set CLK_FLAG=0,CLK_PROCESS=0 Where CLK_DATE BETWEEN dateadd(d,-1,@ShiftDate) AND dateadd(d,1,@ShiftDate)
		and CLK_CARDID=@SwipeCardNumber
		Delete CD from TA_Tbl_ClockDetails CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN @ShiftDate AND @ShiftDate 
		Delete CD from ta_tbl_MatchedPunches CD Where CD.Clk_EmpId=@SwipeCardNumber and CD.Clk_Date BETWEEN @ShiftDate AND @ShiftDate 
		UPDATE MT SET MT.Clk_Process = ''N'' from TA_Tbl_ManualTimeEntry MT
		Inner join TA_Tbl_Employee E on E.Employee_Code_Id = MT.ManualTimeEntry_Employee_Id 
		AND ((MT.ManualTimeEntry_InDate BETWEEN DateAdd(d,-1,@ShiftDate) AND DateAdd(d,1,@ShiftDate)) 
		OR (MT.ManualTimeEntry_OutDate BETWEEN DateAdd(d,-1,@ShiftDate) AND DateAdd(d,1,@ShiftDate)))
		where E.Employee_Id=@Empid
	END	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertManualTimeEntry]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertManualTimeEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ================================================================================  
--  Procedure Name : Proc_TA_InsertManualTimeEntry  
--  Author                 : KUMUTHINI. L  
--  Created On         : 03-Sep-2007  
--  Modified On        : 22-Nov-2007  
--  Description         : This Procedure is used to insert the Manual Time Entry  
--  [Proc_TA_InsertManualTimeEntry] 787,''04-03-2019 14:00:22'',''04-03-2019 14:00:22'',''04-03-2019 14:00:22'',''Shift In'','''','''','''',0,0,''Shift In'',0,''Approved'',''04-03-2019 14:00:22'',4,3,0
-- ================================================================================    
CREATE  PROCEDURE [dbo].[Proc_TA_InsertManualTimeEntry]  
(  
	@ManualEntry_EmployeeId NVARCHAR(20),
	@ManualEntry_Date DATETIME,
	@InDate NVARCHAR(15),  
	@InTime NVARCHAR(20), 
	@InPunchType NVARCHAR(25),
	@OutDate NVARCHAR(15),  
	@OutTime NVARCHAR(20),
	@OutPunchType NVARCHAR(25),
	@InReader_Id INT,  
	@OutReader_Id INT,  
	@Reason NVARCHAR(255),  
	@RouteId INT, 
	@Status nVarchar(25), 
	@TimeStamp DATETIME,  
	@UserId INT,
	@YearSettings_Id NVARCHAR(25),
	@IsOnDuty INT,
	@IsImported int
)  
AS  
begin
	SET NOCOUNT ON;
	DECLARE @Isdel INT  
	SET @Isdel=0
	if(@InReader_Id=787 or @InReader_Id=0)
	BEGIN
		SELECT @InReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=787
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReader_Id
		if(@CountReader>1)
		begin			
			set @OutReader_Id=@InReader_Id
		end		
		--if not exists(select PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType=@InPunchType)
		--begin
		--	select Top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InReader_Id and PunchType in(''In'',''Shift In'')
		--end
	END
	IF(@OutReader_Id=788 or @OutReader_Id=0)
	BEGIN
		SELECT @OutReader_Id=Terminal_Id FROM TA_Tbl_Terminal WHERE Terminal_ReaderID=788
	END		
	IF(@InDate = '' '')
	   BEGIN    
		 INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_OutDate,
		 ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,
		 Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		 VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@OutDate,@OutTime,@OutPunchType,cast(@OutReader_Id as nvarchar(10)),
		 @Reason,@Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10))
		 ,cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1))) 
	   END
	ELSE IF(@OutDate = '' '')  
	  BEGIN
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,cast(@InReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),''N'',cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
	ELSE
	  BEGIN    
		INSERT INTO TA_Tbl_ManualTimeEntry(ManualTimeEntry_Employee_Id,ManualTimeEntry_Date,ManualTimeEntry_InDate,ManualTimeEntry_InTime,ManualTimeEntry_InPunchType,ManualTimeEntry_OutDate,ManualTimeEntry_OutTime,ManualTimeEntry_OutPunchType,ManualTimeEntry_InReaderID,ManualTimeEntry_OutReaderID,ManualTimeEntry_Reason,ManualTimeEntry_Status,Route_Id,Clk_Process,Isdeleted,[TimeStamp],Emp_Id,YearSettings_Id,IsOnDuty,IsImported)
		VALUES(@ManualEntry_EmployeeId,cast(@ManualEntry_Date as nvarchar(20)),@InDate,@InTime,@InPunchType,@OutDate,@OutTime,@OutPunchType,cast(@InReader_Id as nvarchar(10)),cast(@OutReader_Id as nvarchar(10)), 
		@Reason,@Status,cast(@RouteId as nvarchar(20)),''N'', cast(@Isdel as nvarchar(10)),cast(@TimeStamp as nvarchar(20)),cast(@UserId as nvarchar(10)),cast(@YearSettings_Id as nvarchar(10)),cast(@IsOnDuty as nvarchar(10)),cast(@IsImported as CHAR(1)))
	  END
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterDataLevelsParent]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMasterDataLevelsParent]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertMasterDataLevelsParent]
AS
BEGIN
insert into ta_tbl_leveldetails (levelid,parentid,name,description)
select distinct 1,0,level1,level1 from Ta_Tbl_ImportMasterData where 
level1 not in (select name from ta_tbl_leveldetails where isdeleted=0 and parentid=0)
and level1 <>''''
--Added by Manikandan.R
--On 05-02-2014 05.22PM
declare @groupId as bigint
set @groupId=(select GroupId from ta_tbl_usergroup where groupName=''SuperAdmin'')
insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) 
select @groupId,id,1 from Ta_Tbl_levelDetails where id not in(select levelId from TA_Tbl_LevelRights where @groupId=@groupId)
--select * from TA_Tbl_LevelRights order by GroupId,LevelId 
END
' 
END
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches_Test]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakInPunches_Test]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_BreakInPunches_Test]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], (CD.Clk_InDate + CD.Clk_InTime) [DateTime], CD.Clk_InPunchType [PunchType],ROW_NUMBER() OVER(PARTITION BY Clk_EmpId, CAST(Clk_Date AS DATETIME) ORDER BY (CD.Clk_InDate + CD.Clk_InTime) ASC) Id
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = ''N'') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE ''Break In'') AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + ''12:00 PM'') AND (CD.Clk_InDate + ''02:00 PM'') 
 AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + ''09:00 PM'') AND (CD.Clk_InDate + ''10:00 PM'')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, (CD.Clk_InDate + CD.Clk_InTime)
ORDER BY CD.Clk_EmpId, CD.Clk_Date
'
GO
/****** Object:  View [dbo].[TA_VW_BreakInPunches]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakInPunches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_BreakInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], CD.Clk_InPunchType [PunchType]
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = ''N'') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE ''Break In'') AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + ''12:00 PM'') AND (CD.Clk_InDate + ''02:00 PM'') 
 AND (CD.Clk_InDate + CD.Clk_InTime) NOT BETWEEN (CD.Clk_InDate + ''09:00 PM'') AND (CD.Clk_InDate + ''10:00 PM'')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_BreakInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakInPunches'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_BreakInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakInPunches'
GO
/****** Object:  View [dbo].[TA_VW_BreakFirstInPunches]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_BreakFirstInPunches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_BreakFirstInPunches]
AS
SELECT TOP (100) PERCENT ROW_NUMBER() OVER(ORDER BY [EmployeeCodeId]) Id, [EmployeeCodeId], [DeviceId], [Date], [DateTime], [PunchType] FROM (
	SELECT DISTINCT [EmployeeCodeId], [DeviceId], [Date], [DateTime], [PunchType] FROM 
		(SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], (CD.Clk_InDate + CD.Clk_InTime) [DateTime], CD.Clk_InPunchType [PunchType] FROM TA_Tbl_ClockDetails CD 
			RIGHT OUTER JOIN TA_Tbl_Terminal T ON T.Terminal_ReaderID = CD.Clk_InDeviceId
			RIGHT OUTER JOIN TA_Tbl_Entrance_INOUTDetails E ON E.Reader_Id = T.Terminal_Id
		WHERE (CD.Clk_Process = ''N'') AND CD.Clk_Date >= ''01-Jul-2014'' AND CD.Clk_InPunchType IN(''In'', ''Break In''))Tbl) Tbl2
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_BreakFirstInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakFirstInPunches'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_BreakFirstInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_BreakFirstInPunches'
GO
/****** Object:  StoredProcedure [dbo].[TA_Tbl_checkHolidayLeaveApplication]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Tbl_checkHolidayLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- TA_Tbl_checkHolidayLeaveApplication ''2011-07-28'',''2011-07-28''
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[TA_Tbl_checkHolidayLeaveApplication]
	@Fromdate datetime,
	@ToDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	select COUNT(*) as HolidayCount from TA_Tbl_Holiday where (Holiday_FromDate >= @Fromdate and Holiday_FromDate <= @ToDate) and (Holiday_ToDate >=@Fromdate and 
	Holiday_ToDate <= @ToDate) and Holiday_Type=''G''
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_GetParentChild]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_GetParentChild]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'-- =============================================
--	Author	   :	<Author,,Name>
--	Create date:	<Create Date,,>
--	Description:	<Description,,>
--	Modified by:	Manikandan.R
--	Modified on:	31-May-2019 11:19
-- =============================================
--select * from dbo.[fn_TA_GetParentChild](''superadmin'',4)order by ParentChildId
CREATE FUNCTION [dbo].[fn_TA_GetParentChild] 
(
	-- Add the parameters for the function here
	@UserGroupName varchar(max), 
	@parent_id int
)
RETURNS @TA_Tbl_ReturnParentChild TABLE (ParentChildId int null)
AS
BEGIN
	declare @UserGroupId as int
	select @UserGroupId=GroupId from TA_Tbl_UserGroup where groupName=@UserGroupName and IsDeleted=0 	
	if(@parent_id<>0)
		BEGIN
				--declare @TA_Tbl_ParentChild TABLE 
				--(
				--	-- Add the column definitions for the TABLE variable here
				--ID int identity(1,1) NOT NULL,
				--ParentChildId int null,
				--tier_cnt int NULL,
				--lineage_id varchar(50)
				--)
				--/* declare our tier cnt integer, and set it to two
				-- (for the number of tiers existing in the temp tabel for our Nth level loop */
				--Declare @tier as int
				--SET @tier = 2
				--/* Let''s build the root level This inserts the root level into the temp table */
				--INSERT INTO @TA_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)
				--VALUES(@parent_id,1,''1'')
				--/*
				--Now we must go get for first batch of children (if there are any)
				--*/
				----INSERT INTO @TA_Tbl_ParentChild
				----Select child_id,2,''1'' from tb_tree where parent_id = @parent_id
				--INSERT INTO @TA_Tbl_ParentChild
				--Select id,2,''1'' from ta_tbl_leveldetails where parentid = @parent_id
				--/*
				--Now comes the magic- believe it or not. We need to stamp our newly added children with their genetic code, so to speak. Each line item is given a map back to its the top level parent via the lineage_id
				--*/
				--UPDATE @TA_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt
				--/*Now the table is initalized and ready for the Nth level iterations. So we start a while loop using the SQL Server''s @@rowcount (i''m not sure what this variable is called in other platforms but I''m sure a rows affected variable should be available) . We also have our @tier int set to 2 (we''ve added two other tiers already, so that''s the current tier).*/
				--WHILE @@rowcount > 0
				--BEGIN
				--SET @tier = @tier+1
				--/*Go get children nodes for the next tier that are not already accounted for */
				----INSERT INTO @TA_Tbl_ParentChildTemp (ParentChildId)
				----select ParentChildId from @TA_Tbl_ParentChild
				--INSERT INTO @TA_Tbl_ParentChild (ParentChildId,tier_cnt,lineage_id)
				--SELECT id, @tier,(select lineage_id from @TA_Tbl_ParentChild where ParentChildId = parentid)
				--FROM ta_tbl_leveldetails
				----inner join @TA_Tbl_ParentChildTemp PC on PC.ParentChildId in (ta_tbl_leveldetails.parentid)
				----and PC.ParentChildId NOT in (ta_tbl_leveldetails.id)
				--WHERE parentid IN (select ParentChildId from @TA_Tbl_ParentChild)
				--AND id NOT in (select ParentChildId from @TA_Tbl_ParentChild)
				----delete from @TA_Tbl_ParentChildTemp
				--/* Now stamp the lineage ID with last numeral, the ID field asigned to the new nodes */
				--UPDATE @TA_Tbl_ParentChild set lineage_id = lineage_id+LTRIM(STR(ID)) WHERE len(lineage_id) < tier_cnt
				--END
				--insert into @TA_Tbl_ReturnParentChild
				--select PC.ParentChildId from @TA_Tbl_ParentChild PC
				--inner join TA_Tbl_LevelRights LR on PC.ParentChildId=LR.LevelId
				--where LR.GroupId=@UserGroupId
				----select * from @TA_Tbl_ReturnParentChild
				--/* The loop end once no more related children can be found. So, with all the children added we need only select the temp table ordered by the lineage_id for teh SP''s result*/
				----select ParentChildId from @TA_Tbl_ParentChild 
				----order by ParentChildId
			;WITH ChildLevelDetails as
			(
				SELECT LR.LevelId as selectedParent_Child FROM TA_Tbl_LevelRights LR
				INNER JOIN Ta_Tbl_levelDetails LD on LR.LevelId=LD.id
				WHERE GroupId=@UserGroupId and LD.isDeleted=0 and LD.id=@parent_id
				UNION ALL
				SELECT LR.LevelId from TA_Tbl_LevelRights LR
				INNER JOIN Ta_Tbl_levelDetails LD on LR.LevelId=LD.id
				INNER JOIN ChildLevelDetails CL ON CL.selectedParent_Child = ld.parentId
				WHERE GroupId=@UserGroupId and LD.isDeleted=0
			)
			INSERT INTO @TA_Tbl_ReturnParentChild
			SELECT selectedParent_Child FROM ChildLevelDetails order by selectedParent_Child
		END
		ELSE
		BEGIN
			INSERT INTO @TA_Tbl_ReturnParentChild
			SELECT LevelId FROM TA_Tbl_LevelRights WHERE GroupId=@UserGroupId
		END
		RETURN 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPermission]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Modified by	:	Prabakaran.P
-- Modified on	:	06-Feb-10
-- Proc_TA_InsertPermission 5,''26/Mar/2019'',''1'',''26/Mar/2019 09:00'',''26/Mar/2019 09:30'',''26/Mar/2019'',1,3,''Approved'','''',null
CREATE  PROCEDURE [dbo].[Proc_TA_InsertPermission]
(
	@EmployeeID int,
	@Permission_Date datetime,
	@PermissionType nvarchar(50),
	@Permission_FromTime datetime,
	@Permission_EndTime datetime,
	@Reason nvarchar(1000),
	@auEmpId nvarchar(50),
	@YearSettings_Id nvarchar(20),
	@strPermissionStatus nvarchar(20),
	@CCMail varchar(3000),
	@Permission_Hours varchar(5)
)
as
BEGIN
	SET NOCOUNT ON;
	declare @UnPlanned as int
	set @UnPlanned=0
	if @EmployeeID<>@auEmpID
	Begin
	set @UnPlanned=1
	end	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
		[EffectiveDate] ASC
		) ON [PRIMARY]
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
		[LevelId] ASC
		) ON [PRIMARY]
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
		[EmployeeId] ASC
		)ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Permission_Date as nvarchar(50)), 102) and EL.LevelId is not null
	declare @sql nvarchar(MAX)
	declare @Isdeleted bit
	declare @del bit
	set @del=0
	set @Isdeleted=0
	set @sql=''''
	declare @CountRecord as int
	set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID and Isdeleted=0)
	if(@strPermissionStatus='''' and @CountRecord>0)
		BEGIN
			set @strPermissionStatus=''Forwarded''
		END
	else if (@strPermissionStatus='''' and @CountRecord=0)
		BEGIN
			set @strPermissionStatus=''Pending''
		END
	begin
	--Arabic content is not inserting properly into database, uncomment the below coding and comment the static coding.
	--set @sql=''INSERT INTO TA_Tbl_Permission
	--(Employee_Id,Permission_Date,Permission_Type,Permission_FromTime,Permission_ToTime,Permission_Reason,Permission_Status,IsDeleted,Emp_Id,YearSettings_Id, UnPlanned, CCMail,Permission_Hours,No_Of_Hours) 
	--VALUES('''''' + cast(@EmployeeID as nvarchar(25)) + '''''', ''''''+ cast(@Permission_Date as nvarchar(100)) + '''''',N'''''' + @PermissionType + '''''','''''' + cast(@Permission_FromTime as nvarchar(100)) + '''''','''''' + cast(@Permission_EndTime as nvarchar(100)) + '''''',N'''''' + @Reason + '''''',N'''''' + @strPermissionStatus + '''''','''''' + cast(@Isdeleted as nvarchar(5)) + '''''',N'''''' + @auEmpId + '''''',N'''''' + @YearSettings_Id + '''''', '' + cast(@UnPlanned as nvarchar(25)) + '','''''' + @CCMail + '''''','''''' + @Permission_Hours + '''''','''''' + @Permission_Hours + '''''')''
	--Exec(@sql)
	
	INSERT INTO TA_Tbl_Permission
	(Employee_Id,Permission_Date,Permission_Type,Permission_FromTime,Permission_ToTime,Permission_Reason,Permission_Status,IsDeleted,Emp_Id,YearSettings_Id, UnPlanned, CCMail,Permission_Hours,No_Of_Hours) 
	VALUES(cast(@EmployeeID as nvarchar(25)),cast(@Permission_Date as nvarchar(100)),@PermissionType,
	cast(@Permission_FromTime as nvarchar(100)),cast(@Permission_EndTime as nvarchar(100)),@Reason ,@strPermissionStatus,cast(@Isdeleted as nvarchar(5)),@auEmpId ,@YearSettings_Id ,cast(@UnPlanned as nvarchar(25)),@CCMail,@Permission_Hours ,@Permission_Hours)
	
	SELECT P.Permission_Id,LD.Id AS LevelId,P.UnPlanned,Permission_Status as ''Status'' FROM TA_Tbl_Permission P
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = P.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
	INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
	WHERE P.Permission_Id = (SELECT @@IDENTITY AS Permission_Id)
	end
	drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[temp_UpdatePerShiftAllocation]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[temp_UpdatePerShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[temp_UpdatePerShiftAllocation] 
(@EmpId int,@year int,@month int,@Day1Shift int,@Day2Shift int,@Day3Shift int,@Day4Shift int,@Day5Shift int,@Day6Shift int,@Day7Shift int,@Day8Shift int,@Day9Shift int,@Day10Shift int,@Day11Shift int,@Day12Shift int,@Day13Shift int,@Day14Shift int,@Day15Shift int,@Day16Shift int,@Day17Shift int,@Day18Shift int,@Day19Shift int,@Day20Shift int,@Day21Shift int,@Day22Shift int,@Day23Shift int,@Day24Shift int,@Day25Shift int,@Day26Shift int,@Day27Shift int,@Day28Shift int,@Day29Shift int,@Day30Shift int,@Day31Shift int)
AS
	BEGIN 
		UPDATE TA_Tbl_PermanentShiftAllocation SET Day1Shift=@Day1Shift,Day2Shift=@Day2Shift,Day3Shift=@Day3Shift,Day4Shift=@Day4Shift,Day5Shift=@Day5Shift,Day6Shift=@Day6Shift,Day7Shift=@Day7Shift,Day8Shift=@Day8Shift,Day9Shift=@Day9Shift,Day10Shift=@Day10Shift,Day11Shift=@Day11Shift,Day12Shift=@Day12Shift,Day13Shift=@Day13Shift,Day14Shift=@Day14Shift,Day15Shift=@Day15Shift,Day16Shift=@Day16Shift,Day17Shift=@Day17Shift,Day18Shift=@Day18Shift,Day19Shift=@Day19Shift,Day20Shift=@Day20Shift,Day21Shift=@Day21Shift,Day22Shift=@Day22Shift,Day23Shift=@Day23Shift,Day24Shift=@Day24Shift,Day25Shift=@Day25Shift,Day26Shift=@Day26Shift,Day27Shift=@Day27Shift,Day28Shift=@Day28Shift,Day29Shift=@Day29Shift,Day30Shift=@Day30Shift,Day31Shift=@Day31Shift WHERE [Year]=@year and [Month]=@month and  EmployeeId=@EmpId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created On		:	09-Oct-2013
Descriptions	:	Adding procedure for checking addtional weekly off grouping restore
Proc_TA_CheckAdditionalWeeklyOffGroupCount ''32,33''
*/
CREATE proc [dbo].[Proc_TA_CheckAdditionalWeeklyOffGroupCount]
(
@AddionalWeekId nvarchar(2000)
)
as
begin
	select count(AL.LevelId) as count,AD.Addl_WeekOff_Day,AD.Addl_WeekOff_Week,IsDeleted from TA_Tbl_Additional_WeeklyOff AD
	inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=AD.Addl_WeeklyOff_Id
	where AD.Addl_WeeklyOff_Id in (select Value from dbo.Split(@AddionalWeekId,'',''))
	group by AL.LevelId,AD.Addl_WeekOff_Day,AD.Addl_WeekOff_Week,AD.IsDeleted
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeePunchMonitor]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_EmployeePunchMonitor]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Thilakraj Chinaaraj>
-- Create date: <26-Feb-2016>
-- Description:	<For Sample Web services>
/*
Exec [TA_Proc_EmployeePunchMonitor] ''789''
*/
-- =============================================
CREATE PROCEDURE [dbo].[TA_Proc_EmployeePunchMonitor]
(	
@EmployeeCodeID  int=null,
	@date  date =null
)
AS
BEGIN
	if (@EmployeeCodeID is null)
	Begin
		Set @EmployeeCodeID=973;
	End
	if (@date is null)
	Begin
		Set @date=GETDATE();
	End
		--Set @EmployeeCodeID=789;
	--Insert into Ta_tbl_EmployeePunch  
	--Select RD.CLK_CARDID as ''Employee ID'',RD.CLK_DATE as ''Date'' ,RD.CLK_TIME as ''Time''
	--from TA_Tbl_Clk_RawData RD
	--Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	--Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	--Where RD.CLK_CARDID=@EmployeeCodeID and RD.CLK_DATE=@date and(Rd.CLK_FLAG=0 or CLK_PROCESS=0)
	--order by CLK_ID 
	SELECT RD.CLK_ID,RD.CLK_CARDID as ''Employee ID'',RD.CLK_DATE as ''Date'' ,RD.CLK_TIME as ''Time'' ,T.Terminal_Name,PT.PunchType
	from TA_Tbl_Clk_RawData RD
	Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	inner Join Ta_tbl_EmployeePunch EP on RD.CLK_CARDID=EP.EmployeeId
	Where RD.CLK_CARDID=@EmployeeCodeID and RD.CLK_DATE=@date and(Rd.CLK_FLAG=0 or CLK_PROCESS=0) 
	order by CLK_ID 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[select_EmpLeavePolicyDetails_EDR]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[select_EmpLeavePolicyDetails_EDR]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <11-May-2019 05.56 PM>
-- Description:	<After release We created this procedure>
-- select_EmpLeavePolicyDetails_EDR 3,''04/01/2019''
-- =============================================
CREATE PROCEDURE [dbo].[select_EmpLeavePolicyDetails_EDR]
(
	@PolicyID int,
	@fromDat varchar(20)
)
AS
BEGIN
	Declare @Diff int
	set @Diff=11-DATEPART(month,CONVERT(datetime,@fromDat))
	if(@Diff<=0)
	begin
		set @Diff=1
	end
	select LP.Policy_Id,PolicyName,LT.LeaveType_Id,LeaveType,
	Permonth=
	CASE	WHEN SUBSTRING(CONVERT(VARCHAR(10),MaxDays_applicable/12.0),CHARINDEX(''.'',MaxDays_applicable/12.0)+1,LEN(MaxDays_applicable/12.0))%5!=0 then 
				CASE	WHEN DATEPART(MONTH,CONVERT(DATETIME,@fromdat)) In(11) then CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*4 
						WHEN DATEPART(MONTH,CONVERT(DATETIME,@fromdat)) In(12) then CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*2
						ELSE CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,0))*@Diff+4 
				END
			ELSE CONVERT(decimal(18,2),round(MaxDays_applicable/12.0,2)*(13-DATEPART(month,CONVERT(datetime,@fromDat))))
	END,
	MaxDays_applicable from TA_Tbl_LeavePolicyDetails LP 
	INNER JOIN TA_Tbl_LeaveType LT ON LT.LeaveType_Id=LP.LeaveType_Id 
	INNER JOIN TA_Tbl_LeavePolicy L ON L.Policy_Id=LP.Policy_Id where LP.policy_id=@PolicyID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[ReminderMailForLeavePolicyUpdationToHR]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReminderMailForLeavePolicyUpdationToHR]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <11-07-2019>
-- Description:	<Send reminder mail to HR for Leave policy updation>
-- =============================================
CREATE PROCEDURE [dbo].[ReminderMailForLeavePolicyUpdationToHR]
AS
BEGIN
	SET NOCOUNT ON;
	Declare @TriggerDate datetime
	Declare @StartDate datetime
	Declare @EndDate datetime
	set @TriggerDate=DATEADD(d,24,DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0))
	--select @TriggerDate
	if(@TriggerDate=CONVERT(varchar(11),GETDATE()))
	begin
		if not exists(select id from ta_tbl_remainder where convert(varchar(11),TimeStamp)=CONVERT(varchar(11),GETDATE()) and Type=''LPR'')
		begin
			set @StartDate=DATEADD(d,-14,@TriggerDate)
			set @EndDate=DATEADD(d,-15,DATEADD(m,1,@TriggerDate))
			Declare @yearsettingID int
			select @yearsettingID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
			Create table #TempLeavePolicy
			(
				Employee_Code_Id	varchar(20),
				Employee_FirstName	varchar(20),
				DateOfJoining		datetime,
				[Current Policy]	varchar(20),
				[Total Year Experience]	varchar(20),
				[Total Days] int,
				ExperienceAdded		datetime,
				Row					varchar(20),
				LeavePolicy_Id		varchar(20),
				IsAlreadyUpdated	bit default(0)
			)
			Create table #TempLeavePolicy1
			(
				Employee_Code_Id	varchar(20),
				Employee_FirstName	varchar(20),
				DateOfJoining		datetime,
				[Current Policy]	varchar(20),
				[Total Year Experience]	varchar(20),
				[Total Days] int,
				ExperienceAdded		datetime,
				Row					varchar(20),
				LeavePolicy_Id		varchar(20),
				IsAlreadyUpdated	bit default(0)
			)
			--select @StartDate,@EndDate
			Insert into #TempLeavePolicy
			select 
					--@StartDate,
					--@EndDate,
					Employee_Code_Id,Employee_FirstName,DateOfJoining,PolicyName as [Current Policy],
					[Total Year Experience]=DATEDIFF(d,DateOfJoining,GETDATE())/365,[Total Days]=DATEDIFF(D,DateOfJoining,GETDATE()),
					ExperienceAdded=DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining),  
					Row=ROW_NUMBER()over(partition by employee_code_id order by Employee_Code_Id),
					ELP.LeavePolicy_Id,0
					from TA_Tbl_Employee E
			inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
			inner join TA_Tbl_LeavePolicy LP on ELP.LeavePolicy_Id=LP.Policy_Id
			where Employee_Status=1 and isnull(InActiveDate,'''')=''''
			and (DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining)>=@StartDate
			and DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining)<=@EndDate)
			and ELP.YearSettingId=@yearsettingID and ELP.LeavePolicy_Id not in(76,72)
			and DATEDIFF(d,DateOfJoining,GETDATE())>180
			update #TempLeavePolicy set IsAlreadyUpdated=1 where Employee_Code_Id in(select Employee_Code_Id from #TempLeavePolicy TLP where Row>1)
			
			--Below 1.5 yrs category
			Insert into #TempLeavePolicy1
			select 
				--@StartDate,
				--@EndDate,
				Employee_Code_Id,Employee_FirstName,DateOfJoining,PolicyName as [Current Policy],
				[Total Year Experience]=DATEDIFF(d,DateOfJoining,GETDATE())/365,[Total Days]=DATEDIFF(D,DateOfJoining,GETDATE()),
				ExperienceAdded=DATEADD(year,DATEDIFF(YEAR,DateOfJoining,@TriggerDate),DateOfJoining),  
				ROW_NUMBER()over(partition by employee_code_id order by Employee_Code_Id),
				ELP.LeavePolicy_Id,0
				from TA_Tbl_Employee E
				inner join TA_Tbl_Emp_LeavePolicy ELP on E.Employee_Id=ELP.EmployeeId
				inner join TA_Tbl_LeavePolicy LP on ELP.LeavePolicy_Id=LP.Policy_Id
				where Employee_Status=1 and isnull(InActiveDate,'''')=''''
				and ELP.YearSettingId=@yearsettingID and ELP.LeavePolicy_Id in(72)
				and DATEDIFF(d,DateOfJoining,GETDATE())>180
				
			update #TempLeavePolicy1 set IsAlreadyUpdated=1 where Employee_Code_Id in(select Employee_Code_Id from #TempLeavePolicy TLP where Row>1)
			
			select	Employee_Code_Id,
					Employee_FirstName,
					DateOfJoining=replace(CONVERT(varchar(11),DateOfJoining,113),'' '',''-''),
					[Current Policy],			
					TotalYearExperience=convert(varchar(20),[Total Days]/365)+ '' Yrs '' + convert(varchar(20),([Total Days]%365)/12) +'' months ''+convert(varchar(20),([Total Days]%365)%12) +'' day(s)''
			from #TempLeavePolicy where IsAlreadyUpdated=0
			--union all
			--select	787,
			--		''Manikandan'',
			--		DateOfJoining=replace(CONVERT(varchar(11),''2011-03-21'',113),'' '',''-''),
			--		''5 year above'',			
			--		TotalYearExperience=''8 Yrs ''
			
			
			--below 1.5 category always fetch
			select Employee_Code_Id,
					Employee_FirstName,
					DateOfJoining=replace(CONVERT(varchar(11),DateOfJoining,113),'' '',''-''),
					[Current Policy],			
					TotalYearExperience=convert(varchar(20),[Total Days]/365)+ '' Yrs '' + convert(varchar(20),([Total Days]%365)/12) +'' months ''+convert(varchar(20),([Total Days]%365)%12) +'' day(s)''
			from #TempLeavePolicy1 where IsAlreadyUpdated=0
			
			select EmailId as EmailId from TA_Tbl_Employee where Employee_Code_Id=''6003''
			
			drop table #TempLeavePolicy
			drop table #TempLeavePolicy1
		end
	end
	--else
	--begin
	--	select ''Not Triggering date''
	--end
END' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[fn_TA_CountNumberOfWorkingDays]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_TA_CountNumberOfWorkingDays]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================    
-- Author:  <Author,,Name>    
-- Create date: <Create Date,,>    
-- Description: <Description,,>    
-- fn_TA_CountNumberOfWorkingDays 44    
-- =============================================    
CREATE function [dbo].[fn_TA_CountNumberOfWorkingDays]    
(
--@MonthClosureID int
@FromDate   nvarchar(20),    
@ToDate   nvarchar(20)    
)  
  RETURNS int   
AS    
BEGIN    
 declare @days as int    
-- declare @FromDate as nvarchar(20)    
-- declare @ToDate as nvarchar(20)    
-- Count number of days in a month    
 --select @FromDate = MonthClosure_StartDate ,@ToDate= MonthClosure_EndDate, @days=datediff(d,MonthClosure_StartDate,MonthClosure_EndDate)+1    
 --from ta_tbl_monthclosure where monthClosure_id=@MonthClosureID    
--End of count number of days in a month    
set @days=datediff(d,@FromDate,@ToDate)+1  
  declare @Mon as int    
  declare @year as int    
  declare @IsHoliday as int    
  set @IsHoliday=0      
  declare @CurDate as nvarchar(25)    
  Declare @Count as int    
  set @Count = 0    
  declare @StartDay as int    
  set @StartDay=1    
  declare @TotHoliday as int    
  set @TotHoliday = 0    
  declare @iFlag as int    
  set @iFlag = 0    
  while @startDay<=@days    
  Begin    
-- 1 = sunday      
   if (datepart(dw,dateadd(d,@iFlag,@FromDate))=1)    
   Begin    
    set @count = @count + 1    
   End     
   set @StartDay= @StartDay + 1    
   set @iFlag= @iFlag+1    
  End    
 Declare @Holiday as int    
 set @Holiday = (select isnull(sum (datediff(day,holiday_fromDate,dateadd(day,1,holiday_toDate))),0)  from ta_tbl_holiday where holiday_type=''G''  and     
  (((@FromDate between holiday_fromDate and holiday_toDate)or    
  @ToDate between holiday_fromDate and holiday_toDate))     
  or (holiday_fromDate between @FromDate and @ToDate or (holiday_toDate between @FromDate and @ToDate))    
  )    
 --select @days - @count - @Holiday  as TotWorkingDays    
 return  @days - @count - @Holiday  
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[EmpReProcess]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmpReProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[EmpReProcess] 
as
declare @Process_Rec_ID varchar(20)
declare @Employee_Code varchar(20)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare emp_ReProcess cursor for 
select  Process_Rec_ID,Employee_Code_Id,Date,Shift_Id,NormOT,OffOT,HolOT  from dbo.TA_Tbl_ProcessedData WHERE
      Attendance=''Present'' and InTime is not null and OutTime is not null order by Process_Rec_ID
open emp_ReProcess
fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@NormOT,@OffOT,@HolOT
while (@@fetch_status = 0 )
begin
 set @OTtype=''N''
if @HolOT<>''00:00''
begin 
 set @OTtype=''H''
end
if @OffOT<>''00:00''
begin 
 set @OTtype=''O''
end
set @eCount=(select  count(Clk_EmpId ) from TA_Tbl_ClockDetails WHERE
       Clk_EmpId = @Employee_Code AND Clk_InTime IS NOT NULL AND Clk_OutTime IS NOT NULL  AND Clk_InDate =@Emp_Date )
if @eCount>0
begin
		exec ReProcess_EmpLogs  @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@OTtype
		select @val=''T''
 end
  fetch emp_ReProcess into @Process_Rec_ID, @Employee_Code,@Emp_Date,@Shift_Id,@NormOT,@OffOT,@HolOT
end   
deallocate emp_ReProcess' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AllocateWeekOff_AutoShift]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AllocateWeekOff_AutoShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AllocateWeekOff_AutoShift]
AS
BEGIN
	SET NOCOUNT ON;
	Declare @StartDate datetime
	Declare @EndDate datetime
	Declare @AddYear int
	Declare @WeeklyOff1 varchar(20)
	Declare @WeeklyOff2 varchar(20)
	Declare @WeeklyOff3 varchar(20)

	---Default Values
	set @AddYear=10
	set @WeeklyOff1=''Sunday''
	set @WeeklyOff2=''Saturday''
	set @WeeklyOff3=''''

	--set @StartDate=CONVERT(varchar(11),dateadd(month,-1,GETDATE()))
	--set @EndDate=DATEADD(YEAR,@AddYear,@StartDate)
	
	--select @StartDate,@EndDate
	set @StartDate=''20191215''
	set @EndDate=getdate();
	--select @StartDate,@EndDate
	
	Create table #TempWeekOffDays(weekoffid int identity(1,1),start datetime,weekdayName varchar(20),MonthValue int,yearValue int,datevalue int)
	;with cte
	as
	(
		select DATEADD(d,0,@startdate) as start,datename(dw,DATEADD(d,0,@startdate)) as weekday
		union all
		select DATEADD(d,1,start),datename(WEEKDAY,DATEADD(d,1,start)) as weekday from cte where @EndDate>=DATEADD(d,1,start) 
	)
	Insert into #TempWeekOffDays
	select start,Weekday,MonthValue=DATEPART(month,start),yearValue=DATEPART(year,start),DATEPART(d,start) from cte where weekday in(@WeeklyOff1,@WeeklyOff2,@WeeklyOff3)
	and start is not null
	option(maxrecursion 0);
	--select * from #TempWeekOffDays

	Declare @TotalDaysCount int
	Declare @Startloop int
	set @Startloop=1
	select @TotalDaysCount=COUNT(weekoffid) from #TempWeekOffDays
	
	Create table #TempEmployee(id int identity(1,1),EmpAutoID int)
	Insert into #TempEmployee
	select Employee_Id from ta_tbl_employee

	while @TotalDaysCount>=@Startloop
	begin
		Declare @Dynamic_InsertQuery varchar(max)
		Declare @insertMonth varchar(10)
		Declare @insertYear varchar(10)
		Declare @insertDate varchar(10)
		Select @insertMonth=MonthValue,@insertYear=yearValue,@insertDate=datevalue from #TempWeekOffDays where weekoffid=@Startloop
		--select @insertMonth,@insertYear,@insertDate
		Declare @EmployeeCount int
		Declare @startEmpLoop int
		set @startEmpLoop=1
		select @EmployeeCount=count(*) from #TempEmployee
		while @EmployeeCount>=@startEmpLoop
		begin
			Declare @EmpAutoID varchar(20)
			set @EmpAutoID=''''
			select @EmpAutoID=EmpAutoID from #TempEmployee where id=@startEmpLoop
			if not exists(select * from TA_Tbl_PermanentShiftAllocation where EmployeeId=@EmpAutoID and Month=@insertMonth and year=@insertYear)
			BEGIN
				--print ''s''
				insert into TA_Tbl_PermanentShiftAllocation (employeeid,year,Month,Emp_Id,DateShift) values(@EmpAutoID,@insertYear,@insertMonth,1,convert(varchar(20),@insertYear)+''-''+CONVERT(varchar(20),@insertMonth)+''-01'')

				set @Dynamic_InsertQuery = '' UPDATE TA_TBL_PERMANENTSHIFTALLOCATION SET DAY''
				set @Dynamic_InsertQuery = @Dynamic_InsertQuery + @insertDate +''shift=-1 where EmployeeId=''+@EmpAutoID +'' and Month=''+@insertMonth +'' and Year=''+@insertYear
				Execute(@Dynamic_InsertQuery)
			END
			else
			begin
				set @Dynamic_InsertQuery = '' UPDATE TA_TBL_PERMANENTSHIFTALLOCATION SET DAY''
				set @Dynamic_InsertQuery = @Dynamic_InsertQuery + @insertDate +''shift=-1 where EmployeeId=''+@EmpAutoID +'' and Month=''+@insertMonth +'' and Year=''+@insertYear
				Execute(@Dynamic_InsertQuery)
			end
			set @startEmpLoop=@startEmpLoop+1
		end		
		set @Startloop=@Startloop+1
	end
	--select * from #TempWeekOffDays
	drop table #TempWeekOffDays
END
' 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTLeaveApplication]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_EmployeeOTLeaveApplication 182
Description		:	Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	
Modified On		:	
*/
CREATE    PROCEDURE [dbo].[Proc_TA_EmployeeOTLeaveApplication] 
@EmployeeId varchar(50)
AS
Declare @FromDate as datetime
Declare @ToDate as datetime
Declare @CompOffDays as bigint
Declare @NumberOfDays as bigint
Declare @OtMinHrs as nvarchar(20)
Declare @OtHrs as bigint
Declare @OtMin as bigint
Declare @OtMinProcessedData as bigint
Declare @TotalOtMin as bigint
Declare @Employee_code_Id as nvarchar(50)
BEGIN
	SET NOCOUNT ON; 
	set @Employee_code_Id=(select SwipeCardNo from TA_Tbl_Employee where Employee_Id=@EmployeeId and IsDeleted=0)
	set @FromDate=(select FromDate from TA_Tbl_YearSetting where IsActive=1)
	set @ToDate=(select ToDate from TA_Tbl_YearSetting where IsActive=1)
	set @OtMinHrs=(select isnull(OtMinHrs,''00:00'') as OtMinHrs from TA_Tbl_LeavePolicy lp
	inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lp.Policy_Id
	where elp.EmployeeId=@EmployeeId 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
	set @OtHrs=(select left(@OtMinHrs,2))
	set @OtMin=(select right(@OtMinHrs,2))
	set @TotalOtMin=(@OtHrs*60) + @OtMin
	set @OtMinProcessedData=(select sum(OtMins) from TA_Tbl_ProcessedData
	WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id=@Employee_code_Id AND OvertimeStatus=''Approved'')
	set @NumberOfDays=(select sum(isnull(NumberOfDays,0)) as NumberOfDays from TA_tbl_LeaveApplication 
	WHERE ((Leave_FromDate BETWEEN  @FromDate AND @ToDate) AND (Leave_ToDate BETWEEN  @FromDate AND @ToDate))
	AND Employee_Id=@EmployeeId and Type=''Comp Off'' and Status NOT IN (''Rejected'') and IsDeleted=0)
	if(@NumberOfDays is null or @NumberOfDays='''')
		BEGIN
		set @NumberOfDays=0
		END
	IF(@TotalOtMin > 0)
		BEGIN
			set @TotalOtMin=@TotalOtMin * @NumberOfDays
		END
	ELSE
		BEGIN
			set @TotalOtMin=0
		END
	select @TotalOtMin as OTMinsLeaveApplication,@OtMinProcessedData as OTMinsProcessedData,@OtMinHrs as OtMinHrs
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTStatus]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_EmployeeOTStatus  
Description : To Update the OverTime Status in ta_tbl_processedData  table
Tables Included : ta_tbl_ProcessedData,ta_tbl_Employee  
Created By : Sasireka  
Created On : 09-Jan-2009  
Modified By :  
Modified On :  
*/  
--Proc_TA_EmployeeOTStatus ''100'',''Approved'',''2017-03-23'',''<DocumentElement><Table><Process_Rec_ID>20575</Process_Rec_ID><Employee_Id>2</Employee_Id><ActHrsOT>13:30</ActHrsOT><ActOffOT>13:30</ActOffOT><ActHolOT>13:30</ActHolOT><ActOtMins>810</ActOtMins><ExtraTime_Id>258</ExtraTime_Id></Table></DocumentElement>'',1
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeOTStatus]
(
@EmployeeCode nvarchar(20),
@Status varchar(20),
@OtDate datetime,
@xml xml,
@isRequest int
)
As
BEGIN 
		set nocount on
		Declare @Index int
		Set @Index = 0;
		EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		update ta_tbl_ProcessedData set ta_tbl_ProcessedData.OverTimeStatus=@Status
		from OpenXML(@Index, ''/DocumentElement/Table'')
		--With (Process_Rec_ID Bigint ''Process_Rec_ID'',SelectedRecords int ''SelectedRecords'')) OT ON OT.Process_Rec_ID=PD.Process_Rec_ID
		With (Process_Rec_ID Bigint ''Process_Rec_ID'') as OT 
		inner join ta_tbl_ProcessedData pd
		ON OT.Process_Rec_ID=PD.Process_Rec_ID
		--Where OT.SelectedRecords=1		 
		Exec sp_xml_removedocument @Index
		if(@isRequest=1)
			BEGIN
			EXEC sp_xml_preparedocument @Index OUTPUT, @xml
			--Update the OverTime Status
			update TA_Tbl_OverTimeStatus set TA_Tbl_OverTimeStatus.OverTimeStatus=@Status
			from OpenXML(@Index, ''/DocumentElement/Table'')
			With (ExtraTime_Id Bigint ''ExtraTime_Id'') as OT 
			inner join TA_Tbl_OverTimeStatus OTT
			ON OT.ExtraTime_Id=OTT.ExtraTime_Id
			Exec sp_xml_removedocument @Index
			--Create the Temp table for the OverTime Status
			CREATE table #TblRecords (ID int identity(1,1),Process_RecID BIGINT, Employee_Id INT, ExtraMins INT, OverTimeStatus VARCHAR(50),ExtraTime_Id int)
			DECLARE @Index1 INT 
			set @Index1= 0
			EXEC sp_xml_preparedocument @Index1 OUTPUT, @Xml
			--Insert the temp table value
			insert into #TblRecords select Process_Rec_ID,Employee_Id,ActOtMins,@Status,ExtraTime_Id
			FROM OPENXML(@Index1, ''/DocumentElement/Table'')	WITH(
			Process_Rec_ID BIGINT ''Process_Rec_ID'',
			Employee_Id INT ''Employee_Id'',
			ActHrsOT varchar(50) ''ActHrsOT'',
			ActOtMins VARCHAR(5) ''ActOtMins'',
			ExtraTime_Id INT ''ExtraTime_Id''
		   ) AS OT 	
			--select * from #TblRecords
			DECLARE @FromDate DATETIME, @ToDate DATETIME, @MaxDate DATETIME, @DateFormt DATETIME
			DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT
			DECLARE @Employee_code_Id NVARCHAR(50), @OtText VARCHAR(MAX)
			DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT
			DECLARE @ValidDates INT
			declare @EmployeeId bigint
			DECLARE @ExtraOT_ID INT
			Declare @i int=1
			Declare @j int
			select @j=COUNT(*) from #TblRecords
			while(@i<=@j)
				BEGIN
					select @EmployeeId=Employee_Id,@ExtraOT_ID=ExtraTime_Id from #TblRecords where ID=@i
					SELECT @TypeOfOT = OtHourWise,@HalfDayOTMins = DATEDIFF(MI,''00:00'', ISNULL(OtMinHrs, ''00:00'')),@FullDayOTMins = DATEDIFF(MI,''00:00'',ISNULL(FullDayOTMinHrs, ''00:00'')),@ValidDates = ISNULL(LP.CompOffValidDays, 60) FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id WHERE ELP.EmployeeId = @EmployeeId AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeId ORDER BY ELP.ToDate DESC)
					--If the leave policy is Day wise then calculate the overtime hours in day wise
					IF(@TypeOfOT=1)
						BEGIN
							SELECT @SumOfOTMins = (@SumOfOTMins + ExtraMins),@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),@OtText = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @OtText ELSE (@OtText + '';'' + CAST(Process_RecID AS VARCHAR(50)) + ''&'' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),@MaxDate = NULL FROM TA_Tbl_OverTimeStatus WHERE Employee_Id = @EmployeeId AND OvertimeStatus=''Approved'' and ExtraTime_Id=@ExtraOT_ID
							update TA_Tbl_OverTimeStatus set 
							NoOfDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							RemainingDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),T.[Date]) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END)  FROM TA_Tbl_OverTimeStatus T  where T.ExtraTime_Id=@ExtraOT_ID
						END
					--If the leave policy is hours wise then calculate the overtime hours
					ELSE
						BEGIn
							update TA_Tbl_OverTimeStatus set 
							NoOfDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							RemainingDays=(CASE WHEN T.ExtraMins >= @FullDayOTMins THEN 1.0 WHEN T.ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),
							CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),T.[Date]) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END)  FROM TA_Tbl_OverTimeStatus T  where T.ExtraTime_Id=@ExtraOT_ID
						END
				set @i=@i+1
				END
				drop table #TblRecords
	  END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Pro_TA_ViewProjectbyProjectId]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Pro_TA_ViewProjectbyProjectId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<View screen binding values procedure for Project>
-- =============================================
CREATE PROCEDURE [dbo].[Pro_TA_ViewProjectbyProjectId]
@ProjectId bigint, 
@userId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

IF EXISTS(select * from TA_Tbl_Project where project_Id = @ProjectId)
	Begin
		select isnull(Project_Name,'''') as Project_Name,
		isnull(Project_Code,'''') as Project_Code,
		isnull(Client_Name,'''') as Client_Name,
		isnull(Project_Description,'''') as Project_Description, 
		Project_StartTime,
		Project_EndTime,
		isnull(Project_Status,'''') as Project_Status,
		LevelID,Mandays,ManHours,
		case when LevelID is not null and LevelID<>0 then (Select name from Ta_Tbl_levelDetails l where l.id=TA_Tbl_Project.LevelID) else '''' end as LevelName
		from TA_Tbl_Project
		where project_Id = @ProjectId
	End

IF EXISTS(select ProjectID from TA_tbl_ProjectTaskList where ProjectID = @ProjectId)
	Begin
		Select TaskID,TaskName,TaskHours as Hours from TA_tbl_ProjectTaskList where ProjectID = @ProjectId
	End


END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePunchTypes]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeletePunchTypes]
@Type CHAR(1),
@PunchType_Id INT,
@PunchType_Ids NVARCHAR(50)
AS
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_PunchTypes SET IsDeleted = @DEL WHERE PunchType_Id = @PunchType_Id
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_PunchTypes SET IsDeleted='' + @DEL + '' WHERE PunchType_Id IN  ('' + @PunchType_Ids + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePermissionApplication]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePermissionApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_DeletePermissionApplication
Description		:	Update Permisssion Details of Employees Based on their Permission_Id
					IsDeleted Flag Set to 1 - For Deleted Item
Tables Included	:	TA_Tbl_Permission
Created By		:	Prabakaran
Created On		:	20-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_DeletePermissionApplication]
	@Permission_Id bigint,
	@auEmpId int
as
begin
	set nocount on;
	delete from TA_Tbl_PermissionConversation where PermissionId=@Permission_Id
	delete from TA_Tbl_Permission where Permission_Id=@Permission_Id
	--if the employee applied permission for second time in a month and deleted the first permission entry,
	--the first permission entry details need not to be loaded into gridview control of modify page.
	if exists(select Prev_Perm_ID from ta_tbl_PrevPermissionDetails_EastMan where Prev_Perm_ID=@Permission_Id)
	begin
		Delete from ta_tbl_PrevPermissionDetails_EastMan where Prev_Perm_ID=@Permission_Id
	end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteOndutyEntry]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteOndutyEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : Proc_TA_DeleteOndutyEntry
Description : Update Manual Time Entry and  Details of Employees Based on their onduty_ID
IsDeleted Flag Set to 1 - For Deleted Item
Tables Included : TA_Tbl_ManualTimeEntry,TA_Tbl_OndutyEntry
Created By : Karthikeyan.R
Created On : 15-Mar-2016
Description : To Added new status called as DELETED for the deleted entry.For V1.4 Release
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteOndutyEntry]
@Onduty_Id BIGINT,
@auEmpId BIGINT
AS
BEGIN
	SET NOCOUNT ON;
	--UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = 1,Emp_Id=@auEmpId,ManualTimeEntry_Status=''Deleted'' WHERE OnDuty_ID=@Onduty_Id
	delete from TA_Tbl_ManualTimeEntry WHERE OnDuty_ID=@Onduty_Id
	--update TA_Tbl_OndutyEntry set Isdeleted=1,Emp_Id=@auEmpId,Onduty_Status=''Deleted'' where Onduty_ID=@Onduty_Id
	delete from TA_Tbl_OndutyEntry WHERE OnDuty_ID=@Onduty_Id
	declare @FromDate as nvarchar(30)
	declare @ToDate as nvarchar(30)
	declare @EmployeeCode as nvarchar(30)
	set @FromDate=(select Onduty_FromDate from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	set @ToDate=(select Onduty_ToDate from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	set @EmployeeCode=(select Onduty_EmployeeID from TA_Tbl_OndutyEntry where Onduty_ID=@Onduty_Id)
	exec Proc_TA_ReprocessEmpData @FromDate,@ToDate,@EmployeeCode
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteSpouseDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteSpouseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteSpouseDetails]
		@EmployeeId INT
	AS
	BEGIN
		DELETE FROM  TA_Tbl_EmpChildrenDetails  WHERE Emp_ID=@EmployeeId AND Spouse_Child=''S''
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteScheduleEmailIdsBeforeUpdating]
(
	@ScheduleId int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    delete from TA_tbl_MailIdsForTriggeringEmail where ScheduleId = @ScheduleId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delLevels]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_delLevels]  
(  
 @levID varchar(10),  
 @opr varchar(1)   
)  
as  
begin  
 if @opr=''C''  
  Begin  
   declare @checkFlag  int  
   set @checkFlag = 0  
   declare @recCount as int  
   set @recCount = (select count(*) from ta_tbl_leveldetails where levelId=@levID and isdeleted=0)  
   if (@recCount>0)  
    Begin  
     set @checkFlag=1  
    End  
   set @recCount = (select count(*) from ta_tbl_level where parentLevelId=@levID and isdeleted=0)  
   if (@recCount>0)  
    Begin  
     set @checkFlag=1  
    End     
  select @checkFlag as checkFlag  
  end  
 else  
  Begin  
	declare @Query varchar(2000)
	set @Query = ''''
    set @Query = @Query + ''update ta_tbl_level set isdeleted=1 where levelid in ( '' + cast(@levID as varchar(10)) + '')''
    exec (@Query)
  End   
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectCompany]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CMITechSelectCompany]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <22-Jan-2020>
-- Description:	<CMITech Select Company dropdown in grid>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CMITechSelectCompany] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @LastLevel int
	Declare @LastLevelcount int
	Declare @LastLevelBefore int
	
	 set @LastLevel = (select MAX(levelID) from ta_tbl_level where isDeleted = 0)
	 set @LastLevelcount = (select count(*) from Ta_Tbl_levelDetails where levelId = @LastLevel)	 
	 if(@LastLevelcount = 0)
	 Begin	
		create table #LevelTemp (LevelId int)
		insert into #LevelTemp select top 2 levelID from ta_tbl_level  where isDeleted = 0 order by levelid desc;
		set @LastLevelBefore = (select top 1 levelID from #LevelTemp order by levelid asc)
		Select isnull(id,0) as id, isnull(name,'''') as name 
		from Ta_Tbl_levelDetails where levelId = @LastLevelBefore
		order by id asc	
	 End
	 Else
	 Begin
		Select isnull(id,0) as id, isnull(name,'''') as name 
		from Ta_Tbl_levelDetails where levelId = @LastLevel
		order by id asc	
	 End
	 
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeeSpouseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeeSpouseDetails]
		@EmployeeId INT
	AS
	DECLARE @DEL BIT
	SET @DEL=0
	BEGIN
		UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child=''S''
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteManualTimeEntry]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteManualTimeEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : Proc_TA_DeleteManualTimeEntry
Description : Update Manual Time Entry Details of Employees Based on their ManualTimeEntry_Id
IsDeleted Flag Set to 1 - For Deleted Item
Tables Included : TA_Tbl_ManualTimeEntry
Created By : Kumuthini.L
Created On : 08-Jan-09
Modified By : K.Gopinath
Modified On : 10 Feb 2014
Description : To Added new status called as DELETED for the deleted entry.For V1.4 Release
*/
CREATE PROCEDURE [dbo].[Proc_TA_DeleteManualTimeEntry]
@ManualTimeEntry_Id BIGINT,
@auEmpId BIGINT
AS
begin
	set nocount on
	declare @FromDate nvarchar(50)
	declare @ToDate nvarchar(50)
	declare @EmpoyeeCode nvarchar(15)
	set @FromDate=(select ManualTimeEntry_InDate from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	set @ToDate=(select ManualTimeEntry_OutDate from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	set @EmpoyeeCode=(select ManualTimeEntry_Employee_Id from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Id=@ManualTimeEntry_Id)
	UPDATE TA_Tbl_ManualTimeEntry SET IsDeleted = 1,Emp_Id=@auEmpId,ManualTimeEntry_Status=''Deleted'' WHERE ManualTimeEntry_Id=@ManualTimeEntry_Id
	exec Proc_TA_ReprocessEmpData @FromDate,@ToDate,@EmpoyeeCode
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGlobalHoliday]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountGlobalHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CountGlobalHoliday  
Description : counting global holiday
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CountGlobalHoliday]  
AS  
BEGIN
	select SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1) as ''Days'' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type=''G'' and h.Isdeleted=0  and ys.IsActive=1
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeavePolicyDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeavePolicyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- Create date: 28 June 2007
-- Description:	Leave Policy - Delete
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteLeavePolicyDetails]
	@LeavePolicyID INT
AS
BEGIN
	SET NOCOUNT ON;
	DELETE FROM TA_Tbl_LeavePolicyDetails WHERE Policy_Id=@LeavePolicyID 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountYearlyHoliday]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountYearlyHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CountYearlyHoliday  
Description : counting total yearly holiday 
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CountYearlyHoliday]  
AS
BEGIN  
	select SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1) as ''Days'' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type=''Y'' and h.Isdeleted=0  and ys.IsActive=1
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteImportErrorData]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteImportErrorData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_DeleteImportErrorData]
	-- Add the parameters for the stored procedure here
	@id as nvarchar(Max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	delete from TA_Tbl_ImportMasterError where id in (SELECT * FROM [dbo].[SplitupEmployeeCode] (@id))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekOff]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckRestoreWeekoff 
Description : check weekoff before restore, is already there or not  
Tables Included : TA_Tbl_Additional_WeeklyOff
Created By : Christopher S  
Created On : 8-Feb-2008  
Modified By		:	Manjula.P	
Modified On		:	05-Oct-2013
Descriptions	:	Checking Restore option with already inserted levels of additional weekly off Mantis : 0019292 
Proc_TA_CheckRestoreWeekOff 21,'''','''',''R'' 
*/  
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreWeekOff]
(        
  @weekOffId INT,     
  @weekDay nVarchar(15) ,
  @weekOffWeek nvarchar(15),
  @Type varchar(2)
)         
As        
  BEGIN        
   if(@Type = ''V'')
	   BEGIN   
		   SELECT COUNT(Addl_WeeklyOff_Id) AS WeekOffCount FROM TA_Tbl_Additional_WeeklyOff       
		   WHERE  Addl_WeekOff_Day=@weekDay AND Addl_WeekOff_Week=@weekOffWeek AND Addl_WeeklyOff_Id <> @weekOffId 
		   AND IsDeleted = 0
	   END
   else 
       BEGIN
		   declare @Day nvarchar(15)
		   declare @Week nvarchar(15)
		   --select @Day = Addl_WeekOff_Day,@Week = @weekOffWeek  from TA_Tbl_Additional_WeeklyOff
		   --where Addl_WeeklyOff_Id = @weekOffId
		   --Added by Manjula.P on 05-Oct-2013 
		   declare @Levels nvarchar(2000);
		   select @Day = Addl_WeekOff_Day,@Week = Addl_WeekOff_Week,@Levels = isnull(@Levels,0)+'',''+cast((AWL.LevelId)as varchar)  from TA_Tbl_Additional_WeeklyOff AW
		   inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
		   where AW.Addl_WeeklyOff_Id = @weekOffId
           SELECT COUNT(AW.Addl_WeeklyOff_Id) AS WeekOffCount FROM TA_Tbl_Additional_WeeklyOff  AW
           inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id     
		   WHERE  Addl_WeekOff_Day=@Day AND Addl_WeekOff_Week=@Week AND Aw.Addl_WeeklyOff_Id <> @weekOffId 
		   AND IsDeleted = 0 and AWL.LevelId in (select Value from  dbo.Split (@Levels,'',''))
		   --(@Levels)
		   --End *********************************
       END	   
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreWeekday]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreWeekday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	31-Dec-2013
Descriptions	:	Adding levelid and shiftid condition because changed the fucntionality with multiple closing time with single date
Proc_TA_CheckRestoreWeekday 5
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRestoreWeekday]
(        
  @weekDayId INT         
)         
As        
  BEGIN 
   declare @weekFromDate as NVARCHAR(30)
   declare @weekToDate as NVARCHAR(30)
   --Added by Manjula.P on 31-Dec-2013
   declare @ShiftId as nvarchar(max);
   create table #LevelId ( LevelId int)
   insert into #LevelId 
   select LevelId from Ta_Tbl_Temporary_WeeklyOff_Levels where TempWeekday_Id=@weekDayId
   create table #ShiftId(ShiftId nvarchar(max) )
   --********************************
   select @weekFromDate = TempWeekday_FromDate,@weekToDate = TempWeekday_ToDate,@ShiftId=ShiftId from ta_tbl_Temweekday 
   where TempWeekday_Id = @weekDayId   
   --Added by Manjula.P on 31-Dec-2013
   insert into #ShiftId
   select value from Split((Select * from (select @ShiftId as ShiftId) A), '','')    
   SELECT COUNT(*) AS WeekDateCount FROM TA_Tbl_TemWeekday  TW
   --Added by Manjula.P on 31-Dec-2013
   inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWL.TempWeekday_Id=TW.TempWeekday_Id
   inner join #LevelId on #LevelId. LevelId=TWL.LevelId
   inner join #ShiftId on #ShiftId.ShiftId in (select Value from dbo.Split(TW.ShiftId,'',''))
   WHERE TempWeekday_FromDate=convert(datetime,@WeekFromdate,103) and TempWeekday_ToDate=convert(datetime,@weekTodate,103) AND TW.TempWeekday_Id <> @weekDayId AND IsDeleted = 0
   --Added by Manjula.P on 31-Dec-2013
   drop table #LevelId
   drop table #ShiftId
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestorePunchTypes]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestorePunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckRestorePunchTypes
Description : check Punch type before insert, is already there or not  
Tables Included : TA_Tbl_LeaveType
Created By : Kumuthini.L  
Created On : 6-Feb-2008  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestorePunchTypes]
(        
	@PunchTypeId INT  
)         
As
BEGIN
	SET NOCOUNT ON
	Declare @TerminalId INT
	Declare @PunchType nVarchar(50)      
	Select @TerminalId=Terminal_id,@PunchType=PunchType from TA_Tbl_PunchTypes where PunchType_Id=@PunchTypeId 
	SELECT COUNT(PunchType_Id) AS [RestoreCount] FROM TA_Tbl_PunchTypes       
	WHERE Terminal_Id = @TerminalId AND PunchType = @PunchType AND PunchType_Id <> @PunchTypeId AND IsDeleted = 0         
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Delete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypes_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckPunchTypes_Delete  
Description : Save year settings details into table  
Tables Included : TA_Tbl_PunchTypes, TA_Tbl_ManualTimeEntry  
Created By : Arun vinoth.T  
Created On : 31-Oct-2007   
Modified By :  R.Manikandan
Modified On :  23-11-2016
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Delete]
(
   @PunchTypeId INT
)
AS
BEGIN 	
	SELECT COUNT(M.ManualTimeEntry_Id) as PunchTypesMappingCount FROM TA_Tbl_PunchTypes P,TA_Tbl_ManualTimeEntry M WHERE P.PunchType_Id = @PunchTypeId AND ((P.Terminal_Id = M.ManualTimeEntry_InReaderID AND 
	P.PunchType = M.ManualTimeEntry_InPunchType) OR (P.Terminal_Id = M.ManualTimeEntry_OutReaderID AND P.PunchType = M.ManualTimeEntry_OutPunchType))
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypes_Available]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypes_Available]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <28-May-2019 03:02 PM>
-- Description:	<Verifying particular punch types is exists or not of web clock in and out>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypes_Available]
AS
BEGIN
	SET NOCOUNT ON;
	SELECT ShiftIn=COUNT(''Shift In''),
	ShiftOut=COUNT(''Shift Out''),
	LunchOut=COUNT(''Lunch Out''),
	LunchIn=COUNT(''Lunch In''),
	BreakOut=COUNT(''Break Out''),
	BreakIn=COUNT(''Break In''),
	PunchType
	from TA_Tbl_PunchTypes	where Isdeleted=0 group by PunchType
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_CheckPunchTypeForDiscrepancy] 787,''Shift In''
CREATE PROCEDURE [dbo].[Proc_TA_CheckPunchTypeForDiscrepancy]
(
	@TerminalId varchar(50),
	@punchType varchar(50)
)
AS  
BEGIN 
	SET NOCOUNT ON;
	declare @Status varchar(max)
	set @Status=''''
	Declare @Terminal_Id int
	declare @Type varchar(10)
	declare @EntranceId int
	Declare @count int
	declare @Readerid varchar(max)
	declare @i int
	set @i=1
	set @Readerid=''''
	select @Terminal_Id=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@TerminalId and IsDeleted=0
	if((select COUNT(*)from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id)=1)
		begin	 
			select @Type=Type,@EntranceId=Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id
			Create table #Temp(id int identity(1,1),Readerid int)
			if(@Type=''In'')
				begin
					select @count=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type=''Out''
					insert into #Temp select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type=''Out''
					while @i<=@count
						begin
							if @Readerid=''''
								begin
									set @Readerid=(select Readerid from #Temp where id=@i)
								end
							else
								begin
									set @Readerid=@Readerid+'',''+(select Readerid from #Temp where id=@i)
								end
							set @i=@i+1
						end
				end
			else
				begin
					select  @count=COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type=''In''
					insert into #Temp select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Entrance_Id=@EntranceId and Type=''In''
					while @i<=@count
						begin
							if @Readerid=''''
								begin
									set @Readerid=(select Readerid from #Temp where id=@i)
								end
							else
								begin
									set @Readerid=@Readerid+'',''+(select Readerid from #Temp where id=@i)
								end
							set @i=@i+1
						end
				end
		end
	else
		begin			
			SELECT @Readerid=COALESCE(convert(varchar(max),@Readerid)+'','','''')+CONVERT(varchar(20),Reader_Id) FROM TA_Tbl_Entrance_INOUTDetails 
			where Entrance_Id=(SELECT top 1 Entrance_Id FROM TA_Tbl_Entrance_INOUTDetails where Reader_Id=@Terminal_Id)
			select @Readerid=right(@Readerid,LEN(@readerid)-1)			
		end
	
	if(@TerminalId=''787'')
	begin
		if(@punchType=''Shift In'')
		begin
			select ''Shift Out'' as status
		end
		if(@punchType=''Shift Out'')
		begin
			select ''Shift In'' as status
		end
	end
	if(@TerminalId=''788'')
	begin
		if(@punchType=''Shift In'')
		begin
			select ''Shift Out'' as status
		end
		if(@punchType=''Shift Out'')
		begin
			select ''Shift In'' as status
		end
	end
		
	if(@TerminalId!=''787'' and @TerminalId!=''788'')
	begin
		if(@punchType=''In'')
			begin
			   exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Out'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')
			end
		else if(@punchType=''Break In'')
			begin
			   exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Break Out'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')
			end 
		else if(@punchType=''Shift In'')
			begin
				exec(''(select PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Shift Out'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')
			end
		else if(@punchType=''Out'')
			begin
				exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''In'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')
			end
		else if(@punchType=''Shift Out'')
			begin
				exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Shift In'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')			
			end
		else if(@punchType=''Break Out'')
			begin
				exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Break In'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')			
			end
		else if(@punchType=''Lunch Out'')
			begin		   
			   exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Lunch In'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')			
			end
		else if(@punchType=''Lunch In'')
			begin
			   exec(''(select distinct PunchType as status from TA_tbl_PunchTypes where PunchType in(''''Lunch Out'''') and Isdeleted=0 and Terminal_Id in(''+ @Readerid+''))'')			
			end
		else	
			begin
				select @Status as status
			end
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRestoreLeavePolicy]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRestoreLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckRestoreLeaveType
Description : check leave policy before restoring, is already there or not  
Tables Included : TA_Tbl_LeavePolicy
Created By : Kumuthini.L  
Created On : 6-Feb-2008  
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Proc_TA_CheckRestoreLeavePolicy]
(        
  @LeavePolicyId INT        
)         
As        
BEGIN        
	SET NOCOUNT ON;
	Declare @PolicyName nVarchar(200)   
	Declare @LeaveTypeIsDeleted int
	Declare @Count int
	Declare @Count1 int
	Select @PolicyName= PolicyName FROM TA_Tbl_LeavePolicy WHERE Policy_Id = @LeavePolicyId
	select @Count=COUNT(IsDeleted) from TA_Tbl_LeaveType where LeaveType_Id in(select LeaveType_Id from TA_Tbl_LeavePolicyDetails where Policy_Id=@LeavePolicyId) 
	and IsDeleted<>0
	SELECT @Count1=COUNT(Policy_Id)  FROM TA_Tbl_LeavePolicy WHERE PolicyName = @PolicyName AND Policy_Id <> @LeavePolicyId AND IsDeleted = 0
	select @count as [Count],@Count1 AS [Count1]
 END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftAllocation]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : [Proc_TA_CheckShiftAllocation]  
Description : check shift allocation 
Tables Included : TA_Tbl_PermanentShiftAllocation  
Created By : Prabakaran  
Created On : 30-Jul-07  
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftAllocation] 
(
   @EmpId Int,
   @Year Int,
   @Month Int
)
 AS
BEGIN
               SELECT EmployeeId  FROM TA_Tbl_PermanentShiftAllocation WHERE EmployeeId = @EmpId AND [Year] = @Year AND [Month] = @Month
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE   PROCEDURE [dbo].[Proc_TA_CheckTempWeekDayHoliday_Insert]
(
	@weekDayId int,
	@WeekFromdate NVARCHAR(15)='''',
	@weekTodate NVARCHAR(15)='''',
	@Type varchar(2),
	@levelid varchar(max) =null
)
AS
BEGIN
	if(@Type = ''I'')
		BEGIN
			SELECT COUNT(Holiday_Id) AS WeekDateHolidayCount FROM TA_Tbl_Holiday 
			WHERE (( Holiday_FromDate>=@WeekFromdate and Holiday_ToDate<=@WeekFromdate)
			or (Holiday_FromDate>=@weekTodate  and Holiday_ToDate<=@weekTodate)) and Holiday_Type=''G'' and IsDeleted = 0
			and (levelid in (select value from dbo.split(@levelid,'','')) or levelid=0)			
		END
	ELSE
		BEGIN
			declare @FromDate as NVARCHAR(30)
			declare @ToDate as NVARCHAR(30)
			select @FromDate = TempWeekday_FromDate,@ToDate = TempWeekday_ToDate from ta_tbl_Temweekday 
			where TempWeekday_Id = @weekDayId 
			SELECT COUNT(Holiday_Id) AS WeekDateHolidayCount FROM TA_Tbl_Holiday 
			WHERE (( Holiday_FromDate>=@WeekFromdate and Holiday_ToDate<=@WeekFromdate)
			or (Holiday_FromDate>=@weekTodate  and Holiday_ToDate<=@weekTodate)) and Holiday_Type=''G'' and IsDeleted = 0			
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTempWeekDay_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTempWeekDay_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	19-Dec-2013
Descriptions	:	Adding this param to allowing multiple entries for single date because of various shift
-- Proc_TA_CheckTempWeekDay_Insert ''2013/01/30'',''2013/01/30'',''<DocumentElement>  <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>3</LevelId> </Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels> <LevelId>4</LevelId> </Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>5</LevelId></Ta_Tbl_Temporary_WeeklyOff_Levels> <Ta_Tbl_Temporary_WeeklyOff_Levels><LevelId>24</LevelId></Ta_Tbl_Temporary_WeeklyOff_Levels></DocumentElement>'',''10:00 AM'',''2,3''
*/
CREATE  PROCEDURE [dbo].[Proc_TA_CheckTempWeekDay_Insert]
(
	@WeekFromdate NVARCHAR(15)='''',
	@WeekTodate NVARCHAR(15)='''',
	@XMLdata xml,
	--Adding this param to allowing multiple entries for single date because of various shift by Manjula.P on 19-Dec-2013
	@ClosingTime nvarchar(15),
	--Adding ShiftId param to check if already exist.
	@ShiftId nvarchar(max)
)
AS
BEGIN
	DECLARE @Index int
	set @Index = 0 		   
	create table #GiveShiftId(GivenShiftId nvarchar(max))
	declare @ParamShiftId nvarchar(max);
	set @ParamShiftId=(@ShiftId);
	insert into #GiveShiftId
	select value from  Split(@ParamShiftId,'','') 
	--select * from #GiveShiftId
	EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
	--Added below line for creatinf temp table for getting shiftId for the temp weekday by MAnjula.P on 28-Dec-2013
	create table #temp(tempShiftId nvarchar(max))
	declare @TableShiftId nvarchar(max);
	create table #TableActualShiftId(Id int identity(1,1) not null,ShiftId nvarchar(max))
	insert into #TableActualShiftId
	SELECT distinct TWD.ShiftId FROM TA_Tbl_TemWeekday TWD
	inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWD.TempWeekday_Id = TWL.TempWeekday_Id
	inner join #GiveShiftId on #GiveShiftId.GivenShiftId in ( select value from dbo.Split(TWD.ShiftId,'','')) 
	--inner join (select xm.LevelId from OPENXML(@Index, ''/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels'')with (LevelId int ''LevelId'') as xm) as A on  A.LevelId = TWL.LevelId	
	WHERE ((TWD.TempWeekday_FromDate between @WeekFromdate and @WeekTodate)or(TWD.TempWeekday_ToDate between @WeekFromdate and @WeekTodate)
	or (@WeekFromdate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate) 
	or (@WeekTodate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate))
	and IsDeleted = 0 
	and #GiveShiftId.GivenShiftId in (select Value from dbo.Split (@ShiftId,'',''))
	--and  twl.LevelId in (select GivenShiftId from #GiveShiftId )	
	--and ClosingTime=@ClosingTime	
	group by TWD.ShiftId 
	DECLARE @MaxCount INTEGER
	DECLARE @Count INTEGER
	DECLARE @Txt VARCHAR(MAX)
	SET @Count = 1
	SET @Txt = ''''
	SET @MaxCount = (select COUNT(Id) from #TableActualShiftId)
	WHILE @Count<=@MaxCount
    BEGIN
    IF @Txt!=''''
        SET @Txt=@Txt+'','' + (SELECT ShiftId FROM #TableActualShiftId WHERE Id=@Count)
    ELSE
        SET @Txt=(SELECT ShiftId FROM #TableActualShiftId WHERE Id=@Count)
    SET @Count=@Count+1
    END
	set @TableShiftId=(SELECT @Txt AS Txt)
	insert into #temp
	select value from Split((Select * from (select @TableShiftId as ShiftId) A), '','') 
	--select * from #temp	
	--*************************************************************************************************************
	SELECT COUNT(*) AS WeekDateCount FROM TA_Tbl_TemWeekday TWD inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWD.TempWeekday_Id = TWL.TempWeekday_Id
	inner join (select xm.LevelId from OPENXML(@Index, ''/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels'')with (LevelId int ''LevelId'') as xm) as A on  A.LevelId = TWL.LevelId
	inner join #temp on #temp.tempShiftId in (select value from dbo.Split(TWD.ShiftId,'',''))
	WHERE ((TWD.TempWeekday_FromDate between @WeekFromdate and @WeekTodate)or(TWD.TempWeekday_ToDate between @WeekFromdate and @WeekTodate)
	or (@WeekFromdate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate) 
	or (@WeekTodate between TWD.TempWeekday_FromDate and TWD.TempWeekday_ToDate))
	and IsDeleted = 0 
	--and ClosingTime=@ClosingTime 
	and #temp.tempShiftId in (select Value from dbo.Split (@ShiftId,'',''))
	drop table #temp
	drop table #GiveShiftId
	drop table #TableActualShiftId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Child_Levels_Insert]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Child_Levels_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Child_Levels_Insert] 
(
	@opr nvarchar(1),
	@levelId int,
	@levelName nvarchar(100),
	@parentLevelId int,	
	@description nvarchar(255),
	@city nvarchar(100),
	@state nvarchar(100),
	@country nvarchar(100),
	@zip nvarchar(50),
	@phone1 nvarchar(50),
	@phone2 nvarchar(50),
	@fax1 nvarchar(50),
	@fax2 nvarchar(50),
	@email nvarchar(100),
	@web nvarchar(100),
	@id int,
	@logo image,
	@emp_id as nvarchar(25)
)
AS
Begin
	declare @sql as nvarchar(3000)  
	declare @groupId as bigint
	select @groupId=GroupId from ta_tbl_usergroup where groupName=''SuperAdmin''
	if (@opr=''I'')
		Begin
			insert into Ta_tbl_levelDetails (levelid,parentId,name,description,city,state,country,zip,phone1,phone2,fax1,fax2,email,webaddress,emp_id) 
			values (cast (@levelId as nvarchar(25)),
			cast(@parentLevelId as nvarchar(25)),
			@levelname,
			@description,
			@city,
			@state,
			@country,
			@zip,
			@phone1,
			@phone2,
			@fax1,
			@fax2,
			@email ,@web,@emp_id)			
			declare @nextId as int
			set @nextId = (select @@identity)
			update Ta_tbl_leveldetails set logo=@logo where id = @nextId
			--Inserts the Level wise rights
			--Below line commented by Manikandan.R on 14-July-2020 on 12:38 pM after relesing of iffco project
			--insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) values (@groupId,@nextId,@emp_Id)
			goto UpdateRights;
			--Added By manikandan.R
			--For Inserting the default values to reduce the unwanted redirection.
			--Added on 19-11-2013 03:57 PM
			--This option is not in the below version like 1.0,1.1,1.2,1.3.
			if(@parentLevelId=0)
				begin
				--Added last arguments as 0 for ODEntry in  TA_Tbl_ApprovalSettings column
					insert into TA_Tbl_ApprovalSettings values(@nextId,0,0,0,0,1,0,0,0,0,0)
					--select 1
				end	
		End
	Else
		Begin
			update ta_tbl_levelDetails set levelid=@levelId,parentId=@parentLevelId,name=@levelName,description=@description,city=@city,state=@state,country=@country,zip=@zip,phone1=@phone1,phone2=@phone2,fax1=@fax1,fax2=@fax2,email=@email,webaddress=@web,logo=@logo,emp_id=@emp_id where id=@id			
		End
		
	UpdateRights:
		--select 1
		Declare @TotalUsergroup int
			Declare @start int
			set @start=1
			Create table #Tempusergroup(Autoid int identity(1,1),groupID bigint)
			Insert into #Tempusergroup
			select groupId from TA_Tbl_Usergroup 
			select @TotalUsergroup= COUNT(*) from TA_Tbl_Usergroup 
			Declare @parentID bigint
			Declare @TotallevelCount int
			Declare @TotallevelRightsCount int
			select @TotallevelCount=count(*) from Ta_Tbl_levelDetails where parentId=@parentLevelId and id!=@nextId
			while @start<=@TotalUsergroup
			begin
				select @groupId=groupId  from #Tempusergroup where Autoid=@start				
				select @TotallevelRightsCount=count(*) from Ta_Tbl_levelDetails LD 
				left outer join TA_Tbl_LevelRights LR on LD.id=LR.LevelId
				where GroupId=@groupId and LD.parentId=@parentLevelId and isnull(LR.LevelId,0)!=0
				if(@TotallevelCount=@TotallevelRightsCount)
				begin					
					insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) values (@groupId,@nextId,@emp_Id)		
				end
				set @start=@start+1
			end
End
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectMatchingDevice]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_SelectMatchingDevice]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_SelectMatchingDevice]
(
	@ReaderID as varchar(25),  
	@Para as varchar(25)  
)
RETURNS varchar(50)
AS
BEGIN
	declare @OutDeviceID as varchar(50)
	declare @DeviceID as int  
	 set @DeviceID = (Select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@ReaderID)  
	 if @Para=''In''  
	 Begin  
	  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type=''Out''  
		set @OutDeviceID = ( Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type=''In'' ) 
	 End  
	 if @Para=''Out''  
	 Begin  
	  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type=''In''  
	  set @OutDeviceID = ( Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type=''Out''  )
	 End  
	return @OutDeviceID
END
' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[Func_TA_SelectInReaderId]    Script Date: 03/25/2021 10:22:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Func_TA_SelectInReaderId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[Func_TA_SelectInReaderId] 
(
	@SwipeCardNo as varchar(20),
	@InOrOut char(4)
)
RETURNS varchar(50)
AS
BEGIN
	declare @DeviceID as varchar(50)
    if(@inOrOut=''In'')
		begin
			set @DeviceID=(select Top 1 cd.Clk_InDeviceId from Ta_tbl_clockdetails cd 
			inner join TA_Tbl_Terminal ter on ter.Terminal_ReaderID=cd.Clk_InDeviceId
			where Clk_EmpId=@SwipeCardNo )
			if(@DeviceID='''' or @DeviceID is null)
				Begin
					select Top 1 @DeviceID=Terminal_Id from TA_Tbl_PunchTypes where PunchType=''In'' or PunchType=''Shift In'' or PunchType=''Break In'' or PunchType=''Lunch In'' or PunchType=''In Duty'' or PunchType=''Official In''
				End
		end
	else
		begin
			set @DeviceID=(select Top 1 cd.Clk_InDeviceId from Ta_tbl_clockdetails cd 
			inner join TA_Tbl_Terminal ter on ter.Terminal_ReaderID=cd.Clk_InDeviceId
			where Clk_EmpId=@SwipeCardNo)
			if(@DeviceID='''' or @DeviceID is null)
				Begin
					select Top 1 @DeviceID=Terminal_Id from TA_Tbl_PunchTypes where PunchType=''Out'' or PunchType=''Shift Out'' or PunchType=''Break Out'' or PunchType=''Lunch Out'' or PunchType=''Out Duty'' or PunchType=''Official Out''
				End	
		end	
	return @DeviceID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckBorrowExists]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckBorrowExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckBorrowExists 6,1
Description		:	Check Borrow Exists for Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
CREATE    PROCEDURE [dbo].[Proc_TA_CheckBorrowExists]
	@Employee_Id int,
	@LeaveType_Id int
AS
begin
	SET NOCOUNT ON;
	select lpd.Borrow_FromNextYear as Borrow from TA_TbL_LeavePolicyDetails lpd
	inner join TA_Tbl_Emp_LeavePolicy elp 
	on elp.LeavePolicy_Id=lpd.Policy_Id
	inner join TA_Tbl_YearSetting ys
	on ys.YearSettings_Id=elp.YearSettingId
	where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
	and ys.IsActive=1 and elp.Isdeleted=0 
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckAdditionalWeekOffForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <30-May-2019>
-- Description:	<Verifying current date is weekly off or not>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOffForService]
	@SwipeCardNo varchar(50),
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
	SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW 
	inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id 
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId 
	INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID 
	WHERE emp.SwipeCardNo = @SwipeCardNo AND AW.IsDeleted = 0  AND 		
	EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,@dtmDate, 102) order by EffectiveDate desc)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckAdditionalWeekOff]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckAdditionalWeekOff]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckAdditionalWeekOff]
	-- Add the parameters for the stored procedure here
	@dtmDate datetime,
	@SwipeCardNo varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW
    inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id
    INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId
    INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID
    WHERE emp.SwipeCardNo = @SwipeCardNo AND AW.IsDeleted = 0  AND
    EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND 
    EffectiveDate <=CONVERT(DATETIME,@dtmDate, 102) order by EffectiveDate desc)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCompoffEligibility]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCompoffEligibility]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <19-March-2012>
-- Description:	<Check the Working for Comp off Apply Eligibility>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCompoffEligibility]
	-- Add the parameters for the stored procedure here
	@Employee_Code_Id nvarchar(25),
	@date datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @SwipeCardNo varchar(10)
	Declare @EmployeeId int
	Declare @Day int
	Declare @Month int
	Declare @Year int
	select @SwipeCardNo=swipeCardNo from TA_Tbl_Employee where Employee_Code_Id=@Employee_Code_Id
	select @EmployeeId=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employee_Code_Id
	set @Day=DAY(@date)
	set @Month=MONTH(@date)
	set @Year=YEAR(@date)
    -- Insert statements for procedure here
    SELECT top 1 * FROM TA_Tbl_ProcessedData
    SELECT top 1 * FROM TA_Tbl_PermanentShiftAllocation
    SELECT top 1 * FROM TA_Tbl_TemporaryShiftAllocation
    select * from TA_Tbl_Shift
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_ImportOndutyEntry]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_ImportOndutyEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		<R.MANIKANDAN>
-- CREATE DATE: <06-APRIL-2019>
-- DESCRIPTION:	<IMPORT THE ONDUTY RECORDS INTO DATABASE>
-- 
/*
PROC_IMPORTONDUTYENTRY @ONDUTYDATA =''<DocumentElement>
  <Data>
    <Sl.No>6</Sl.No>
    <EmployeeId>1003</EmployeeId>
    <Date>01-Apr-2019</Date>
    <Reason />
    <flag>1</flag>
    <Errormessage />
    <recordNumber>1</recordNumber>
    <ShiftID>3</ShiftID>
    <Userid>1</Userid>
    <Status>Approved</Status>
  </Data>
</DocumentElement>''
-- =============================================
*/
--drop PROCEDURE [dbo].[Proc_ImportOndutyEntry]
CREATE PROCEDURE [dbo].[Proc_ImportOndutyEntry]
	@ONDUTYDATA XML = NULL
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @XMLPARAMS INT,@YEARSETTINGID INT
	DECLARE @ERRMSG VARCHAR(MAX), @ERRIDS VARCHAR(MAX)	
			EXEC SP_XML_PREPAREDOCUMENT @XMLPARAMS OUTPUT, @ONDUTYDATA
			CREATE TABLE  #TA_TBL_IMPORTONDUTYRECORDS(AUTOID INT IDENTITY(1,1),EMPLOYEE_ID VARCHAR(100), DATE VARCHAR(20),
			REASON VARCHAR(MAX),SHIFTID INT,userid bigint,Status varchar(10))
			INSERT INTO #TA_TBL_IMPORTONDUTYRECORDS
				SELECT TBL.EmployeeId,TBL.Date,case when (TBL.Reason IS null or TBL.Reason='''') then ''Onduty'' else TBL.Reason end,TBL.ShiftID,TBL.Userid,TBL.Status
				FROM OPENXML (@XMLPARAMS, ''/DocumentElement/Data'', 2) WITH 
				  (EmployeeId VARCHAR(50),Date VARCHAR(20),Reason VARCHAR(MAX),ShiftID INT,Userid bigint,Status varchar(10)) TBL
				INNER JOIN TA_TBL_EMPLOYEE E ON E.EMPLOYEE_CODE_ID = TBL.EMPLOYEEID
				AND E.ISDELETED = 0 AND E.EMPLOYEE_STATUS = 1
			DECLARE @START INT
			SET @START=1
			DECLARE @TOTALREC INT
			SELECT @TOTALREC =COUNT(*) FROM #TA_TBL_IMPORTONDUTYRECORDS 
			SELECT @YEARSETTINGID = [YEARSETTINGS_ID] FROM [TA_TBL_YEARSETTING] WHERE [ISACTIVE] = 1 
			--SELECT * FROM #TA_TBL_IMPORTONDUTYRECORDS
			WHILE @START<=@TOTALREC
			BEGIN
				---ONDUTY ENTRY TABLE
				BEGIN
				DECLARE @TYPE NVARCHAR(2)
				DECLARE @ONDUTY_ID INT
				DECLARE @ONDUTY_EMPLOYEEID NVARCHAR(20)
				DECLARE @ONDUTY_ENTRYDATE	DATETIME
				DECLARE @ONDUTY_TYPE INT
				DECLARE @INCLUDEWEEKOFF INT
				DECLARE @ONDUTY_FROMDATE DATETIME
				DECLARE @ONDUTY_FROMTIME NVARCHAR(50)
				DECLARE @ONDUTY_TODATE DATETIME
				DECLARE @ONDUTY_TOTIME NVARCHAR(50)
				DECLARE @ONDUTY_REASON NVARCHAR(MAX)
				DECLARE @ONDUTY_STATUS NVARCHAR(25)
				DECLARE @EMP_ID INT
				DECLARE @FROM_SESSION NVARCHAR(25)
				SET @FROM_SESSION =''''
				DECLARE @TO_SESSION NVARCHAR(25)
				SET @TO_SESSION =''''
				DECLARE @MAXONDUTYID BIGINT
				SELECT @MAXONDUTYID=MAX(ONDUTY_ID) FROM TA_TBL_ONDUTYENTRY
				END
				---MANUAL ENTRY TABLE
				BEGIN
				DECLARE @MANUALENTRY_EMPLOYEEID NVARCHAR(20)
				DECLARE @MANUALENTRY_DATE DATETIME
				DECLARE @INDATE NVARCHAR(15)
				DECLARE @INTIME NVARCHAR(20)
				DECLARE @INPUNCHTYPE NVARCHAR(25)
				DECLARE @OUTDATE NVARCHAR(15)
				DECLARE @OUTTIME NVARCHAR(20)
				DECLARE @OUTPUNCHTYPE NVARCHAR(25)
				DECLARE @INREADER_ID INT
				DECLARE @OUTREADER_ID INT
				DECLARE @REASON NVARCHAR(MAX)
				DECLARE @ROUTEID INT
				DECLARE @STATUS NVARCHAR(25)
				DECLARE @USERID INT
				--DECLARE @YEARSETTINGS_ID NVARCHAR(25)
				DECLARE @ISONDUTY INT
				DECLARE @SHIFTID NVARCHAR(25)
				DECLARE @SHIFTDATE NVARCHAR(15)
				DECLARE @ONDUTYID INT
				END
				--GET VALUE FROM TEMP TABLE
				BEGIN
					SELECT	@TYPE=''I'',
							@ONDUTY_TYPE=1,
							@MANUALENTRY_EMPLOYEEID=EMPLOYEE_ID,
							@INCLUDEWEEKOFF=0,
							@MANUALENTRY_DATE=CONVERT(VARCHAR(11),GETDATE()),
							@INDATE=DATE,
							@INPUNCHTYPE=''IN'',
							@OUTDATE=DATE,
							@OUTPUNCHTYPE=''OUT'',
							@REASON=REASON,
							@ROUTEID=0,
							@STATUS=Status,
							@USERID=userid,
							@ISONDUTY=1,
							@SHIFTID=SHIFTID,
							@SHIFTDATE=DATE,
							@ONDUTYID=0
					FROM #TA_TBL_IMPORTONDUTYRECORDS WHERE AUTOID=@START
				END
				--SHIFT START TIME AND END TIME
				BEGIN
					SELECT @INTIME=SHIFT_STARTTIME,@OUTTIME=SHIFT_ENDTIME FROM TA_TBL_SHIFT WHERE SHIFT_ID=@SHIFTID AND ISDELETED=0
				END
				--IN READER ID
				BEGIN
					SELECT @INREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID=''787''
				END
				--OUT READER ID
				BEGIN
					SELECT @OUTREADER_ID=TERMINAL_ID FROM TA_TBL_TERMINAL WHERE TERMINAL_READERID=''788''
				END
				--ASSIGN VALUES TO ONDUTY TABLE
				BEGIN
					SELECT @ONDUTY_ID=@ONDUTYID,@ONDUTY_EMPLOYEEID=@MANUALENTRY_EMPLOYEEID,@ONDUTY_ENTRYDATE=@MANUALENTRY_DATE,
					@ONDUTY_FROMDATE=@INDATE,@ONDUTY_FROMTIME=@INTIME,@ONDUTY_TODATE=@OUTDATE,@ONDUTY_TOTIME=@OUTTIME,
					@ONDUTY_REASON=@REASON,@ONDUTY_STATUS=@STATUS,@EMP_ID=@USERID
					--SELECT 
					--@TYPE,@ONDUTY_ID, @ONDUTY_EMPLOYEEID, @ONDUTY_ENTRYDATE, @ONDUTY_TYPE, @INCLUDEWEEKOFF,
					--@ONDUTY_FROMDATE,@ONDUTY_FROMTIME,@ONDUTY_TODATE,@ONDUTY_TOTIME,@ONDUTY_REASON,
					--@ONDUTY_STATUS,@EMP_ID,@FROM_SESSION, @TO_SESSION;					
				END
				--INSERT ONDUTY VALUES
				DECLARE	@RETURN_VALUE bigint
				BEGIN
					DECLARE @sql nvarchar(max)
					SET @sql = ''''
					SET @sql = @sql + ''INSERT INTO TA_Tbl_OndutyEntry (Onduty_EmployeeID,Onduty_EntryDate,Onduty_Type,IncludeWeekOff,Onduty_FromDate,Onduty_FromTime,Onduty_ToDate
					,Onduty_ToTime,Onduty_Reason,Onduty_Status,Isdeleted,TimeStamp,Emp_Id,From_Session,To_Session) 
					VALUES (N''''''+ @Onduty_EmployeeID +'''''',N'''''' + cast(@Onduty_EntryDate as nvarchar(20)) + '''''',N'''''' +CAST(@Onduty_Type as nvarchar(10)) +'''''',N'''''' +CAST(@IncludeweekOff as nvarchar(10)) +'''''',N'''''' + cast(@Onduty_FromDate as nvarchar(20) )+ '''''',N'''''' + CAST(@Onduty_FromTime as nvarchar(50))+ '''''',N'''''' + cast(@Onduty_ToDate as nvarchar(20)) + '''''',N'''''' + CAST(@Onduty_ToTime as nvarchar(50)) + '''''',N'''''' + CAST(@Onduty_Reason as nvarchar(max)) + '''''',N'''''' +CAST(@Onduty_Status as nvarchar(25)) + '''''',N'''''' + CAST(0 as nvarchar(2)) + '''''',getdate(),N'''''' + CAST(@Emp_Id as nvarchar(10)) +'''''',N'''''' + CAST(@From_Session as nvarchar(25)) +'''''',N'''''' + CAST(@To_Session as nvarchar(25)) +'''''')''
					EXEC (@sql)	
					select @RETURN_VALUE=MAX(Onduty_ID) from TA_Tbl_OndutyEntry				
					--select @RETURN_VALUE
					--INSERT INTO MANUAL ENTRY TABLE
					BEGIN
						IF (@RETURN_VALUE IS NOT NULL AND @RETURN_VALUE<>'''')
						BEGIN
							--SELECT ''ENTEREED''
							IF(@MAXONDUTYID!=@RETURN_VALUE)
							BEGIN
								--SELECT ''ENTEREED Main''
								EXEC [DBO].[PROC_TA_INSERTONDUTYENTRY] @MANUALENTRY_EMPLOYEEID,@MANUALENTRY_DATE,@INDATE,
								@INTIME,@INPUNCHTYPE,@OUTDATE,@OUTTIME,@OUTPUNCHTYPE,@INREADER_ID,@OUTREADER_ID,
								@REASON,@ROUTEID,@STATUS,@USERID,@YEARSETTINGID,@ISONDUTY,@SHIFTID,@SHIFTDATE,@RETURN_VALUE;
								Update TA_Tbl_ManualTimeEntry set IsImported=1 where OnDuty_ID=@RETURN_VALUE
							END
						END
					END
				END
				SET @START=@START+1
			END
			EXEC SP_XML_REMOVEDOCUMENT @XMLPARAMS
			DELETE FROM #TA_TBL_IMPORTONDUTYRECORDS
			SELECT ''MSG:SHIFTIMPORTSUCCESSFULLY'' [MESSAGE]
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		: Kumuthini
-- Created  Date        : 13-Jan-09   
-- Proc_TA_AddUpdateEmployeeBonusLeave 1,2,5,6
-- Description:	Add or Update Employee Bonus Leave Details
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_AddUpdateEmployeeBonusLeave]
(
	@YearSettingId int,	
	@EmployeeId int,
	@BonusLeaveQuota int = 0,
	@EmpId int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Count AS int
	SELECT @Count = COUNT(*) FROM TA_Tbl_EmployeeBonusLeave WHERE YearSettingId = @YearSettingId AND EmployeeId = @EmployeeId
	IF(@Count >= 1)
	BEGIN
		UPDATE TA_Tbl_EmployeeBonusLeave SET BonusLeaveQuota = @BonusLeaveQuota,EmpId = @EmpId WHERE YearSettingId = @YearSettingId AND EmployeeId = @EmployeeId
	END
	ELSE
	BEGIN
		INSERT INTO TA_Tbl_EmployeeBonusLeave(YearSettingId,EmployeeId,BonusLeaveQuota,EmpId) VALUES (@YearSettingId,@EmployeeId,@BonusLeaveQuota,@EmpId)
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingTerminalStatus]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingTerminalStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Terminal status using Terminal ID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingTerminalStatus]
	-- Add the parameters for the stored procedure here
	@Terminal_ReaderID int,
	@inClk_Type varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
    Declare @Status int
	Declare @PunchType varchar(50)
	select @Status=IsDeleted from TA_Tbl_Terminal T where T.Terminal_ReaderID = convert(varchar(20),@Terminal_ReaderID) and T.IsDeleted = 0
	select @PunchType=P.PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID = @Terminal_ReaderID and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
	select isnull(@Status,1) as Status,@PunchType as PunchType
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingTemporaryWeekdayForService]	
	@blnIsPMAM int,
	@dtmActualShiftStartTime datetime,
	@dtmShiftEndTime datetime,
	@levelId int,
	@Is24Hrs int
AS
BEGIN	
		SET NOCOUNT ON;    
		if (@blnIsPMAM=1)
		begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T
			inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate between @dtmActualShiftStartTime and @dtmShiftEndTime)
			AND T.IsDeleted = 0 AND TL.LevelId=@levelId AND @dtmActualShiftStartTime Between  T.TempWeekday_FromDate And T.TempWeekday_ToDate
		end
		else if (@Is24Hrs=1)
        begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T
            inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate = @dtmActualShiftStartTime)
            AND T.IsDeleted = 0 AND TL.LevelId=@levelId
		end
		else
        begin
			SELECT T.ClosingTime,T.ShiftId FROM TA_Tbl_TemWeekday T 
			inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id = TL.TempWeekday_Id 
			WHERE (T.TempWeekday_FromDate <= @dtmActualShiftStartTime and T.TempWeekday_ToDate >= @dtmActualShiftStartTime) AND T.IsDeleted = 0 
			AND TL.LevelId=@levelId
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <22-09-2016>
-- Description:	<Checking Specific device punch Type detail status>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_CheckingSpecificDeviceAndPunchTypeStatus]
	@inClk_DeviceId varchar(20),
	@inClk_Type varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	select P.PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID = @inClk_DeviceId and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>

-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime ''Early Exit'',1


-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime ''Absent - Single Day'',2
-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime ''Continuous Absent'',6
-- Proc_TA_CheckingShiftTimingsReachedTriggeringTime ''Late Entry'',2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckingShiftTimingsReachedTriggeringTime]
	-- Add the parameters for the stored procedure here
	@TemplateName VARCHAR(50),
	@ShiftID INT
AS
BEGIN
	SET NOCOUNT ON;	
	if not exists(
	select sl.Status from TA_Tbl_SMSLogDetails SL 
	inner join ta_tbl_Smstemplates ST on ST.id=SL.TemplateId 
	where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and sl.status=1 and ST.TemplateName=@TemplateName 
	and ShiftId=@ShiftID and ST.TemplateName!=''Late Entry'')
	begin	
		if exists(select sl.Status from TA_Tbl_SMSLogDetails SL 
		inner join ta_tbl_Smstemplates ST on ST.id=SL.TemplateId 
		where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and sl.status=1 and ST.TemplateName=''Continuous Absent'')
		begin
			select 0
			return
		end
		DECLARE @FirstTriggeringTime DATETIME
		DECLARE @ShiftTiming DATETIME
		DECLARE @TriggeringTime DATETIME
		DECLARE @TemplateID int
		DECLARE @NextTriggeringTime DATETIME
		DECLARE @LessHrsLimitation VARCHAR(5)	
		DECLARE @lesshrsLimitationInMins INT
		DECLARE @TagName VARCHAR(50)
		if(@TemplateName=''Late Entry'')
		begin
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1   --active template need to take
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0  -- active shift shift starttime
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming		
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		-- today date add shift shift starttime
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
			if not exists(select top 1 logid from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID 
			and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and ShiftId=@ShiftID and Status=1)
			begin
				set @TriggeringTime=@TriggeringTime
			end
			else
			begin
				SELECT top 1 @NextTriggeringTime= NextTriggeringTime from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
				and Status=1 and ShiftId=@ShiftID
				order by logid desc			
				set @TriggeringTime=@NextTriggeringTime	
			end
		end	
		if(@TemplateName=''Early Exit'')
		begin
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming		
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName=''Less Hours Worked'')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@LessHrsLimitation=LessHrsLimitation 
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName=''Absent - Single Day'')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		end
		if(@TemplateName=''Continuous Absent'')
		begin			
			SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
			from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
			select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
			set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
			set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
			set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		end
		if(@TriggeringTime<=GETDATE())
		begin
			select 1
		end
		else 
		begin
			select 0
		end
	end
	else
	begin
		select 1000000
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHolidayUpdate]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGlobalHolidayUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckGlobalHolidayUpdate  
Description : check global holiday while update
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGlobalHolidayUpdate]
(
	@HID int,
	@HolidayType varchar(3)
)  
AS  
BEGIN  
	select isnull(SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1),0) as ''Days'' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
	where h.Holiday_type=@HolidayType and h.Holiday_Id<>@HID and  h.Isdeleted=0  and ys.IsActive=1
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckGlobalHoliday]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckGlobalHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckGlobalHoliday ''Y''
Description : check global holiday  
Tables Included : TA_Tbl_Holiday, TA_Tbl_YearSetting    
Created By : Janakaraj.P   
Created On : 20-Aug-2007  
Modified By :    
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckGlobalHoliday](@HolidayType varchar(3))  
AS   
BEGIN  
	SET NOCOUNT ON	
	select isnull(SUM(DateDiff(d,h.Holiday_FromDate,h.Holiday_ToDate)+ 1),0) as ''Days'' From TA_Tbl_Holiday h
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id  
	where h.Holiday_type=@HolidayType and h.Isdeleted=0 and ys.IsActive=1 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckForHolidayForCollect]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckForHolidayForCollect]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11:39 AM>
-- Description:	<Checking holiday is declared for current date>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckForHolidayForCollect]
	@dtmDate datetime
AS
BEGIN
	SET NOCOUNT ON;
    Select Holiday_Id from TA_Tbl_Holiday where Holiday_FromDate <= @dtmDate and Holiday_ToDate >= @dtmDate and Holiday_Type = ''G'' and IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckEntrance_Delete]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckEntrance_Delete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_CheckEntrance_Delete
Description	:	Checking the entrance In Terminal and out Terminal Mapped in TA_Tbl_Clk_RawData
Tables Included	:	ta_tbl_entrance Ta_tbl_Terminal and TA_Tbl_Clk_RawData
Created By	:	Prabakaran
Created On	:	05-Oct-07
Modified By	:  R.Manikandan
Modified On	:  22-11-2016 16.53
*/
CREATE Procedure [dbo].[Proc_TA_CheckEntrance_Delete]    
( 
    @EntranceId int   
)     
As    
BEGIN    
	SET NOCOUNT ON
	DECLARE @Count AS INT
	DECLARE @Count1 AS INT
	select @Count = Count(CLK_DEVICEID) from TA_Tbl_Clk_RawData C
	inner join TA_Tbl_Terminal t on C.CLK_DEVICEID=t.Terminal_ReaderID
	inner join TA_Tbl_Entrance_INOUTDetails e on t.Terminal_Id=e.Reader_Id 
	where e.Entrance_Id=@EntranceId and t.IsDeleted=0
	SELECT @Count1 = COUNT(M.ManualTimeEntry_Id) FROM TA_Tbl_Entrance_INOUTDetails E
	inner join TA_Tbl_ManualTimeEntry M on (E.Reader_Id = M.ManualTimeEntry_InReaderID OR E.Reader_Id = M.ManualTimeEntry_OutReaderID ) 
	WHERE E.Entrance_Id = @EntranceId 
	SELECT @Count + @Count1 AS EntranceReadersCount
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckApplicableAfterDays]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckApplicableAfterDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckApplicableAfterDays  202,53,''01/03/2008''
Description  :    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckApplicableAfterDays]    
(   
@Employee_Id bigint,    
@leaveType_Id int,
@FromDate datetime   
)    
AS    
declare @test as decimal    
declare @Result as varchar(10)    
if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
BEGIN   
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 
	and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
else
BEGIN
    set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101))     
if(@test=0)    
 begin    
 set @Result=''Y''    
 end    
else    
 begin 
 declare @eligible as decimal       
 if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
  BEGIN   
	  set @eligible=(select distinct (Datediff(d,e.DateOfJoining,@FromDate) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 
	  and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	  and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))   
  END 
  else
  BEGIN
      set @eligible=(select distinct (Datediff(d,e.DateOfJoining,@FromDate) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc))   
  END 
    if (@eligible>=0)    
      begin    
      set @Result=''Y''    
      end       
    else    
     begin    
     set @Result=''N''    
     end    
end    
select @Result as RemainingNoOfLeaves
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForOnDuty]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayForOnDuty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		K.Gopinath
-- Create date: 15-02-2014
-- Description:	Check for holidays while onduty entry
-- =============================================
 CREATE procedure [dbo].[Proc_TA_CheckHolidayForOnDuty]
	@Date Varchar(15)
as 
BEGIN
	SET NOCOUNT ON;
	SELECT COUNT(*) as HolidayCount from TA_Tbl_Holiday where IsDeleted=0 And(@Date between Holiday_FromDate and Holiday_ToDate) and Holiday_Type=''G''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidaycount]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidaycount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckHolidaycount  
Description : check holidays count
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckHolidaycount]
AS
BEGIN
	SET NOCOUNT ON
	SELECT COUNT(*) AS MaxCount  FROM TA_Tbl_Holiday WHERE Isdeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_CheckLeavePolicyDatesExists  60010,''2008-12-01 00:00:00.000'',''2008-12-31 00:00:00.000''
Description  :    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists_Angler]    
@Employee_Id bigint,    
@FromDate datetime,
@ToDate datetime     
AS    
begin
	SET NOCOUNT ON;
	declare @test as decimal    
	declare @Result as varchar(10)    
	select count(empl.EmployeeId) as PolicyCount from ta_tbl_emp_leavepolicy empl
	where empl.EmployeeId=@Employee_Id 
	and (@FromDate between empl.FromDate and empl.ToDate) and (@ToDate between empl.FromDate and empl.ToDate)
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeaveType]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeaveType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeaveType 86 
Description		: check leave type before insert, is already there or not  
Tables Included : TA_Tbl_LeavePolicyDetails  
Created By		: Arun Vinoth.T  
Created On		: 14-Aug-2007  
Modified By		: Prabakaran.P  
Modified On		: 27-Feb-08 
*/  
CREATE Procedure [dbo].[Proc_TA_CheckLeaveType]
(        
 @LeaveTypeId int        
)         
As        
DECLARE @Isdel INT        
SET @Isdel=0        
 BEGIN 
	SET NOCOUNT ON;
    select count(LeaveType_Id) as LType from TA_Tbl_LeavePolicyDetails lpd
	inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 
	where LeaveType_Id=@LeaveTypeId and lp.IsDeleted=0    
 END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicy]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLeavePolicy  
Description : check leave policy before insert, is already there or not  
Tables Included : TA_Tbl_Emp_LeavePolicy  
Created By : Arun Vinoth.T  
Created On : 14-Aug-2007  
Modified By :  
Modified On :  
*/  
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckLeavePolicy] 
	-- Add the parameters for the stored procedure here
	@LeavePolicy INT
AS
BEGIN
	SET NOCOUNT ON;
	SELECT COUNT(LeavePolicy_Id) as count FROM TA_Tbl_Emp_LeavePolicy WHERE LeavePolicy_Id=@LeavePolicy AND Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPassportExpiryAlert]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPassportExpiryAlert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:        Velumani P
-- Create date:  31 Jan 2020
-- Description:   Get Passport notification Details
-- Proc_TA_GetPassportExpiryAlert 4,''IndividualUsers''
--Proc_TA_GetPassportExpiryAlert 3,''IndividualUsers''
--Proc_TA_GetPassportExpiryAlert 2,''IndividualUsers''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPassportExpiryAlert]
      -- Add the parameters for the stored procedure here
      @employeeID as int,
      @UserGroupName as nvarchar(100)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
		declare @PassportExpiry varchar(250) 
		declare @PassportFromdate datetime
		Declare @PassportTodate datetime
		Declare @TodayExpiry datetime
		Declare @Valid int
		DECLARE @DATEFORMAT AS INT
		DECLARE @TIMEFORMAT AS NVARCHAR(10)
		SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
		set @Valid= 0
		select @PassportFromdate = dateadd(dd, -50,Passport_expirydate) from TA_Tbl_Employee where Employee_Id = @employeeID
		select @PassportTodate = Passport_expirydate from TA_Tbl_Employee where Employee_Id = @employeeID
		select @Valid = 1 where getdate() between @PassportFromdate and @PassportTodate
		select @Valid = 2 where @PassportTodate < getdate()
		set @TodayExpiry = (select DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
		select @Valid = 3 where @PassportTodate = @TodayExpiry

		if(@Valid = 1)
		begin
			set @PassportExpiry = ''Your Passport will be expired on '' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + ''. Please update ''
		End
		else if(@Valid = 2)
		begin
			set @PassportExpiry = ''Your Passport expired on '' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + ''. Please update ''
		End	
		else if(@Valid = 3)
		begin
			set @PassportExpiry = ''Your Passport will expire today '' +  CONVERT(VARCHAR, @PassportTodate, @DATEFORMAT)  + ''. Please update ''
		End	
		else
		begin
			set @PassportExpiry = ''0''
		End

		------

	select isnull(@PassportExpiry,0) as Passport

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetParentLevelidUsingEmpid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 2016-01-05
-- Description:	Getting Parent level id For Successive year value calculation
-- After getting the issue in client place while using successive year in leave application,its not allowing to save the data.
-- =============================================
create PROCEDURE [dbo].[Proc_Ta_GetParentLevelidUsingEmpid]
	-- Add the parameters for the stored procedure here
	@EmployeeAutoID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,	
		SWIPECARD VARCHAR(50)
	)
	Declare @levelId int	
	set @levelId=
	(
		SELECT top 1 EL.LEVELID FROM 
		(
			SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EMPLOYEEID FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 	
			WHERE EMP.ISDELETED=0 and EMP.Employee_id=@EmployeeAutoID
			group by EmployeeId
		) ELEVEL
		INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID	
		AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(getdate() AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
	)
	while((select parentId from Ta_Tbl_levelDetails where id=@levelId)!=0)
	begin
		select @levelId=parentId from Ta_Tbl_levelDetails where id=@levelId
	end
	select @levelid
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetParentLevelIdsForEmailScheduler]
	-- Add the parameters for the stored procedure here
	@EmailLevelid int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempLevelDetails(Levelid int,parentId int)
	Declare @LevelId int
	Declare @ParentId int
    -- Insert statements for procedure here
    if((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)!=0)
		begin
			while((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)!=0)
				begin
					select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
					insert into #TempLevelDetails values(@LevelId,@ParentId)
					set @EmailLevelid=@ParentId 
					if((select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)=0)
						begin
							select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
							insert into #TempLevelDetails values(@LevelId,@ParentId)
						end
				end
		end
	else
		begin
			if Exists(select parentId from Ta_Tbl_levelDetails where id=@EmailLevelid)
				begin
					select @LevelId=id,@ParentId=parentId from Ta_Tbl_levelDetails where id=@EmailLevelid
					insert into #TempLevelDetails values(@LevelId,@ParentId)		
				end
		end
	select * from #TempLevelDetails 	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 26-07-2017 03.51 PM
-- Description:	Getting Parent Level details using usergroup
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetParentLevelDetailsUsingGroupName]
@UserGroupName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @GroupID int
	SELECT @GroupID=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
	select ld.id,ld.name from TA_Tbl_LevelRights lr
	inner join Ta_Tbl_levelDetails ld on lr.LevelId=ld.id
	where lr.GroupId=@GroupID and ld.parentId=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionConversation]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionConversation] 
	@permissionApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_PermissionConversation WHERE PermissionId = @permissionApplicationId Order by OrderBy desc
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionByPermissionId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionByPermissionId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetPermissionByPermissionId 12
Description		:	Get Permission Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetPermissionByPermissionId]
	@Permission_Id int =null
as
begin
	set nocount on;
	select *,EL.LevelId,ED.DesignationId from TA_Tbl_Permission P
	inner join TA_TBL_Employee E on P.Employee_Id=E.Employee_Id
	inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeId 
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=EL.LevelId   
	where 
	((@Permission_Id is null) or (Permission_Id=@Permission_Id)) and 
	EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and 
	EffectiveDate <= P.Permission_AppliedDate order by EffectiveDate desc)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeavePrivateNotes]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeavePrivateNotes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--Proc_TA_GetLeavePrivateNotes 60
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLeavePrivateNotes] 
	-- Add the parameters for the stored procedure here	
	@leaveApplicationId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LP.LeavePrivateNotesId,LP.LeaveApplicationId,(Emp.Employee_FirstName + '' '' + isnull(Emp.Employee_LastName,'''')) as NotesBy,LP.Notes,LP.OrderBy,LP.ToMailIds,LP.CcMailIds,
	LP.Emp_Id,LP.TimeStamp,Emp.EmailId as FromMailId FROM TA_Tbl_LeavePrivateNotes LP
	INNER JOIN TA_Tbl_Employee Emp on Emp.Employee_Id=LP.NotesBy
	WHERE LP.LeaveApplicationId = @leaveApplicationId 
	Order By OrderBY Desc
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetODEntryById]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetODEntryById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--[Proc_TA_GetODEntryById] 16
--select CONVERT(varchar,getdate(),101)
-- Modified by Gopinath on 11 feb 2014 for Datetime conversion
CREATE PROCEDURE [dbo].[Proc_TA_GetODEntryById]
(@ODID as int)
AS
BEGIN
	DECLARE @Isdel int
	SET @Isdel=0
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	DECLARE @TimeFormat as nvarchar(25)
	SELECT @date=DateFormat,@TimeFormat=timeformat FROM TA_Tbl_DateandTimeFormat
	IF(@date=''dd/MM/yyyy'')
	BEGIN
		SET @dateFormat = 103
	END
	ELSE IF(@date=''MM/dd/yyyy'')
	BEGIN
		SET @dateFormat = 101
	END
	ELSE
	BEGIN
		SET @dateFormat = 106
	END
	--set @TimeFormat=''hh:mm''
	select OD.Onduty_ID,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, Onduty_EntryDate,106),'' '',''-'')
			else convert(varchar, Onduty_EntryDate,@dateFormat)
	end as Onduty_EntryDate,
	case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Onduty_FromDate,106),'' '',''-'')
			else convert(varchar, Onduty_FromDate,@dateFormat) 
	end as Onduty_FromDate,
	case	when (@TimeFormat)=''hh:mm'' then CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OD.Onduty_FromTime,0)), 114) 
			else Onduty_FromTime
	end Onduty_FromTime,
	case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Onduty_ToDate,106),'' '',''-'')
			else convert(varchar, Onduty_ToDate,@dateFormat) 
	end as Onduty_ToDate,
	case when (@TimeFormat)=''hh:mm'' then CONVERT(varchar(8), DATEADD(minute,0,convert(datetime,OD.Onduty_ToTime,0)), 114) 
			else Onduty_ToTime
	end Onduty_ToTime
	,OD.Onduty_Reason,OD.Onduty_Status,Onduty_Type,IncludeWeekOff,From_session,To_session,
	E.Employee_FirstName + '''' + E.Employee_LastName AS ''Employee_Name'',E.Employee_Id,E.Emailid,
	E.Employee_Code_Id,ld.name as LevelName, ld.id as levelid,ED.DesignationID,e.Reporting_To,e.Leave_Sanc_Authority
	FROM TA_Tbl_OndutyEntry as OD 
	INNER JOIN TA_Tbl_Employee as E ON E.Employee_Code_Id=OD.Onduty_EmployeeID
	inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
	inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
	WHERE OD.Isdeleted=@Isdel and OD.Onduty_ID=@ODID
	select * from TA_Tbl_OnDutyConversation where OnDutyApplicationId=@ODID order by OnDutyConversationId desc
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetNumberOfHolidaysTaken]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetNumberOfHolidaysTaken]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetNumberOfHolidaysTaken 10924,3,2
Description		:	Get the Remaining No of Holidays from TA_Tbl_LeaveApplication and TA_Tbl_HolidaySettings
Tables Included	:	Ta_Tbl_Holiday,Ta_Tbl_LeaveApplication and ta_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetNumberOfHolidaysTaken] 
	@Employee_Id int,
	@LeaveType_Id int,
	@YearSettingId int
AS
BEGIN
	DECLARE @LevelId int 
	select @LevelId=LevelId from ta_tbl_employeeLevel where employeeId=@Employee_Id
	while((select Id from TA_tbl_LevelDetails where id=@LevelId) <> '''') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@LevelId) <> 1)
				begin
				set @LevelId = (select parentId from TA_tbl_LevelDetails where id=@LevelId) 
				end
			else
			begin
				break
			end
		ENd
	set @LevelId=@LevelId
	if(@LeaveType_Id<>-1)
	BEGIN
		declare @CountRecordExist as int
		set @CountRecordExist=(select count(*) From Ta_Tbl_LeaveApplication la where la.Type=''Restricted Holiday'' and la.Isdeleted=0 and la.status not in(''Rejected'')and la.Employee_Id=@Employee_Id and YearSettings_Id=@YearSettingId)
		if @CountRecordExist>0
			begin
				select h.holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate,sum(la.NumberOfDays) as HolidaysTaken from Ta_Tbl_Holiday h
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id
				where   la.Type=''Restricted Holiday'' and la.Isdeleted=0 and status not in(''Rejected'') and la.Employee_Id=@Employee_Id 
				and h.YearSettings_Id=@YearSettingId
				group by h.holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate
				union
				select h.Holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate, ''0'' as HolidaysTaken 
				From TA_Tbl_Holiday h 
				where h.isdeleted=0 and Holiday_Type=''Y''  and h.YearSettings_Id=@YearSettingId
			end
		else
			begin
				select 0 as HolidaysTaken,h.Holiday_Id,h.Holiday_FromDate,h.Holiday_ToDate From ta_Tbl_Holiday h
				where h.Holiday_Id=@LeaveType_Id and h.YearSettings_Id=@YearSettingId
			end
	END
	ELSE
	BEGIN
		declare @NumberOfDays as float
		declare @YearlyMaxDays as float
		set @NumberOfDays=(select isnull(sum(NumberOfDays),0.0) as NumberOfDays from TA_Tbl_LeaveApplication la
		inner join TA_Tbl_Holiday h on h.Holiday_Id=la.LeaveType_id
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id
		where ys.YearSettings_ID=@YearSettingId and la.Type=''Restricted Holiday'' and la.Employee_Id=@Employee_Id and la.IsDeleted=0 and la.Status<>''Rejected'')
		set @YearlyMaxDays=(select Yearly_Maxdays from TA_Tbl_HolidaySettings hs
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_ID=hs.YearSettingId
		where ys.YearSettings_ID=@YearSettingId)
		set @NumberOfDays= @YearlyMaxDays-@NumberOfDays
		select ''Restricted Holiday'' as ''Restricted Holiday'',@NumberOfDays as NumberOfDays
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSanctionUser]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSanctionUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan.R
-- Create date: 25-05--2017
-- Description:	Get My calendar Data
-- Proc_TA_GetSanctionUser 359
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSanctionUser]
	-- Add the parameters for the stored procedure here
	@EmployeeID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
	select distinct EmpAutoId from #EmployeeIds  where EmpAutoId not in (@EmployeeID)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRestrictedHolidayCount]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRestrictedHolidayCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	27-Dec-2013
Descriptions	:	Added this conditon while taking from process data table
 Proc_TA_GetRestrictedHolidayCount 27
 */
CREATE   Procedure [dbo].[Proc_TA_GetRestrictedHolidayCount]         
(          
	@Holiday_Id int          
)
As	
BEGIN
	DECLARE @Count INT
	DECLARE @Count1 INT
	Select @Count =Count(LeaveType_id) from ta_tbl_Leaveapplication la inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id
	where ys.IsActive=1 and la.LeaveType_id=@Holiday_Id  AND la.Isdeleted=0 AND la.Type=''Restricted Holiday'' and la.Status <> ''Rejected''
	SELECT @Count1= COUNT(P.Process_Rec_Id) FROM TA_Tbl_ProcessedData P
	inner join TA_Tbl_Holiday H on 1=1 WHERE H.Holiday_Id = @Holiday_Id AND P.ProcessFlag = 1 AND P.Date BETWEEN H.Holiday_FromDate AND H.Holiday_ToDate and P.Date<GETDATE()
	SELECT  isnull(@Count,0) +isnull(@Count1,0) AS RestrictedHolidayCount
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- select * from ta_tbl_leveldetails
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftDetailsForAutoShiftAllocation] 
	@LevelID int
AS
Begin
	Declare @parentID int
	
	;WITH ChildLevelDetails as
	(
		SELECT id,parentid from Ta_Tbl_levelDetails LD where id=@LevelID
		UNION ALL
		SELECT ld.id,ld.parentId  from Ta_Tbl_levelDetails LD 
		INNER JOIN ChildLevelDetails CL ON LD.id=CL.parentId			
	)
	select @parentID=isnull(id,0) from ChildLevelDetails where parentId=0
	select @LevelID=@parentID;
	DECLARE @timeformat   varchar(10)
	SELECT @timeformat=TimeFormat FROM TA_Tbl_DateandTimeFormat	
	if(@timeformat=''hh:mm tt'')
		begin
			select 0 Shift_Id,''-Select-'' Shift_Name,''-Select-'' Shift_ShortName
			union
			SELECT Shift_Id,Shift_Name,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName 
				from TA_Tbl_Shift
			where isdeleted=0 and level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName
			from TA_Tbl_Shift where isdeleted=0 and level_id=0
		end
	else
		begin
			select 0 Shift_Id,''-Select'' Shift_Name,''-Select-'' Shift_ShortName
			union
			SELECT Shift_Id,Shift_Name,Shift_ShortName + '' ( '' + convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName 
			from TA_Tbl_Shift where  isdeleted=0 and level_id=@LevelID
			Union
			SELECT Shift_Id,Shift_Name, Shift_ShortName + '' ( '' + convert(char(5),cast(Shift_StartTime as datetime),108) + '' - '' + convert(char(5),cast(Shift_EndTime as datetime),108) + '' ) '' as Shift_ShortName
			from TA_Tbl_Shift where  isdeleted=0 and level_id=0
		end
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchValue]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPunchValue]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-11-2016>
-- Description:	<Proc_TA_GetPunchValue,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPunchValue]
	-- Add the parameters for the stored procedure here
	@inClk_DeviceId varchar(20),
	@inPunchType varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select P.Value from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T  on P.Terminal_Id = T.Terminal_Id 
	where T.Terminal_ReaderID =@inClk_DeviceId
	and P.PunchType = @inPunchType and P.IsDeleted = 0 and T.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPunchTypesByTerminalId]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPunchTypesByTerminalId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetPunchTypesByTerminalId]
(
	@TerminalId INT,
	@PunchType nVarchar(2)
) 
AS
IF (@PunchType = ''I'')
	BEGIN
		 if((select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)=@TerminalId)
			begin
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''In'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''Shift In'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''Break In'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''Lunch In'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''Official In'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''787''
				AND PunchType IN (''Out Duty'') AND Isdeleted = 0 and Addedby=''A'' order by PunchType_Id
			end
		 else
			begin		
				SELECT PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id = @TerminalId 
				AND PunchType IN (''In'',''Shift In'',''Break In'',''Lunch In'',''Official In'',''Out Duty'') AND Isdeleted = 0
			end
    END
IF (@PunchType = ''O'')
    BEGIN
		if((select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)=@TerminalId)
			begin
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''Out'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''Shift Out'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''Break Out'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''Lunch Out'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''Official Out'') AND Isdeleted = 0 and Addedby=''A''
				union all
				SELECT top 1 PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id != ''788'' 
				AND PunchType IN (''In Duty'') AND Isdeleted = 0 and Addedby=''A'' order by PunchType_Id
			end
		 else
			begin		
				SELECT PunchType_Id,PunchType,Value,PunchType as PunchType_Value FROM TA_TBL_PunchTypes WHERE Terminal_Id = @TerminalId 
				AND PunchType IN (''Out'',''Shift Out'',''Break Out'',''Lunch Out'',''Official Out'',''In Duty'') AND Isdeleted = 0
			end
    END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetSMSLogDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetSMSLogDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetSMSLogDetails ''-select-'',''2019-08-01'',''2019-08-05'','''',''Superadmin'',0,1,0
-- Proc_TA_GetSMSLogDetails ''Permission Application - Forward'',''2016-09-30'',''2016-09-30'',''Karthikeyan ,'',''Superadmin'',0,1,2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetSMSLogDetails]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(100),
	@fromDat DATETIME,
    @ToDat DATETIME,
    @ReceiverId NVARCHAR(max),
    @UserGroupName NVARCHAR(250),
    @GradeLevel NVARCHAR(20),
    @ParentId INT,
    @Status int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	--Get current date time format.
	DECLARE @dateFormat as INT
	DECLARE @date as nVARCHAR(25)             
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
	IF(@date=''dd/MM/yyyy'')
	BEGIN
		  SET @dateFormat = 103
	END
	ELSE IF(@date=''MM/dd/yyyy'')
	BEGIN
		  SET @dateFormat = 101
	END
	ELSE
	BEGIN
		  SET @dateFormat = 106
	END      
	--INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@ReceiverId,''''
	--INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@ReceiverId,'''' 
	--INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@ReceiverId,''''
	if(@ReceiverId is not null and @ReceiverId <> '''')
	BEGIN
	  CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	  INSERT INTO #EmployeeID
	  SELECT Value from dbo.SplitUpEmployeeName(@ReceiverId,'','')
	end
	DECLARE @sqlQuery as NVARCHAR(max)
	SET @sqlQuery = ''''
	SET @sqlQuery = @sqlQuery + '' SELECT sl.logid, TemplateID,TemplateName,SL.Message,TriggeredTimings,E.Employee_FirstName as receivers,
	case	when SL.Status=0 then ''''Message Not Sent''''
			when SL.STatus=1 then ''''Message Sent'''' end Status  from ta_tbl_smslogdetails SL''
	SET @sqlQuery = @sqlQuery + '' Inner join Ta_Tbl_SMSTemplates ST on SL.TemplateID=ST.ID''
	SET @sqlQuery = @sqlQuery + '' left outer join ta_tbl_employee E on SL.Receivers=E.swipecardNo ''
	--SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id ''
	--SET @sqlQuery = @sqlQuery + '' INNER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
 --   SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id ''
 --   SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
 --   SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID ''
 --   SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id ''
 --   SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' where 1=1 ''
	if(@fromDat!='''' and @ToDat!='''')
	begin
		 SET @sqlQuery = @sqlQuery + '' And (TriggeredDate >= CONVERT(DATETIME,''''''+cast( @fromDat as nVARCHAR(50))+'''''', 102)) 
      AND (TriggeredDate <= CONVERT(DATETIME,''''''+cast(@todat as nVARCHAR(50))+'''''', 102)) '' 
	end
	if(@ReceiverId is not null and @ReceiverId <> '''')
	begin
		SET @sqlQuery = @sqlQuery + '' And SL.Receivers in(select * from #EmployeeID)''
	end
	if(@Status!=2)
	begin
		SET @sqlQuery = @sqlQuery + '' And SL.Status=''+CONVERT(char(1),@status)
	end
	if(@TemplateName!=''-Select-'')
	begin
		Declare @Templateid int
		set @Templateid=(select id from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName)
		SET @sqlQuery = @sqlQuery + '' And SL.TemplateID=''+CONVERT(varchar(10),@Templateid)
	end
	print(@sqlQuery)
	Execute(@sqlQuery)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingCompanyDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingCompanyDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 02-12-2014
-- Description:	Getting Compancy Details
-- drop procedure [dbo].[Proc_Ta_GettingCompanyDetailsForService]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingCompanyDetailsForService]
AS
BEGIN
	SET NOCOUNT ON;
	BEGIN TRY
		BEGIN TRANSACTION		
		select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName
		from TA_Tbl_LevelDetails ld inner join TA_Tbl_Level l on l.LevelId=ld.LevelId
		where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.parentid=0	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0
             ROLLBACK TRANSACTION
	END CATCH
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTerminalMappingCount]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTerminalMappingCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Modified by	:	Prabakaran.P
-- Modified on	:	17-Mar-08
CREATE   PROCEDURE [dbo].[Proc_TA_GetTerminalMappingCount]
(
	@TerminalId INT
)
AS
BEGIN
	DECLARE @Count AS INT
	DECLARE @Count1 AS INT
	SELECT @Count1 =COUNT(P.Terminal_Id) FROM TA_Tbl_Terminal T
	inner join TA_Tbl_PunchTypes P on P.Terminal_Id = T.Terminal_Id WHERE T.Terminal_Id = @TerminalId
	SELECT @Count = COUNT(eio.Entrance_Id) FROM TA_Tbl_Entrance_INOUTDetails eio INNER JOIN TA_Tbl_Entrance en ON en.Entrance_Id=eio.Entrance_Id 
	WHERE eio.Reader_Id=@TerminalId
	SELECT @Count + @Count1 AS TerminalMappingCount
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	10-Dec-2013
Descriptions	:	Adding this proce for getting processed data of the temp weekday
*/
CREATE proc [dbo].[Proc_TA_GetTempWeeklyOffProcessedDays]
(
@tempWeekday_Id int
)
as
begin
	select COUNT(*) as count from TA_Tbl_ProcessedData P
	inner join TA_Tbl_TemWeekday TW on P.Date between TW.TempWeekday_FromDate and TW.TempWeekday_ToDate
	inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TWL.TempWeekday_Id=TW.TempWeekday_Id
	where TW.IsDeleted=0 and TW.timestamp<=P.Date
	and P.ProcessFlag=1 and TW.TempWeekday_Id=@tempWeekday_Id
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeDetailsForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-08-2015
-- Description:	Getting Punch Type Details using device and punch value
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForService]
	-- Add the parameters for the stored procedure here
	@inClk_DeviceId varchar(20),
	@inClk_Type varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select P.PunchType from TA_Tbl_PunchTypes P,TA_Tbl_Terminal T where P.Terminal_Id = T.Terminal_Id 
	and T.Terminal_ReaderID = @inClk_DeviceId and P.Value = @inClk_Type and P.IsDeleted = 0 and T.IsDeleted = 0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Modified date: <23-11-2016 14.19>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingPunchTypeDetailsForMovementsEntry]
AS
BEGIN
	SET NOCOUNT ON;	
	SELECT TOP 1 PunchType,1	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''In''			UNION 
	SELECT TOP 1 PunchType,2	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Out''			UNION
	SELECT TOP 1 PunchType,3	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Shift In''		UNION 
	SELECT TOP 1 PunchType,4	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Shift Out''	UNION
	SELECT TOP 1 PunchType,5	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Break In''		UNION 
	SELECT TOP 1 PunchType,6	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Break Out''	UNION
	SELECT TOP 1 PunchType,7	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Lunch In''		UNION
	SELECT TOP 1 PunchType,8	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Lunch Out''	UNION
	SELECT TOP 1 PunchType,9	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''In Duty''		UNION
	SELECT TOP 1 PunchType,10	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Out Duty''		UNION
	SELECT TOP 1 PunchType,11	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Official In''	UNION
	SELECT TOP 1 PunchType,12	AS DataValueField FROM TA_Tbl_PunchTypes WHERE Isdeleted=0 and PunchType=''Official Out'' 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingReceiverDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingReceiverDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GettingReceiverDetails ''Leave Application - Apply'',787,''Manikandan'',''2016-09-05 to 2016-09-05'',''CL'',''1''
-- Proc_TA_GettingReceiverDetails ''Permission Application - Apply'',102,''Rajiv'',''29-Sep-2016 11:00 To 29-Sep-2016 12:00'','''',''01:00''
-- Proc_TA_GettingReceiverDetails ''OnDuty - Forward'',102,''Rajiv'',''07/Sep/2016 09:00:00 AM To 07/Sep/2016 02:00:00 PM'','''',''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingReceiverDetails]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(50),
	@Employee_ID varchar(50),
	@EmployeeName varchar(50),
	@LeaveFrom_LeaveTo varchar(50),
	@LeaveType varchar(10),
	@NoofDays varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @TagName VARCHAR(50)
	if(@TemplateName=''Leave Application - Apply'' or @TemplateName=''Leave Application - Forward'' or @TemplateName=''Leave Application - Approved'' or @TemplateName=''Leave Application - Rejected'')
	begin
		set @TagName=''LeaveApplication''
	end
	else if(@TemplateName=''Permission Application - Apply'' or @TemplateName=''Permission Application - Forward'' or @TemplateName=''Permission Application - Approved'' or @TemplateName=''Permission Application - Rejected'')
	begin
		set @TagName=''PermissionApplication''
	end
	else if (@TemplateName=''OnDuty - Apply'' or @TemplateName=''OnDuty - Forward'' or @TemplateName=''OnDuty - Approved'' or @TemplateName=''OnDuty - Rejected'')
	begin
		set @TagName=''OnDuty''
	end
	Declare @TagCount int
	CREATE TABLE #TempTags(id INT IDENTITY(1,1),Tags VARCHAR(max))
	CREATE TABLE #TempTagPosition(id int identity(1,1),Tag varchar(500),position int)
	CREATE TABLE #TempTagPositionFinal(id int identity(1,1),Tag varchar(500),position int,ColumnNames varchar(20))
	create table #TempFinal(id int identity(1,1),EmployeeName varchar(250),EmployeeId varchar(50),FromAndTo varchar(50),Type varchar(10),Days varchar(10))
	insert into #TempFinal values(@EmployeeName,@Employee_ID,@LeaveFrom_LeaveTo,@LeaveType,@NoofDays)
	--select * from #TempFinal
	INSERT INTO #TempTags
	SELECT Tags FROM Ta_Tbl_SMSTags WHERE TemplateName=@TagName and Tags!=''{User Name}''
	set @TagCount=(select COUNT(*) from #TempTags)
	--select * from #TempTags
	Declare @Tags varchar(500)
	declare @Start int
	set @Start=1	
	while @Start<=@TagCount
	begin		
		select @Tags=Tags from #TempTags where id=@Start
		--select @Tags
		insert into #TempTagPosition 
		select @Tags,CHARINDEX(@Tags,Tags) from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		and CHARINDEX(@Tags,Tags)!=0
		set @Start=@Start+1
	end	
	insert into #TempTagPositionFinal	
	select Tag,position,
	case	when Tag=''{Employee ID}''	then ''EmployeeId''
			when Tag=''{Employee Name}''	then ''EmployeeName''
			when Tag=''{Leave From - Leave To}'' or Tag=''{Permission From - Permission To}'' or Tag=''{OnDuty From - OnDuty To}''	then ''FromAndTo''
			when Tag=''{Leave Type}''	then ''Type''
			when Tag=''{No.of Days}'' or Tag=''{No.of Hrs}'' then ''Days''			
	end
	from #TempTagPosition order by position
	--select * from #TempTagPosition
	Declare @Totalrecord int
	set @Totalrecord=(select COUNT(*) from #TempFinal)
	declare @i int
	set @i=1
	Create table #FinalStringTable(id int identity(1,1),FinalString varchar(max))
	Declare @TagName1 varchar(20)
	Declare @TagName2 varchar(20)
	Declare @TagName3 varchar(20)
	Declare @TagName4 varchar(20)
	Declare @TagName5 varchar(20)
	select @TagName1=ColumnNames from #TempTagPositionFinal where id=1
	select @TagName2=ColumnNames from #TempTagPositionFinal where id=2
	select @TagName3=ColumnNames from #TempTagPositionFinal where id=3
	select @TagName4=ColumnNames from #TempTagPositionFinal where id=4
	select @TagName5=ColumnNames from #TempTagPositionFinal where id=5
	while @i<=@Totalrecord
	begin		
		Declare @DynamicSQL varchar(max)
		set @DynamicSQL=''''		
		set @DynamicSQL=@DynamicSQL+''select ''
		if(@TagName1!='''')
		begin
			set @DynamicSQL=@DynamicSQL+@TagName1
		end
		if(@TagName2!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName2
		end
		if(@TagName3!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName3
		end
		if(@TagName4!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName4
		end
		if(@TagName5!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName5
		end
		set @DynamicSQL=@DynamicSQL+'' From #TempFinal where id=''+CONVERT(varchar(max),@i)
		Insert into #FinalStringTable
		Execute(@DynamicSQL)		
		set @i=@i+1
	end
	Declare @FinalString nvarchar(max)
	select @FinalString=coalesce(@FinalString+'','','' '')+isnull(FinalString,'''') from #FinalStringTable
	--select @FinalString
	if(@FinalString!='''')
	begin
		select Message+@FinalString as Message,@FinalString as ExceptionEmployees,@TemplateName as TemplateName
		from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName and Status=1	
	end
	else
	begin
		select '''' Message,'''' ExceptionEmployees,@TemplateName as TemplateName
	end
	select E.Employee_FirstName+'' ''+E.Employee_LastName as Receivers,E.SwipeCardNo,E.Mobile_Number from TA_Tbl_Employee E
	 where UserGroup_Id in(
	select Usergroupid from Ta_Tbl_SMSReceivers SR
	inner join Ta_Tbl_SMSTemplates ST on SR.TemplateId=ST.id
	where TemplateName=@TemplateName and ST.Status=1) and E.Isdeleted=0 and E.Employee_Status=1
	and E.SwipeCardNo!=''18000000''
    -- Insert statements for procedure here
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingEmpDetailsForBonusLeaveUpdationForService]
AS
BEGIN
	SET NOCOUNT ON;
	select TA_Tbl_Employee.Employee_Id,TA_Tbl_Employee.SwipeCardNo,Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota,TA_Tbl_YearSetting.FromDate,
	TA_Tbl_YearSetting.ToDate from Ta_Tbl_EmployeeBonusLeave INNER JOIN TA_Tbl_Employee ON  TA_Tbl_Employee.Employee_Id=Ta_Tbl_EmployeeBonusLeave.EmployeeId
	INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearSetting.YearSettings_Id=Ta_Tbl_EmployeeBonusLeave.YearSettingId
	Where TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_YearSetting.IsActive=1 
	and Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota >0 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNoOfLOP]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNoOfLOP]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	:	Proc_TA_GetRemainingNoOfLOP  10924 ,131,''04/09/2012'',''04/09/2012'',4
Description 	:	Get LOP leave quota of Employees Based on their Employee_Id  
Tables Included :	Ta_Tbl_LeaveApplication,TA_Tbl_LeavePolicy  
			TA_Tbl_LeavePolicyDetails,TA_Tbl_Emp_LeavePolicy
			TA_Tbl_YearSetting
Created By 	:	Prabakaran  
Created On	:	20-Nov-07  
Modified By 	: 
Modified On 	:
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNoOfLOP]  
@Employee_Id int,  
@LeaveType_Id int,
@LeaveFromDate datetime,
@LeaveToDate datetime,
@YearSettingId int 
AS  
if(@LeaveType_Id<>-1)
	BEGIN
		declare @LeaveApplicationCount as decimal(18,1)  
        select @LeaveApplicationCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		where la.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id
		and la.Type in (''LOP'') and la.status not in(''Rejected'')  and la.isdeleted=0 
		if(@LeaveApplicationCount > 0)  
			begin  
				Select isnull(lpd.Max_Lop_Days,0.0)-isnull(sum(la.NumberOfDays),0.0) as RemainingNoOfLOPDays,ISNULL(@LeaveApplicationCount,0) as availed
				from TA_Tbl_LeavePolicyDetails lpd
				inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
				inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
				inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId  
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lpd.LeaveType_Id and la.YearSettings_Id=@YearSettingId
				where la.employee_Id=@Employee_Id and elp.EmployeeId=@Employee_Id
				and la.LeaveType_Id=@LeaveType_Id and ys.IsActive=1 and la.Isdeleted=0 
				and la.Status not in (''Rejected'') 
				and la.Type in (''LOP'') 
				and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
				inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
				where TA_Tbl_YearSetting.IsActive=1
				--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
				and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
				Group by lpd.Max_Lop_Days 
			end  
		else  
			begin  
				Select isnull(lpd.Max_Lop_Days,0.0) as RemainingNoOfLOPDays,ISNULL(@LeaveApplicationCount,0) as availed 
				from TA_Tbl_LeavePolicyDetails lpd
				inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
				inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
				inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId 
				where ys.IsActive=1 and lpd.LeaveType_Id=@LeaveType_Id and elp.EmployeeId=@Employee_Id
				and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
				inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
				where TA_Tbl_YearSetting.IsActive=1
				--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between			TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
				and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			end 
	END 
ELSE
	BEGIN
		    Select lt.LeaveType, isnull(lpd.Max_Lop_Days,0.0)-isnull(sum(la.NumberOfDays),0.0) as RemainingNoOfLOPDays   
			from TA_Tbl_LeavePolicyDetails lpd
			--inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
			inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId  
			inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lpd.LeaveType_Id and la.YearSettings_Id=@YearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id= la.LeaveType_Id 
			where la.employee_Id=@Employee_Id and elp.EmployeeId=@Employee_Id
			and ys.IsActive=1 and la.Isdeleted=0 
			and la.Status not in (''Rejected'') 
			and la.Type in (''LOP'') and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			--and la.Type in (''LOP'') and elp.ToDate in(select TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc) 
			and lpd.LossOfPay=1
			Group by lpd.Max_Lop_Days,lt.LeaveType 
			union
			Select lt.LeaveType,isnull(lpd.Max_Lop_Days,0.0) as RemainingNoOfLOPDays 
			from TA_Tbl_LeavePolicyDetails lpd
			--inner join   TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id
			inner join   TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			inner join  TA_Tbl_LeaveType lt on lt.LeaveType_Id= lpd.LeaveType_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId 
			where ys.IsActive=1 and  elp.EmployeeId=@Employee_Id
			and lpd.LeaveType_Id not in (select LeaveType_Id from Ta_Tbl_LeaveApplication where employee_Id=@Employee_Id and Status not in (''Rejected'') and Type in (''LOP'')and IsDeleted=0 and YearSettings_Id=@YearSettingId )
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc) 
			and lpd.LossOfPay=1
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GettingSMSScheduleDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GettingSMSScheduleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <13-09-2016>
-- Description:	<Getting Schedule Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GettingSMSScheduleDetails]
	-- Add the parameters for the stored procedure here	
	@TemplateName varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here    
	select count(*) from Ta_Tbl_SMSTemplates ST 
	inner join Ta_Tbl_SMSReceivers SR on ST.id=SR.TemplateId
	where TemplateName=@TemplateName and Status=1	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_Ta_GetGlobalHolidayCountForLeaveApplication]  
@FromDate datetime,  
@ToDate datetime  
as  
begin
	SET NOCOUNT ON;
	declare @count as int  
	declare @CheckValue as datetime  
	create table #Temp(FromDate datetime)  
	set @count=0  
	while(@FromDate<=@ToDate)  
	begin  
		set @CheckValue=  
		(select @FromDate as FromDate from ta_tbl_holiday h inner join  
		ta_tbl_yearsetting ys on h.YearSettings_Id=ys.YearSettings_Id   
		where (@FromDate between h.Holiday_FromDate and h.Holiday_ToDate) and h.Holiday_Type=''G'' and   
		h.IsDeleted=0 and ys.IsActive=1)  
		if(@CheckValue>0)  
		insert into #Temp values(@CheckValue)
		set @FromDate=DateAdd(day,1,@FromDate)  
	end  
	select * from #Temp 
	drop table #Temp  
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmployeeShiftDateDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Gopinath.k
-- Create date: 16-Dec-16
-- Description:	To fetch the employee worked details based on date for C/off Entry in THDC
-- Proc_Ta_GetEmployeeShiftDateDetails ''2019/08/10'',''787''

--Proc_Ta_GetEmployeeShiftDateDetails ''2019/08/15'', ''VO357''a
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmployeeShiftDateDetails]
@date nvarchar(20),
@EmployeeCode nvarchar(20)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	DECLARE @dateFormat as int	
	declare @EmployeeID as int
	declare @LeaveStatus as nvarchar(100)
	select @DATEFORMAT=DateFormat,@TIMEFORMAT=TimeFormat from [dbo].[Func_TA_GetDateTimeFormat]()
	declare @GetLevelID as int
	select @GetLevelID=EL.LevelId,@EmployeeID=E.Employee_Id from TA_Tbl_EmployeeLevel EL inner join TA_Tbl_Employee E on E.Employee_Id=EL.EmployeeId where E.Employee_Code_Id=@EmployeeCode
    DECLARE @childID INT 
    ;WITH ParentLevel AS
    (
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
        UNION ALL
        SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
        INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
     )
     SELECT TOP 1 @GetLevelID=id FROM ParentLevel r ORDER BY lvl DESC
     declare @CountRecord as int
     SELECT @CountRecord = count(Employee_Id) FROM TA_Tbl_Employee 
		WHERE Leave_Sanc_Authority = Reporting_To AND Employee_Id = @EmployeeID  
	declare @OTApproval as int
	select @OTApproval=OTApproval from TA_Tbl_ApprovalSettings where CompanyId=@GetLevelID
	DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT,@OtText VARCHAR(MAX)
			SELECT		@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,''00:00'', ISNULL(OtMinHrs, ''00:00'')),
						@FullDayOTMins = DATEDIFF(MI,''00:00'',ISNULL(FullDayOTMinHrs, ''00:00''))
						FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
						WHERE ELP.EmployeeId = @EmployeeID AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
						INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
						WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeID ORDER BY ELP.ToDate DESC)


	IF(@CountRecord > 0)
	BEGIN
		SET @LeaveStatus = ''Forwarded''
	END
	ELSE IF(@CountRecord = 0)
	BEGIN
		SET @LeaveStatus = ''Pending''
	END	
	if(isnull(@OTApproval,0)=0)
	begin
		SET @LeaveStatus = ''Approved''
	end

	print @CountRecord
	print @LeaveStatus

	Select p.Employee_code_id,p.Date,p.Shift_id,
	case when OutTime is not null and OutTime<>''00:00'' then
		CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN  CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,p.OutTime,0)), 114) 
				 ELSE substring(convert(varchar(25),convert(datetime,OutTime)),13,5)+'' ''+ substring(convert(varchar(25),convert(datetime,OutTime)),18,2)
		END 
	end OutTime,
	case when InTime is not null and InTime<>''00:00'' then
		CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,p.InTime,0)), 114) 
				ELSE substring(convert(varchar(25),convert(datetime,InTime)),13,5)+'' ''+ substring(convert(varchar(25),convert(datetime,InTime)),18,2)
		END
	end
	InTime,
	p.NormOt,
	p.OffOt,p.HolOt,E.Employee_FirstName + case when E.Employee_MiddleName is not null then '' '' + cast(E.Employee_MiddleName as varchar(50)) else '' '' end + E.Employee_LastName AS ''Employee Name'',case WHEN p.OtMins >= @HalfDayOTMins THEN ''Reached'' else ''Not Reached'' end as ComStatus,
	CASE when (p.NormOt!=''00:00'') then ''Week Day'' ELSE
	CASE when (p.OffOt!=''00:00'') then ''Weekly Off'' ELSE 
	CASE when (p.HolOt!=''00:00'') then ''Holiday'' ELSE
	''NO OT Record Found'' END END END  as  ''WeekofftypeNormOt'',@GetLevelID ''TopLevelID''
	,E.Employee_Id
	,LD.name as LevelName
	,p.ExtraMins
	,@LeaveStatus as ''OverTimeStatus'',p.Process_Rec_ID,
	case when isnull(@HalfDayOTMins,0)=0 then ''LeavePolicyNotAssign'' else ''Assign'' end as LeavePolicyStatus
	from Ta_tbl_Processeddata p 
	inner join TA_Tbl_Employee E on p.Employee_Code_Id=E.SwipeCardNo
	inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
	inner join Ta_Tbl_levelDetails LD on LD.ID=EL.LevelId where  date = CONVERT(DATETIME,cast(@date as nvarchar(50)), 102) 
	and CompOff_Eligible=1 and OT_Eligible=0 and E.Employee_Code_Id = @EmployeeCode
	--and p.FNAttendanceCode in (''Weekly Off'', ''Holiday'') and p.ANAttendanceCode in (''Weekly Off'', ''Holiday'') --for vaighai client  
	--Select E.Employee_FirstName + case when E.Employee_MiddleName is not null then '' '' + cast(E.Employee_MiddleName as varchar(50)) else '' '' end + E.Employee_LastName AS ''Employee Name'' from Ta_Tbl_employee Where Employee_code_id=@EmployeeCode
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmployeeRequiredPeriod]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmployeeRequiredPeriod]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
Procedure Name : Proc_TA_GetEmployeeRequiredPeriod  202,53 
Description  : Get Eligible days for Employees Based on their Employee_Id and LeaveType_ID    
Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_GetEmployeeRequiredPeriod]    
@Employee_Id bigint,    
@leaveType_Id int,
@LeaveFromDate datetime,
@LeaveToDate datetime    
AS    
declare @test as decimal    
declare @Result as varchar(10)    
if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
BEGIN  
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id 
	and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
ELSE
BEGIN
	set @test=(select ApplicableAfterDays from TA_Tbl_LeavePolicyDetails lpd     
	inner join TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id   
	inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId     
	where lpd.leaveType_Id=@leaveType_Id  and elp.EmployeeId=@Employee_Id and y.IsActive=1 
	and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id 
	--and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
	order by TA_Tbl_Emp_LeavePolicy.ToDate desc))
END
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101))     
if(@test=0)    
 begin    
 set @Result=''N''    
 end    
else    
 begin    
  declare @eligible as decimal    
  if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
  BEGIN    
	  set @eligible=(select distinct (Datediff(d,e.DateOfJoining,getdate()) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id
	  and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) 
	  order by TA_Tbl_Emp_LeavePolicy.ToDate desc))   
  END 
  ELSE
  BEGIN
      set @eligible=(select distinct (Datediff(d,e.DateOfJoining,getdate()) - lpd.ApplicableAfterDays) as EligibleDays   from TA_Tbl_LeavePolicyDetails lpd inner join    
	  TA_TBL_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id     
	  inner join TA_Tbl_Employee e on e.employee_Id=elp.EmployeeId     
	  inner join TA_tbl_YearSetting y on y.YearSettings_Id=elp.YearSettingId    
	  where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@leaveType_Id and y.IsActive=1
	  and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
	  inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
	  where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id
	  --and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) 
	  order by TA_Tbl_Emp_LeavePolicy.ToDate desc)) 
  END
    if (@eligible>=0)    
      begin    
      set @Result=''Y''    
      end       
    else    
     begin    
     set @Result=''R''    
     end    
end    
select @Result as RemainingNoOfLeaves    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetErrorVersionDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetErrorVersionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author			:	A.K.T.MOORTHI
-- Create date	:	24-Dec-2013
-- Description	:	Get The Error Version Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetErrorVersionDetails]
	@PageName VARCHAR(150),
	@TrackingPlatform VARCHAR(150),
	@ErrorMsg VARCHAR(MAX),
	@ErrorText VARCHAR(MAX)
AS
BEGIN
	DECLARE @ClientName VARCHAR(250), @Version VARCHAR(100), @ProductName VARCHAR(100), @ErrStatus VARCHAR(15)
	DECLARE @BugHistory VARCHAR(MAX), @BugId VARCHAR(1000)
	DECLARE @DateTime DATETIME
	SET @ClientName = (SELECT TOP 1 name FROM Ta_Tbl_levelDetails WHERE parentId = 0 AND isDeleted = 0)
	SET @ProductName = ''Timecheck''	
	SET @DateTime = GETDATE()
	SET @ErrStatus = ''New''
	SET @BugHistory = ''''
	SELECT @PageName = displayName FROM TA_Tbl_Page WHERE [path] = @PageName
	SELECT @Version = ApplicationVersionName FROM TA_Tbl_Version
	IF EXISTS(SELECT ErrorMsg FROM TA_Tbl_PageError WHERE ErrorMsg LIKE ''%'' + @ErrorMsg + ''%'' AND PageName LIKE ''%'' + @PageName + ''%'' )
	BEGIN
		SET @ErrStatus = ''Repeatly''
		SELECT 
			@BugHistory = @BugHistory + (CASE WHEN LEN(ErrorId) = 1 THEN (''Bug No: 000'' + CAST(ErrorId AS VARCHAR(1000))) WHEN LEN(ErrorId) = 2 THEN (''Bug No: 00'' + CAST(ErrorId AS VARCHAR(1000))) WHEN LEN(ErrorId) = 3 THEN (''Bug No: 0'' + CAST(ErrorId AS VARCHAR(1000))) ELSE (''Bug No: '' + CAST(ErrorId AS VARCHAR(1000))) END) + '' '' + ErrorMsg + CHAR(13)
		FROM TA_Tbl_PageError WHERE ErrorMsg LIKE ''%'' + @ErrorMsg + ''%'' AND PageName LIKE ''%'' + @PageName + ''%'' 
	END
	IF NOT EXISTS(SELECT ErrorMsg FROM TA_Tbl_PageError WHERE ErrorMsg LIKE ''%'' + @ErrorMsg + ''%'' AND PageName LIKE ''%'' + @PageName + ''%'' )
	BEGIN
		INSERT INTO TA_Tbl_PageError(ErrorMsg, ErrorDetails, PageName, ProductName, ProductVersion, ClientName, TrackingPlatForm, ErrorTime, BugStatus)
				VALUES(@ErrorMsg, @ErrorText, @PageName, @ProductName, @Version, @ClientName, @TrackingPlatform, @DateTime, @ErrStatus)
		SET @BugId = @@IDENTITY
	END
	ELSE
	BEGIN
		SELECT @BugId = MAX(ErrorId) FROM TA_Tbl_PageError WHERE ErrorMsg LIKE ''%'' + @ErrorMsg + ''%'' AND PageName LIKE ''%'' + @PageName + ''%'' 		
	END
	SET @BugId = (CASE WHEN LEN(@BugId) = 1 THEN (''Bug No: 000'' + @BugId) WHEN LEN(@BugId) = 2 THEN (''Bug No: 00'' + @BugId) WHEN LEN(@BugId) = 3 THEN (''Bug No: 0'' + @BugId) ELSE (''Bug No: '' + @BugId) END)
	SET @BugHistory = (CASE WHEN @BugHistory = '''' THEN (@BugId + '' '' + @ErrorMsg) ELSE @BugHistory END)
	SELECT @ErrStatus [BugStatus], REPLACE(CONVERT(VARCHAR(11), @DateTime, 106) , '' '', ''-'') + '' '' + CONVERT(VARCHAR(11), @DateTime, 108)  [DateTime], @ProductName [ProductName], ISNULL(@Version, '''') [Version], ISNULL(@ClientName, '''') ClientName, ''ANGLER'' [AsignTo], @BugId BugId, @BugHistory BugHistory, @TrackingPlatform TrackingPlatform, ISNULL(@PageName, '''') PageName, @ErrorMsg	ErrorMsg, @ErrorText ErrorText
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEquivalentDeviceDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEquivalentDeviceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <10-11-2016 11.29 AM>
-- Description:	<Get Equivalent Device Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEquivalentDeviceDetails]	
	@Type char(1)
AS
BEGIN	
	SET NOCOUNT ON;
	Declare @EntranceType char(3)
	if(@Type=''I'')
	begin
		set @EntranceType=''Out''		
	end
	else if(@Type=''O'')
	begin
		set @EntranceType=''In''
	end
	select stuff((select '','' + Terminal_ReaderId + '''' from [TA_Tbl_Entrance_INOUTDetails] En
	inner join TA_Tbl_Terminal Ter on En.Reader_Id = Ter.Terminal_Id 
	where En.Type = @EntranceType AND Ter.IsDeleted = 0 for XML PATH('''')),1,1,'''') as Terminal_ReaderId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance_Angler]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEntrance_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetEntrance_Angler]
AS
BEGIN
	SET NOCOUNT ON;
Select E.Entrance_Name,T.Terminal_ReaderID from TA_Tbl_Entrance E
Inner Join TA_Tbl_Entrance_INOUTDetails ED On ED.Entrance_Id=E.Entrance_Id
Inner Join TA_Tbl_Terminal T On T.Terminal_Id=ED.Reader_Id
Where ED.Type=''In''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEntrance]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEntrance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Thilakraj C>
-- Create date: <06-Jun-2014>
-- Description:	<Load IN type Entrance in Employee Add Page>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEntrance]
AS
BEGIN
	SET NOCOUNT ON;
Select E.Entrance_Name,T.Terminal_ReaderID from TA_Tbl_Entrance E
Inner Join TA_Tbl_Entrance_INOUTDetails ED On ED.Entrance_Id=E.Entrance_Id
Inner Join TA_Tbl_Terminal T On T.Terminal_Id=ED.Reader_Id
Where ED.Type=''In''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetEmailScheduler_FilterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_Ta_GetEmailScheduler_FilterDetails 14
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetEmailScheduler_FilterDetails] 
	-- Add the parameters for the stored procedure here
	@scheduleId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	Declare @Filters varchar(max)
	Declare @Count int
	Declare @start int
	Declare @TempTable varchar(max)
	Declare @TempTableInsert varchar(max)
	Declare @TempFiltersvalue varchar(max)
	Declare @TempFiltersvalues varchar(max)
	set @TempTable=''Create Table TempFinalFilters(''
	set @TempTableInsert=''Insert into TempFinalFilters values(''
	set @start=1
	select @Filters=Filters  from TA_Tbl_EmailScheduleFilters where ScheduleId=@scheduleId
	select @Count=COUNT(*) from dbo.Split(@Filters,'','')
	Create table #TempFilters(id int identity(1,1),Filters varchar(max))
	insert into #TempFilters select Value from dbo.Split(@Filters,'','')
	--select * from #TempFilters
	while @start<=@Count 
	begin
		select @TempFiltersvalue=replace(substring(Filters,0,charindex(''='',Filters)),''@'',''''),
		@TempFiltersvalues=replace(substring(Filters,charindex(''='',Filters)+1,LEN(Filters)),''~'','','')
		from #TempFilters where id=@start 
		if(@start!=@Count)
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+'' varchar(max),''
			set @TempTableInsert=@TempTableInsert+''''''''+@TempFiltersvalues+'''''',''
		end
	else
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+'' varchar(max)''
			set @TempTableInsert=@TempTableInsert+''''''''+@TempFiltersvalues+''''''''
		end			
		set @start=@start+1
	end
	set @TempTable=@TempTable+'')''
	set @TempTableInsert=@TempTableInsert+'')''	
	Execute(@TempTable)
	Execute(@TempTableInsert)
	select * from TempFinalFilters
	Select ReportType From TA_Tbl_EmailScheduleFilters Where ScheduleId=@scheduleId
	drop table TempFinalFilters
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIds]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_GetEmailIds ''s''
CREATE  PROCEDURE [dbo].[Proc_TA_GetEmailIds] 
@PrefixText as varchar(20)
 AS
SELECT Emp.EmailId,Emp.Employee_FirstName,LD.name FROM TA_Tbl_Employee Emp
INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EmployeeID=Emp.Employee_ID
INNER JOIN Ta_Tbl_levelDetails LD on EL.LevelId=LD.id 
WHERE Emp.Employee_Status = 1 AND Emp.IsDeleted = 0
AND Emp.Employee_Firstname <> ''Administrator'' and Emp.EmailId like @PrefixText + ''%''
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDepartmentMailIds]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDepartmentMailIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_GetDepartmentMailIds 5
CREATE PROCEDURE [dbo].[Proc_TA_GetDepartmentMailIds]
@LevelId int
AS
BEGIN
if(@LevelId<>0)
	BEGIN
	select Id,LevelId,name,ToMailIds,CCMailIds from TA_Tbl_LevelDetails Where ID=@LevelId and IsDeleted=0
	END
else
	BEGIN
	select Id,LevelId,name,ToMailIds,CCMailIds from TA_Tbl_LevelDetails Where LevelId=(Select max(LevelId) from TA_Tbl_LevelDetails where IsDeleted=0)
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetHolidayDetailsByHolidayID]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetHolidayDetailsByHolidayID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetHolidayDetailsByHolidayID] 
	@HolidayID int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	select @dateFormat =DateFormat from dbo.Func_TA_GetDateTimeFormat()
	select	case when Holiday_Type=''G'' then ''Global Holiday''
				when Holiday_Type=''Y'' then ''Restricted Holiday'' 
			end as Holiday_Type	
	,Holiday_Description,
	convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,
	convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate
	from TA_Tbl_Holiday where Holiday_Id=@HolidayID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationCancellation]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationCancellation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_GetLeaveApplicationCancellation 10
Description		:	Get Leave Application Details of Employees Based on their LeaveApplication_Id
Tables Included		:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationCancellation]
@LeaveApplication_Id int =null
as
declare @strLeaveType as nvarchar(50)
BEGIN
SET NOCOUNT ON;
set @strLeaveType=''Leave''
if(@strLeaveType=''Leave'' or @strLeaveType=''LOP'')
begin
	select la.Type as [Leave Category], (lt.LeaveType) as [Leave Type],la.Leave_FromDate as [LeaveFrom],la.Leave_ToDate as [LeaveTo],'''' as [From],'''' as [To],la.Leave_SessionFrom as [Session From],la.Leave_SessionTo as [Session To],la.NumberOfDays as [No of Days],la.Status as Status,la.IsDeleted as IsDeleted,la.IntimationType as IntimationType from  TA_Tbl_LeaveApplication la inner join  TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id where la.LeaveApplication_Id = @LeaveApplication_Id and lt.Isdeleted=0 And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
else if(@strLeaveType=''Comp Off'' or @strLeaveType=''ESI'')
begin
select la.LeaveApplication_Id as LeaveApplication_Id,
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,
e.Employee_Code_Id as Employee_Code_Id,
e.emailId as emailId,
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,
la.Leave_ApplicationDate as Leave_ApplicationDate,
la.LeaveType_id as LeaveType_id,
la.Type as Type,
(''Others '' + ''/'' +la.Type) as LeaveType,
la.Leave_FromDate as Leave_FromDate,
la.Leave_ToDate as Leave_ToDate,
la.Leave_SessionFrom as Leave_SessionFrom,
la.Leave_SessionTo as Leave_SessionTo,
la.NumberOfDays as NumberOfDays,
la.Reason as Reason,
la.Status as Status,
la.IsDeleted as IsDeleted,
la.Remarks as Remarks,
la.IsBorrow as IsBorrow,ld.name as LevelName, ld.id as levelid,
la.IntimationType as IntimationType
 from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
where la.LeaveApplication_Id = @LeaveApplication_Id
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
if(@strLeaveType=''Restricted Holiday'')
begin
select la.LeaveApplication_Id as LeaveApplication_Id,
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,
e.Employee_Code_Id as Employee_Code_Id,
e.emailId as emailId,
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,
la.Leave_ApplicationDate as Leave_ApplicationDate,
la.LeaveType_id as LeaveType_id,
la.Type as Type,
(la.Type + '' / '' +h.Holiday_Description) as LeaveType,
la.Leave_FromDate as Leave_FromDate,
la.Leave_ToDate as Leave_ToDate,
la.Leave_SessionFrom as Leave_SessionFrom,
la.Leave_SessionTo as Leave_SessionTo,
la.NumberOfDays as NumberOfDays,
la.Reason as Reason,
la.Status as Status,
la.IsDeleted as IsDeleted,
la.Remarks as Remarks,
la.IsBorrow as IsBorrow,ld.name as LevelName, ld.id as levelid,
la.IntimationType as IntimationType 
from  TA_Tbl_LeaveApplication la  
inner join  TA_Tbl_Holiday h  
on la.LeaveType_Id = h.Holiday_Id  
inner join TA_Tbl_Employee e 
on e.Employee_Id=la.Employee_Id
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
where la.LeaveApplication_Id = @LeaveApplication_Id and h.Isdeleted=0
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name  : Proc_TA_GetLeaveApplicationByLeaveApplicationId 7601 
Description  : Get Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included  : TA_Tbl_LeaveApplication  
Created By  : Prabakaran  
Created On  : 24-Jul-07  
Modified By  :   A.K.T.MOORTHI
Modified On  :   24-JUN-2013
Description		:	Add Information To Column In Query
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId_Angler] 
@LeaveApplication_Id int =null 
as  
SET NOCOUNT ON;
declare @strLeaveType as nvarchar(50)  
BEGIN  
set @strLeaveType=''Leave''  
if(@strLeaveType=''Leave'')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
case la.Type when ''Comp Off'' then ''Others'' else lt.LeaveType end as LeaveType,
--(lt.LeaveType) as LeaveType,  
la.Leave_FromDate as LeaveFrom,  
la.Leave_ToDate as LeaveTo,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID ,la.CheckedIDs  ,
la.InformTo
from  TA_Tbl_LeaveApplication la 
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
left outer join TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id  and lt.Isdeleted=0 
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId  
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId 
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id     
where la.LeaveApplication_Id = @LeaveApplication_Id  and la.IsDeleted=0 and la.Type!=''LOP''  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
union all  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
(''Others '') as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID   ,la.CheckedIDs ,la.InformTo
from  TA_Tbl_LeaveApplication la 
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id   
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId 
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id  and la.IsDeleted=0 and la.Type=''LOP''  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
select * from TA_Tbl_LeaveApplicationMaster where LeaveApplication_Id=@LeaveApplication_Id  and Isdeleted=0
end  
else if(@strLeaveType=''Comp Off'' or @strLeaveType=''ESI'')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
(''Others '' + ''/'' +la.Type) as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName,  
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID ,la.CheckedIDs  ,la.InformTo 
from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId  
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
end  
if(@strLeaveType=''Restricted Holiday'')  
begin  
select la.LeaveApplication_Id as LeaveApplication_Id,  
la.Employee_Id as Employee_Id,la.Emp_Id,la.IntimationType,  
e.Employee_Code_Id as Employee_Code_Id,  
e.emailId as emailId,  
(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,  
la.Leave_ApplicationDate as Leave_ApplicationDate,  
la.LeaveType_id as LeaveType_id,  
la.Type as Type,  
(la.Type + '' / '' +h.Holiday_Description) as LeaveType,  
la.Leave_FromDate as Leave_FromDate,  
la.Leave_ToDate as Leave_ToDate,  
la.Leave_SessionFrom as Leave_SessionFrom,  
la.Leave_SessionTo as Leave_SessionTo,  
la.NumberOfDays as NumberOfDays,  
la.Reason as Reason,  
la.Status as Status,  
la.IsDeleted as IsDeleted,  
la.Remarks as Remarks,  
la.IsBorrow as IsBorrow,
ld.name as LevelName, 
ld.id as levelid,
lam.CCMail as CCMail,
lam.LeaveAvailedYear as LeaveAvailedYear,
lam.LeaveAvailedMonth as LeaveAvailedMonth,
ED.DesignationID  ,la.CheckedIDs   , la.InformTo
from  TA_Tbl_LeaveApplication la  
inner join TA_Tbl_LeaveApplicationMaster lam on lam.LeaveApplication_Id = la.LeaveApplication_Id     
inner join  TA_Tbl_Holiday h on la.LeaveType_Id = h.Holiday_Id    
inner join TA_Tbl_Employee e  on e.Employee_Id=la.Employee_Id  
inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0  
And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
And ED.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)  
end  
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name		:	Proc_TA_GetLeaveApplicationByLeaveApplicationId 1094
Description		:	Get Leave Application Details of Employees Based on their LeaveApplication_Id
Tables Included		:	TA_Tbl_LeaveApplication 
Created By		:	Prabakaran
Created On		:	24-Jul-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveApplicationByLeaveApplicationId]
@LeaveApplication_Id int =null
as
declare @strLeaveType as nvarchar(50)
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as INT
	set @dateFormat =(Select DateFormat from dbo.Func_TA_GetDateTimeFormat())
	set @strLeaveType=(select Type from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and isdeleted=0)	
	if(@strLeaveType=''Leave'' or @strLeaveType=''LOP'')
		begin
			select E.Employee_Code_Id as employeeid,
			la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end 
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			(lt.LeaveType + '' / ''  + la.Type) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_LeaveType lt   
			on la.LeaveType_Id = lt.LeaveType_Id
			inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id   
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and lt.Isdeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
	else if(@strLeaveType=''Comp Off'' or @strLeaveType=''ESI'')
		begin
			select E.Employee_Code_Id as employeeid,la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end 
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			(''Others '' + ''/'' +la.Type) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority
			from  TA_Tbl_LeaveApplication la  
			inner join TA_Tbl_Employee e on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
	if(@strLeaveType=''Restricted Holiday'')
		begin
			select E.Employee_Code_Id as employeeid,la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			e.Employee_Code_Id as Employee_Code_Id,
			e.emailId as emailId,
			(e.Employee_FirstName + '' '' + isnull(e.Employee_LastName,'''')) as Employee_FirstName,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ApplicationDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ApplicationDate, @dateFormat) end
			as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			(la.Type + '' / '' +h.Holiday_Description) as LeaveType,
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_FromDate, @dateFormat) end as Leave_FromDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, la.Leave_ToDate, @dateFormat) end 
			as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			ld.name as LevelName,
			la.YearSettings_Id,
			Mobile_Number,
			Reporting_To,
			Leave_Sanc_Authority		
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_Holiday h  
			on la.LeaveType_Id = h.Holiday_Id  
			inner join TA_Tbl_Employee e 
			on e.Employee_Id=la.Employee_Id
			inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId
			inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0
			And el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveTypeDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_GetLeaveTypeDetails ''SuperAdmin''
CREATE  Proc [dbo].[Proc_TA_GetLeaveTypeDetails]
(    
    @UserGroupName nVarchar(250)    
)    
AS      
Begin    
	SET NOCOUNT ON; 
	IF(@UserGroupName = ''SuperAdmin'')    
		BEGIN             
			SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,0 as flag,isnull(isWFH,0) as isWFH into #tempLeaveTypes FROM TA_Tbl_LeaveType order by LeaveType_Id
			update #tempLeaveTypes set flag=1 from #tempLeaveTypes inner join
		       (
					select lpd.LeaveType_Id from TA_Tbl_LeavePolicyDetails lpd inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 					
				)as LeaveTypeDetails on #tempLeaveTypes.LeaveType_Id=LeaveTypeDetails.LeaveType_Id
			update #tempLeaveTypes set flag=1 from #tempLeaveTypes TLT inner join TA_Tbl_LeaveApplication LA on TLT.LeaveType_Id=LA.LeaveType_id 
			select * from #tempLeaveTypes 
		END    
	ELSE    
		BEGIN            
			SELECT LeaveType_Id,LeaveType,LeaveDescription,CountFactor,IsDeleted,0 as flag,isnull(isWFH,0) as isWFH into #tempLeaveTyp FROM TA_Tbl_LeaveType Where IsDeleted=0 order by LeaveType_Id
			update #tempLeaveTyp set flag=1 from #tempLeaveTyp inner join
		       (
					select lpd.LeaveType_Id from TA_Tbl_LeavePolicyDetails lpd inner join TA_Tbl_LeavePolicy lp on lp.Policy_Id=lpd.Policy_Id 
				)as LeaveTypeDetails on #tempLeaveTyp.LeaveType_Id=LeaveTypeDetails.LeaveType_Id
			update #tempLeaveTyp set flag=1 from #tempLeaveTyp TLT inner join TA_Tbl_LeaveApplication LA on TLT.LeaveType_Id=LA.LeaveType_id 
			select * from #tempLeaveTyp 
		END
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelIdForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLevelIdForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		R.MANIKANDAN
-- CREATE DATE: 05-01-2015
-- DESCRIPTION:	GETTING LEVEL ID FOR PROCESSING
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLevelIdForService]
	@INCLK_EMPID VARCHAR(50),
	@INCLK_DATE DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @LEVELID INT	
	SELECT @LEVELID=L.LEVELID FROM TA_TBL_EMPLOYEE E INNER JOIN TA_TBL_EMPLOYEELEVEL L ON L.EMPLOYEEID = E.EMPLOYEE_ID 
	WHERE SWIPECARDNO =  @INCLK_EMPID AND ISDELETED = 0 AND 
	L.EFFECTIVEDATE=(SELECT TOP 1 EFFECTIVEDATE FROM TA_TBL_EMPLOYEELEVEL WHERE EMPLOYEEID=E.EMPLOYEE_ID AND 
	EFFECTIVEDATE <=CONVERT(DATETIME,@INCLK_DATE, 102) ORDER BY EFFECTIVEDATE DESC)	
	WHILE((SELECT PARENTID FROM TA_TBL_LEVELDETAILS WHERE ID=@LEVELID)!=0) 
		BEGIN 
			SELECT @LEVELID=PARENTID FROM TA_TBL_LEVELDETAILS WHERE ID=@LEVELID
		END
	SELECT isnull(@LEVELID,0) AS ID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetLevelDetailsForHoiday]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetLevelDetailsForHoiday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Modified Author:		<R.Manikandan>
-- Modified date: <25-11-2016 11.08>
-- Description:	<Description,,>
-- [Proc_Ta_GetLevelDetailsForHoiday]''Superadmin''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetLevelDetailsForHoiday]
	@UsergroupName nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	select ld.id,ParentID,Name from ta_tbl_leveldetails ld inner join ta_tbl_levelrights lr on ld.id=lr.LevelId
	inner join TA_Tbl_Usergroup ug on lr.GroupId=ug.groupId
	where ld.isdeleted=0 and groupName=@UsergroupName order by parentid,Name
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLevelD]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLevelD]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetLevelD]
@ParentId int
AS
BEGIN
Select LevelId from Ta_Tbl_levelDetails where id=@ParentId	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getMinimumLevel]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getMinimumLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getMinimumLevel]
As
BEGIN
	select min(id) as minID  from ta_tbl_leveldetails where isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarData]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMyCalendarData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_GetMyCalendarData  5 ,''2019-05-01''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetMyCalendarData]
	-- Add the parameters for the stored procedure here
	@EmployeeID as int,
	@ShiftDate as nvarchar(100)
	--@UserGroupName as nvarchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempMyCalendar(EmployeeCodeId varchar(50),Date nvarchar(20),ShiftName nvarchar(100),HrsWork nvarchar(20),InTime nvarchar(20),OutTime nvarchar(20),LateIn nvarchar(20),EarlyOut nvarchar(20),BrackHrs nvarchar(20),LunchHrs nvarchar(20),AttendanceData nvarchar(100),Shift_TotalWorkingHours nvarchar(10),BreakMins int,HrsWrkMins int)
    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	Declare @StartDate as nvarchar(20)
	Declare @EndDate as nvarchar(20)
	SELECT @StartDate=DATEADD(month, DATEDIFF(month, 0, @ShiftDate), 0)
	select @EndDate=DateAdd(d,-1,DATEADD(M,1,@StartDate))
	declare @query as nvarchar(Max) 
	declare @queryInnerJoin as nvarchar(Max) 
	declare @queryWhere as nvarchar(Max) 
	set @query=''''
	set @queryInnerJoin=''''
	set @queryWhere=''''
	set @query=''select  ta_tbl_processedData.Employee_code_id,
	case when ''+CONVERT(varchar,@dateFormat) +''=106 then 
		REPLACE(CONVERT(VARCHAR, Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')  
	else 
		CONVERT(VARCHAR, Date, ''+CONVERT(varchar,@dateFormat)+'') 
	end AS Date,
	isnull(
	SH.Shift_ShortName + ''''('''' + 
		case	when ''''''+CONVERT(varchar,@TimeFormat)+'''''' =''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,SH.Shift_StartTime,0)), 114)
				else
					SH.Shift_StartTime
		end  + '''' - '''' + 
		case	when ''''''+CONVERT(varchar,@TimeFormat)+'''''' =''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,SH.Shift_EndTime,0)), 114)
				else
					SH.Shift_EndTime
		end 
	+ '''')'''',''''Weekly Off'''') as shiftName,
		
		case when  HrsWork is null or HrsWork=''''00:00'''' then ''''-'''' else 
		HrsWork
		
		end HrsWork,
		
		
		case	when InTime<>''''00:00'''' then	
		case	when ''''''+CONVERT(varchar,@TimeFormat)+'''''' =''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114)
				else
					InTime
		end 
						else ''''-''''
		end	InTime,
		case	when OutTime<>''''00:00'''' then	
		case	when ''''''+CONVERT(varchar,@TimeFormat)+'''''' =''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114)
				else
					OutTime
		end 
						else ''''-''''
		end	OutTime , 
		case when  LateIn is null or LateIn=''''00:00'''' then ''''-'''' else LateIn end LateIn ,
		case when  EarlyOut is null or EarlyOut=''''00:00'''' then ''''-'''' else EarlyOut end EarlyOut ,
		BreakHrs,LunchHrs, 
		(FNAttendanceCode + '''' / '''' + ANAttendanceCode) as ''''Attendancedetails'''',
		SH.Shift_TotalWorkingHours,0,
		case when  HrsWork is null or HrsWork=''''00:00'''' then 0 else	 SUBSTRING(HrsWork,0,charindex('''':'''',HrsWork))*60+SUBSTRING(HrsWork,charindex('''':'''',HrsWork)+1,LEN(HrsWork)) end
		from ta_tbl_employee ''
		set @queryInnerJoin =@queryInnerJoin + '' 
		inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo 
		inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId 
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id  
		inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId 
		inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId 
		inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId left join TA_Tbl_Shift SH on ta_tbl_processedData.Shift_Id=SH.Shift_Id ''
		set @queryWhere = @queryWhere + '' where TA_Tbl_Employee.Report_Exclude=0 and Ta_tbl_employee.Employee_Id=''+cast(@EmployeeID as nvarchar(20)) +'' and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Employee_status=1 
		And ta_tbl_processedData.date between  ''''''+cast(@ShiftDate as nvarchar(20)) + ''''''  AND ''''''+cast(@ShiftDate as nvarchar(20)) + '''''' 
		group by  ta_tbl_processedData.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName,Date,InTime,OutTime,LateIn,
		EarlyOut,LunchHrs,SH.Shift_ShortName,SH.Shift_StartTime,SH.Shift_EndTime,HrsWork,FNAttendanceCode,ANAttendanceCode,SH.Shift_TotalWorkingHours,BreakHrs''
		insert into #TempMyCalendar
		Exec(@query + @queryInnerJoin + @queryWhere)
		
		declare @SQLMonthdata as nvarchar(MAX)
		set @SQLMonthdata=''''
		set @SQLMonthdata = @SQLMonthdata + ''select  ''''Present'''' = sum( CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''	
		set @SQLMonthdata = @SQLMonthdata + '' ''''Absent'''' = sum( CASE FNAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''  
		set @SQLMonthdata = @SQLMonthdata + '' ''''WeeklyOff'''' = sum( CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''  
		set @SQLMonthdata = @SQLMonthdata + '' ''''Holiday'''' = sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''  
		set @SQLMonthdata = @SQLMonthdata + '' ''''Leave'''' = SUM(CASE WHEN FNAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''') THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + 
			SUM( CASE WHEN ANAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''') THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),DATENAME(month, DATEADD(month, 0, ''''''+@StartDate+'''''')) as MonthName from ta_tbl_employee ''
		set @queryInnerJoin=''''
		set @queryInnerJoin =@queryInnerJoin + '' inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo 
		inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId 
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id  
		inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId 
		inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId 
		inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId ''
		--left join TA_Tbl_Shift SH on ta_tbl_processedData.Shift_Id=SH.Shift_Id ''
		set @queryWhere=''''
			set @queryWhere = @queryWhere + '' where TA_Tbl_Employee.Report_Exclude=0 and Ta_tbl_employee.Employee_Id=''+cast(@EmployeeID as nvarchar(20)) +'' and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1 
		  And ta_tbl_processedData.date between  ''''''+cast(@StartDate as nvarchar(20)) + ''''''  AND ''''''+cast(@EndDate as nvarchar(20)) + ''''''''
		--insert into #TempMyCalendar
		--print @SQLMonthdata + @queryInnerJoin + @queryWhere
		select * from #TempMyCalendar
		Exec(@SQLMonthdata + @queryInnerJoin + @queryWhere)
		--exec(@SQLMonthdata)
		drop table #TempMyCalendar
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <Aug 16 2019,,>
-- Description:	<This procedure works for getclock date for auto shift in 1 weeklyoff scenario>
-- ============================================
--Aug 2 -- 9 30 pm
--Aug 3 -- 07 20 am
-- Proc_TA_GetClockDateForAutoShiftEmployee ''1001'',''2019-08-01 00:00:00.000'',''11:30:00'',''1''


CREATE PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee_Old]
	@SwipeCardNo varchar(max), 
	@inClk_Date datetime, 
	@inClk_Time varchar(20),
	@CompanyId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DateOfJoining datetime
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	DECLARE @SHIFTID INT
	Declare @PrevEndtime  Datetime	
	set @SHIFTID =0
	CREATE TABLE #TEMP (SHIFTID INT)
	Select @DateOfJoining = DateOfJoining,@EMPLOYEEAUTOID =Employee_Id from TA_Tbl_Employee where SwipeCardNo =  @SwipeCardNo and Isdeleted=0
	if(@inClk_Date > @DateOfJoining)
	Begin
		Declare @PrevDay datetime
		Declare @PrevSatrtTime datetime
			
		DECLARE @QUERY VARCHAR(2000)   
		Declare @WeekoffHours varchar(20)
		
		SET @SHIFTID=0
			
		SET  @PrevDay = DATEADD(d, -1, @inClk_Date)
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		select @WeekoffHours = WeeklyOffStartHours from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
		
		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
		SET @QUERY = ''	SELECT (TSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
						WHERE TSA.[YEAR]= '' + @YEAR + ''  AND  TSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = ''''''+ @EMPLOYEEAUTOID +'''''' ''	
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID,0) 
		DELETE FROM #TEMP
		
		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
		IF(@SHIFTID = 0)
			BEGIN
				SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
		--Check Starttime and End time for weeklyoff--
		if(@SHIFTID=-1)
		begin
			SET  @PrevDay = DATEADD(d, -2, @inClk_Date)
			SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
							WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
			INSERT INTO #TEMP EXEC(@QUERY)
			SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
			SET @SHIFTID = ISNULL(@SHIFTID ,0)
			DELETE FROM #TEMP	
			select @PrevEndtime= @PrevDay+convert(datetime,Shift_StartTime)+convert(datetime,MaxShiftWorkHours) 
			from TA_Tbl_Shift where Shift_Id = @SHIFTID
			set	@PrevSatrtTime=dateadd(minute,1,@PrevEndtime)
			set @PrevEndtime=@PrevSatrtTime+convert(datetime,@WeekoffHours)  -- weeklyoff hours defined in shift setting need to be added.
		end
		else if(@SHIFTID=0) --leave , lop days for auto shift configured employee
		begin
				IF EXISTS(select FNAttendanceCode from TA_Tbl_ProcessedData where Date = @PrevDay and Employee_Code_Id=@SwipeCardNo
				and FNAttendanceCode not in (''Present'', ''Weekly Off'', ''Holiday'')
				and ANAttendanceCode not in (''Present'', ''Weekly Off'', ''Holiday''))
				Begin
					select @PrevDay = @inClk_Date
					select @PrevDay
					
					set @day =DATEPART(DAY,@PrevDay)
					SET @YEAR=DATEPART(YEAR,@PrevDay)
					SET @MONTH=DATEPART(MONTH,@PrevDay)	
					SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
									WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
					INSERT INTO #TEMP EXEC(@QUERY)
					SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
					DELETE FROM #TEMP
					if(@SHIFTID=-1) --for weeklyoff
					begin
						set @SHIFTID=0;
					end
					if(@SHIFTID=0)
					begin
						goto GetShift;
					end
					goto UpdateShift_Permanent;
				End				
		end
		else
		begin
			select @PrevSatrtTime = @PrevDay+convert(datetime,Shift_StartTime), 
			@PrevEndtime= @PrevDay+convert(datetime,Shift_StartTime)+convert(datetime,MaxShiftWorkHours) 
			from TA_Tbl_Shift where Shift_Id = @SHIFTID


		end
		
		--select @PrevSatrtTime,@PrevEndtime
		IF(@inClk_Date+@inClk_Time between @PrevSatrtTime and @PrevEndtime)
		BEGIN
			SELECT @PrevDay
		END
		ELSE
		BEGIN
			--1.31 pm AND OUT CAME ON THE SAME DAY.	
			
			--Aug 1 9:30 pm to Aug 2 07:00 am	Shift name 930
			--Aug 2 03:00 pm to Aug 2 09:30 pm  Shift name 3pm
			--Aug 3 weeklyoff but still he came for work means Initial shift Id = -1
			-- Aug 3 07am Aug 3 03:00pm so new shift id will be allocated through autoshift shifts.
			select @PrevDay = @inClk_Date
			select @PrevDay
			set @SHIFTID=0;
			set @day =DATEPART(DAY,@PrevDay)
			SET @YEAR=DATEPART(YEAR,@PrevDay)
			SET @MONTH=DATEPART(MONTH,@PrevDay)	
			IF(@SHIFTID = 0)  -- It runs for current day , whatever shift id updated in permenent shift table will be taken here. If shift id not present, new shift id wil be find out 
			BEGIN
				SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
			goto GetShift;
			goto UpdateShift_Permanent;
		End		
	End	
	Else	 
	Begin
		select @PrevDay = @inClk_Date
		select @PrevDay
		
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
						WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID ,0)
		DELETE FROM #TEMP
		if(@SHIFTID=-1)
		begin
			set @SHIFTID=0;
		end
		if(@SHIFTID=0)
		begin
			goto GetShift;
		end
		goto UpdateShift_Permanent;
	End 
	
	GetShift:
	begin
		--set @SHIFTID=0
		IF(@inClk_Time !=''00:00'' and @SHIFTID = 0 and @SHIFTID != -1)
		BEGIN
			Declare @Count int
			set @Count=0;
			Create Table #TempAutoShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40));
			Create Table #TempAutoShiftSingleShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40), shiftstartTime varchar(40), minutesdiffStart bigint, orderby int);
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId1,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId1 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId2,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId2 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId3,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId3 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId4,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId4 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId5,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId5 !=0	
			select @Count = isnull(count(EmpId),0)from #TempAutoShift				
			IF(@Count = 1)
			BEGIN
				select @SHIFTID = ISNULL(ShiftId,0)	from #TempAutoShift							
			END
			--ELSE IF(@Count = 0)
			--BEGIN
			--	set @SHIFTID = 0						
			--END
			ELSE
			BEGIN
				insert into #TempAutoShiftSingleShift 
				select b.EmpId,b.ShiftId,b.clkDate, b.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
				RANK()over(order by diff) from 
				(
					select a.EmpId,a.ShiftId,a.clkDate, a.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
					case when datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)<0 then -datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)
					else datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime) end as diff
					from #TempAutoShift a
					inner join TA_Tbl_Shift b on b.Shift_Id = a.ShiftId 
				)as b		

				declare @loopcount int
				Declare @ShiftNewtime datetime
				set @loopcount = 1
				while (@loopcount <= 5)
				Begin		
						select @ShiftNewtime = clkDate+shiftstartTime from #TempAutoShiftSingleShift  where orderby=@loopcount	
						if(@ShiftNewtime < @PrevEndtime)
						Begin
							set @loopcount = @loopcount + 1;													
						End			
						else
						begin
							select @SHIFTID = ShiftId from #TempAutoShiftSingleShift  where orderby=@loopcount	
							break;					
						End			
				End								
			END
			DROP TABLE #TempAutoShiftSingleShift
			DROP TABLE #TempAutoShift
		END
	end	
	UpdateShift_Permanent:
	Begin
		DECLARE @DynamicQuery VARCHAR(MAX)
		SELECT @year=DATEPART(YEAR,@PrevDay),@month=DATEPART(MONTH,@PrevDay),@day=DATEPART(DAY,@PrevDay) 	
		SET @DynamicQuery =''''
		--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
		IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID)
		Begin
			if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EMPLOYEEAUTOID)
			begin
				SET @DynamicQuery =@DynamicQuery +''update TA_Tbl_PermanentShiftAllocation set day''+CONVERT(VARCHAR(2),@day)+''shift=''+CONVERT(VARCHAR(2),@SHIFTID)+ '' where
				month=''+CONVERT(VARCHAR(2),@month)+'' and year=''+CONVERT(VARCHAR(4),@year)+'' and employeeid=''+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)
			end
			else
			begin
				SET @DynamicQuery =@DynamicQuery +''insert into TA_Tbl_PermanentShiftAllocation (day''+CONVERT(VARCHAR(2),@day)+''shift,month,year,employeeid,Emp_id,dateshift)
				values(''+CONVERT(VARCHAR(2),@SHIFTID)+ '',''+CONVERT(VARCHAR(2),@month)+'',''+CONVERT(VARCHAR(4),@year)+'',''+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)+'',1,''''''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+'''''')''
			end
			exec (@DynamicQuery)
		End
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <Aug 16 2019,,>
-- Description:	<This procedure works for getclock date for auto shift in 2 weeklyoff scenario>
--
-- =============================================
--Aug 2 -- 9 30 pm
--Aug 3 -- 07 20 am
-- Proc_TA_GetClockDateForAutoShiftEmployee ''1001'',''2019-08-01 00:00:00.000'',''11:30:00'',''1''
-- Proc_TA_GetClockDateForAutoShiftEmployee ''1001'',''2019-08-01 00:00:00.000'',''19:30:00'',''1''
--Proc_TA_GetClockDateForAutoShiftEmployee ''21'',''2019-12-20 00:00:00.000'',''06:55 AM'',''1''    
--Proc_TA_GetClockDateForAutoShiftEmployee ''21'',''2019-12-21 00:00:00.000'',''09:55 PM'',''1''    
CREATE PROCEDURE [dbo].[Proc_TA_GetClockDateForAutoShiftEmployee]
	@SwipeCardNo varchar(max), 
	@inClk_Date datetime, 
	@inClk_Time varchar(20),
	@CompanyId int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @DateOfJoining datetime
	Declare @day int
	DECLARE @YEAR VARCHAR(5)
	DECLARE @MONTH VARCHAR(5)	
	Declare @EMPLOYEEAUTOID VARCHAR(50)
	DECLARE @SHIFTID INT
	Declare @PrevEndtime  Datetime	
	set @SHIFTID =0
	CREATE TABLE #TEMP (SHIFTID INT)
	Select @DateOfJoining = DateOfJoining,@EMPLOYEEAUTOID =Employee_Id from TA_Tbl_Employee where SwipeCardNo =  @SwipeCardNo and Isdeleted=0
	if(@inClk_Date > @DateOfJoining)
	Begin
		Declare @PrevDay datetime
		Declare @PrevSatrtTime datetime
			
		DECLARE @QUERY VARCHAR(2000)   
		Declare @WeekoffHours varchar(20)
		
		SET @SHIFTID=0
			
		SET  @PrevDay = DATEADD(d, -1, @inClk_Date)
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		select @WeekoffHours = WeeklyOffStartHours from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
		
		-- CHECK SHIFT IN TEMPORARY SHIFT ALLOCATION
		SET @QUERY = ''	SELECT (TSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_TEMPORARYSHIFTALLOCATION TSA					
						WHERE TSA.[YEAR]= '' + @YEAR + ''  AND  TSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = ''''''+ @EMPLOYEEAUTOID +'''''' ''	
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID,0) 
		DELETE FROM #TEMP
		Declare @WeekOffcount  int
		set @WeekOffcount=1
		-- CHECK SHIFT IN PERMANENT SHIFT ALLOCATION IF NOT IN TEMPORARY
		IF(@SHIFTID = 0)
			BEGIN
				SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
		--Check Starttime and End time for weeklyoff--
		if(@SHIFTID=-1)
		begin
			Declare @i int
			Declare @PreviousOneMoreDay datetime
			SET  @PreviousOneMoreDay = DATEADD(d,-1, @PrevDay)
			set @i=1
			while @i>0
			begin				
				  --dec 18 shift 5     
				SET @QUERY = '' SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),DATEPART(DAY,@PreviousOneMoreDay)) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA           
					WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''    
				INSERT INTO #TEMP EXEC(@QUERY)  
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)    
				SET @SHIFTID = ISNULL(@SHIFTID ,0)    
				DELETE FROM #TEMP  
				set @WeekOffcount=@WeekOffcount+1
				if(@SHIFTID!=-1)
				begin
					set @i=-1
					break
				end				
				set @PreviousOneMoreDay=dateadd(d,-@i,@PreviousOneMoreDay)
				set @i=@i+1	
			end
  
			if(@SHIFTID!=-1)  
			begin  
				Declare @Start int
				set @Start=1
				Declare @MaxShiftWorkHours datetime
				Declare @Shift_StartTime datetime
				select @Shift_StartTime=convert(datetime,Shift_StartTime),@MaxShiftWorkHours=convert(datetime,MaxShiftWorkHours) 
				from TA_Tbl_Shift where Shift_Id = @SHIFTID			
				set @PrevSatrtTime= @PreviousOneMoreDay+@Shift_StartTime
				while @WeekOffcount>=@Start
				begin
					if(@Start=1)
					begin					
						set @PrevEndtime=@PrevSatrtTime+@WeekoffHours					
					end
					else
					begin
						set @PrevSatrtTime=DATEADD(minute,1,@PrevEndtime)
						set @PrevEndtime=@PrevEndtime+@WeekoffHours
					end
					--select @PrevSatrtTime,@PrevEndtime 
					set @Start=@Start+1
				end			
		   End 		   
		end
		else if(@SHIFTID=0) --leave , lop days for auto shift configured employee
		begin
				IF EXISTS(select FNAttendanceCode from TA_Tbl_ProcessedData where Date = @PrevDay and Employee_Code_Id=@SwipeCardNo
				and FNAttendanceCode not in (''Present'', ''Weekly Off'', ''Holiday'')
				and ANAttendanceCode not in (''Present'', ''Weekly Off'', ''Holiday''))
				Begin
					select @PrevDay = @inClk_Date
					select @PrevDay
					
					set @day =DATEPART(DAY,@PrevDay)
					SET @YEAR=DATEPART(YEAR,@PrevDay)
					SET @MONTH=DATEPART(MONTH,@PrevDay)	
					SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
									WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
					INSERT INTO #TEMP EXEC(@QUERY)
					SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
					SET @SHIFTID = ISNULL(@SHIFTID ,0)
					DELETE FROM #TEMP
					if(@SHIFTID=-1) --for weeklyoff
					begin
						set @SHIFTID=0;
					end
					if(@SHIFTID=0)
					begin
						goto GetShift;
					end
					goto UpdateShift_Permanent;
				End				
		end
		else
		begin
			select @PrevSatrtTime = @PrevDay+convert(datetime,Shift_StartTime), 
			@PrevEndtime= @PrevDay+convert(datetime,Shift_StartTime)+convert(datetime,MaxShiftWorkHours) 
			from TA_Tbl_Shift where Shift_Id = @SHIFTID


		end
		--select @PrevSatrtTime,@PrevEndtime 
		
		IF(@inClk_Date+@inClk_Time between @PrevSatrtTime and @PrevEndtime)
		BEGIN
			if(@WeekOffcount>1)
			begin
				SELECT @PrevDay=dateadd(d,-(@WeekOffcount-1),@inClk_Date)
				set @SHIFTID=-1
				SELECT @PrevDay
			end
			else 
			begin
				SELECT @PrevDay    
			end
		END
		ELSE
		BEGIN
			--1.31 pm AND OUT CAME ON THE SAME DAY.	
			
			--Aug 1 9:30 pm to Aug 2 07:00 am	Shift name 930
			--Aug 2 03:00 pm to Aug 2 09:30 pm  Shift name 3pm
			--Aug 3 weeklyoff but still he came for work means Initial shift Id = -1
			-- Aug 3 07am Aug 3 03:00pm so new shift id will be allocated through autoshift shifts.
			select @PrevDay = @inClk_Date
			select @PrevDay
			set @SHIFTID=0;
			set @day =DATEPART(DAY,@PrevDay)
			SET @YEAR=DATEPART(YEAR,@PrevDay)
			SET @MONTH=DATEPART(MONTH,@PrevDay)	
			IF(@SHIFTID = 0)  -- It runs for current day , whatever shift id updated in permenent shift table will be taken here. If shift id not present, new shift id wil be find out 
			BEGIN
				SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
								WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
				INSERT INTO #TEMP EXEC(@QUERY)
				SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
				SET @SHIFTID = ISNULL(@SHIFTID ,0)
				DELETE FROM #TEMP				
			END	
			goto GetShift;
			goto UpdateShift_Permanent;
		End		
	End	
	Else	 
	Begin
		select @PrevDay = @inClk_Date
		select @PrevDay
		
		set @day =DATEPART(DAY,@PrevDay)
		SET @YEAR=DATEPART(YEAR,@PrevDay)
		SET @MONTH=DATEPART(MONTH,@PrevDay)	
		SET @QUERY = ''	SELECT (PSA.DAY''+ CONVERT(VARCHAR(10),@day) + ''SHIFT) AS SHIFTID FROM TA_TBL_PERMANENTSHIFTALLOCATION PSA							
						WHERE PSA.[YEAR]= '' + @YEAR + ''  AND  PSA.[MONTH]= '' + @MONTH + '' AND EMPLOYEEID = '''''' + @EMPLOYEEAUTOID +''''''''
		INSERT INTO #TEMP EXEC(@QUERY)
		SET @SHIFTID = (SELECT SHIFTID FROM #TEMP)
		SET @SHIFTID = ISNULL(@SHIFTID ,0)
		DELETE FROM #TEMP
		if(@SHIFTID=-1)
		begin
			set @SHIFTID=0;
		end
		if(@SHIFTID=0)
		begin
			goto GetShift;
		end
		goto UpdateShift_Permanent;
	End 
	
	GetShift:
	begin
		--set @SHIFTID=0
		IF(@inClk_Time !=''00:00'' and @SHIFTID = 0 and @SHIFTID != -1)
		BEGIN
			Declare @Count int
			set @Count=0;
			Create Table #TempAutoShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40));
			Create Table #TempAutoShiftSingleShift(EmpId int, ShiftId int, clkDate datetime, punchtime varchar(40), shiftstartTime varchar(40), minutesdiffStart bigint, orderby int);
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId1,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId1 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId2,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId2 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId3,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId3 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId4,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId4 !=0
			insert into #TempAutoShift select isnull(EmployeeId,0),isnull(ShiftId5,0),@PrevDay,@inClk_Time from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID and ShiftId5 !=0	
			select @Count = isnull(count(EmpId),0)from #TempAutoShift				
			IF(@Count = 1)
			BEGIN
				select @SHIFTID = ISNULL(ShiftId,0)	from #TempAutoShift							
			END
			--ELSE IF(@Count = 0)
			--BEGIN
			--	set @SHIFTID = 0						
			--END
			ELSE
			BEGIN
				insert into #TempAutoShiftSingleShift 
				select b.EmpId,b.ShiftId,b.clkDate, b.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
				RANK()over(order by diff) from 
				(
					select a.EmpId,a.ShiftId,a.clkDate, a.punchtime,b.Shift_StartTime,datediff(minute,clkDate+b.Shift_StartTime,clkDate+punchtime) as Minutediff,
					case when datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)<0 then -datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime)
					else datediff(minute,clkDate+Shift_StartTime,clkDate+punchtime) end as diff
					from #TempAutoShift a
					inner join TA_Tbl_Shift b on b.Shift_Id = a.ShiftId 
				)as b		

				declare @loopcount int
				Declare @ShiftNewtime datetime
				set @loopcount = 1
				while (@loopcount <= 5)
				Begin		
						select @ShiftNewtime = clkDate+shiftstartTime from #TempAutoShiftSingleShift  where orderby=@loopcount	
						if(@ShiftNewtime < @PrevEndtime)
						Begin
							set @loopcount = @loopcount + 1;													
						End			
						else
						begin
							select @SHIFTID = ShiftId from #TempAutoShiftSingleShift  where orderby=@loopcount	
							break;					
						End			
				End								
			END
			DROP TABLE #TempAutoShiftSingleShift
			DROP TABLE #TempAutoShift
		END
		ELSE
		BEGIN
			-- if employee forgot to mark clock in time and manual entry got entered for that entry means, the shift id is not updating	properly.
			--Client need to reprocess the logs once again.Implemented on 10-mar-2020. 05:54 pm			
			IF NOT EXISTS(SELECT Clk_InTime FROM TA_Tbl_ClockDetails WHERE Clk_EmpId=@SwipeCardNo and 
			Clk_Date+Clk_InTime<@inClk_Date+@inClk_Time and Clk_Date=@inClk_Date)
			BEGIN
				--select 1
				set @SHIFTID=0;
				goto GetShift;
			END				
		END
	end	
	UpdateShift_Permanent:
	Begin
		DECLARE @DynamicQuery VARCHAR(MAX)
		SELECT @year=DATEPART(YEAR,@PrevDay),@month=DATEPART(MONTH,@PrevDay),@day=DATEPART(DAY,@PrevDay) 	
		SET @DynamicQuery =''''
		--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
		IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EMPLOYEEAUTOID)
		Begin
			if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EMPLOYEEAUTOID)
			begin
				SET @DynamicQuery =@DynamicQuery +''update TA_Tbl_PermanentShiftAllocation set day''+CONVERT(VARCHAR(2),@day)+''shift=''+CONVERT(VARCHAR(2),@SHIFTID)+ '' where
				month=''+CONVERT(VARCHAR(2),@month)+'' and year=''+CONVERT(VARCHAR(4),@year)+'' and employeeid=''+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)
			end
			else
			begin
				SET @DynamicQuery =@DynamicQuery +''insert into TA_Tbl_PermanentShiftAllocation (day''+CONVERT(VARCHAR(2),@day)+''shift,month,year,employeeid,Emp_id,dateshift)
				values(''+CONVERT(VARCHAR(2),@SHIFTID)+ '',''+CONVERT(VARCHAR(2),@month)+'',''+CONVERT(VARCHAR(4),@year)+'',''+CONVERT(VARCHAR(40),@EMPLOYEEAUTOID)+'',1,''''''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+'''''')''
			end
			exec (@DynamicQuery)
		End
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevelsCollectData]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetChildrenLevelsCollectData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
 /*  
Created By : Prabakaran.P  
Created On : 5-Mar-09  
Description : Store the child Levels for the Company, For Data Process Service  
Proc_Ta_GetChildrenLevelsCollectData  1  
select *  from Ta_Tbl_CollectRawDataCompanyLevelTemp  
delete from Ta_Tbl_CollectRawDataCompanyLevelTemp  
*/    
CREATE PROCEDURE [dbo].[Proc_Ta_GetChildrenLevelsCollectData] 
(@ParentID int) AS  
SET NOCOUNT ON  
DECLARE @NextLevel int, @Counter int, @PostKey varchar(200)  
SET @Counter = 1  
-- Build a cursor to loop through all the kids of this post  
DECLARE c1 CURSOR LOCAL FOR  
SELECT [ID]   
FROM ta_tbl_leveldetails  
WHERE ParentID = @ParentID and IsDeleted=0  
Order by [ID] ASC  
Declare @LevelIds as int  
set @LevelIds=(select count(LevelId) from Ta_Tbl_CollectRawDataCompanyLevelTemp where LevelId=@ParentID)  
if(@LevelIds=0)  
begin  
INSERT Ta_Tbl_CollectRawDataCompanyLevelTemp (LevelId) VALUES (@ParentID)  
end  
OPEN c1  
FETCH NEXT FROM c1  
INTO @ParentID  
WHILE @@FETCH_STATUS = 0  
BEGIN  
  -- Put this record in the temp table  
  INSERT Ta_Tbl_CollectRawDataCompanyLevelTemp (LevelId) VALUES (@ParentID)  
  -- Process all the children for this post  
  EXEC Proc_Ta_GetChildrenLevelsCollectData @ParentID  
  SET @Counter = @Counter + 1  
  -- And get the next record at this level  
  FETCH NEXT FROM c1  
  INTO @ParentID   
END  
CLOSE c1  
DEALLOCATE c1  
SET NOCOUNT OFF  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetChildrenLevels]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetChildrenLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By	: Prabakaran.P
Created On	: 5-Mar-09
Description	: Store the child Levels for the Company, For Data Process Service
Modified By		:	Manjula.P
Modified On		:	05-Feb-2014
Descriptions	:	Issue : in Dataprocess service there is no process if the employee is under parent id directly
				:	Adding this line by Manjula.P on 05-Feb-2014 for inserting passing parent levelid into Ta_Tbl_DataProcessCompanyLevelTemp for process 
					INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
Proc_Ta_GetChildrenLevels 1
select *  from Ta_Tbl_DataProcessCompanyLevelTemp
delete from Ta_Tbl_DataProcessCompanyLevelTemp
*/
CREATE PROCEDURE [dbo].[Proc_Ta_GetChildrenLevels]
(
	@ParentID int
) 
AS
Begin
	SET NOCOUNT ON
	DELETE FROM Ta_Tbl_DataProcessCompanyLevelTemp
	INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	---------------------------------------------------------------------------------------------------
	--DECLARE @NextLevel int, @Counter int, @PostKey varchar(200)
	--SET @Counter = 1
	---- Build a cursor to loop through all the kids of this post
	--DECLARE c1 CURSOR LOCAL FOR 
	--SELECT [ID] FROM ta_tbl_leveldetails WHERE ParentID = @ParentID and IsDeleted=0 Order by [ID] ASC
	--Declare @LevelIds as int
	--set @LevelIds=(select count(LevelId) from Ta_Tbl_DataProcessCompanyLevelTemp where LevelId=@ParentID)
	--if(@LevelIds=0)
	--	begin
	--		INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	--	end
	--OPEN c1
	--FETCH NEXT FROM c1
	--INTO @ParentID
	--WHILE @@FETCH_STATUS = 0
	--	BEGIN
	--		-- Put this record in the temp table
	--		INSERT Ta_Tbl_DataProcessCompanyLevelTemp (LevelId) VALUES (@ParentID)
	--		-- Process all the children for this post
	--		EXEC Proc_Ta_GetChildrenLevels @ParentID
	--		SET @Counter = @Counter + 1
	--		-- And get the next record at this level
	--		FETCH NEXT FROM c1 INTO @ParentID 
	--	END
	--CLOSE c1
	--DEALLOCATE c1	
	;WITH ChildLevelDetails as
	(
		select id as parentAutoid,name FROM ta_tbl_leveldetails WHERE ParentID = @ParentID and IsDeleted=0
		UNION ALL
		select ld.id,ld.name FROM ta_tbl_leveldetails ld
		INNER JOIN ChildLevelDetails CL ON CL.parentAutoid = ld.parentId
	)
	Insert into Ta_Tbl_DataProcessCompanyLevelTemp
	SELECT parentAutoid From ChildLevelDetails
	--SELECT * FROM Ta_Tbl_DataProcessCompanyLevelTemp
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'create PROCEDURE [dbo].[Proc_TA_getChildLevelDetails]
(
	@levelId int,
	@UserGroupName nVarchar(250)
)
as
Begin
	IF(@UserGroupName = ''SuperAdmin'')
		BEGIN
			select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId, b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId
		End
	Else
		Begin
			select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
		End
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAdditionalWeekOffByLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
	Procedure Name : Proc_TA_GetAdditionalWeekOffByLevel  
	Description : Get Additional WeekOff Details of Employees Based on their Level
	Tables Included : TA_Tbl_Additional_WeeklyOff, TA_Tbl_Employee 
	Created By : Kumuthini.L 
	Created On : 19-Feb-08  
	Modified By :  
	Modified On :  
*/  
 --Proc_TA_GetAdditionalWeekOffByLevel ''30'',''03/10/2012'' 
CREATE PROCEDURE [dbo].[Proc_TA_GetAdditionalWeekOffByLevel]
(
   @EmpSwipeCardNo nVarchar(25),
   @Date nVarchar(15)
)
AS
SELECT AW.Addl_WeekOff_Day,AW.Addl_WeekOff_Week FROM TA_Tbl_Additional_WeeklyOff AW 
inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AW.Addl_WeeklyOff_Id = AWL.Addl_WeeklyOff_Id
INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.LevelId = AWL.LevelId
INNER JOIN TA_Tbl_Employee emp ON emp.Employee_Id = EL.EmployeeID
WHERE emp.SwipeCardNo = @EmpSwipeCardNo AND AW.IsDeleted = 0 AND 
EL.EffectiveDate = (SELECT TOP 1 EffectiveDate FROM TA_Tbl_EmployeeLevel WHERE  EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,@Date, 102) order by EffectiveDate desc)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevels]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevels]
(
	@levelId int
)
as
BEGIN
	--select a.id,a.levelid,a.name,b.name as childLevelName,b.parentId,b.levelid as childId,b.description from ta_tbl_leveldetails a inner join ta_tbl_leveldetails b  on b.parentid=a.levelid where b.parentid=@levelId 
  	select * from ta_tbl_leveldetails where parentid=@levelId and isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompOffDays]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompOffDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Proc_TA_GetCompOffDays 10860,2
Procedure Name		:		Proc_TA_GetCompOffDays 10947,2
Description			:		Get Compensatory off Leave Details of Employees Based on their Employee_Id 
Tables Included		:		Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting
Created By			:		Prabakaran
Created On			:		18-Feb-07
Description			:		Remove The Date Convertion In Expaire Date Calculation
EXEC Proc_TA_GetCompOffDays @EmployeeId=947,@YearSettingId=3,@Date=''02-May-2019''
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetCompOffDays] 
	@EmployeeId BIGINT,
	@YearSettingId INT,
	@Date VARCHAR(50) = NULL
AS
BEGIN
	set nocount on
	DECLARE @FromDate DATETIME, @ToDate DATETIME, @MaxDate DATETIME, @DateFormt DATETIME
	DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT
	DECLARE @Employee_code_Id NVARCHAR(50), @OtText VARCHAR(MAX)
	DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT
	DECLARE @ValidDates INT
	declare @employeeCodeID as nvarchar(20)
	declare @RequestCOff int
	declare @today datetime =getdate()
	select @employeeCodeID=Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmployeeId
	declare @LevelId varchar(2000)
	 create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
      insert into #EmpLevel exec [Proc_TA_EmpLevel] @today,@employeeCodeID 
      declare @GetLevelID as int
            set @GetLevelID=(select top 1 LevelId from #EmpLevel)
            DECLARE @childID INT 
             ;WITH ParentLevel AS
            (
                  SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
                  UNION ALL
                  SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
                  INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
            )
            SELECT TOP 1 @LevelId=id
            FROM ParentLevel r
            --inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
            ORDER BY lvl DESC
	select @RequestCOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	if(@RequestCOff is null)
		begin
			select @RequestCOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		end
	BEGIN TRY
			BEGIN TRAN
			-- Get From Date/To Date from Active year
				SELECT @ToDate = ToDate ,@FromDate = FromDate FROM TA_Tbl_YearSetting WHERE YearSettings_Id = @YearSettingId
				IF ((ISNULL(@Date, '''') = '''') OR (@Date = ''''))
				BEGIN
					SET @Date = CONVERT(VARCHAR(11), GETDATE(), 101)
				END
				DECLARE @Denamitator VARCHAR(1), @Dt VARCHAR(10), @Mon VARCHAR(10),  @Year VARCHAR(10)
				DECLARE @PI INT
				BEGIN TRY
					BEGIN TRAN
						SET @DateFormt = CAST(@Date AS DATETIME)
						IF(@@ERROR = 0)
							COMMIT TRAN
				END TRY
				BEGIN CATCH
						IF(@@ERROR <> 0)
							ROLLBACK TRAN
						SET @Denamitator =  CASE WHEN @Date LIKE ''%/%'' THEN ''/'' WHEN @Date LIKE ''%-%'' THEN ''-'' ELSE '' '' END
						SET @PI = 0
						SET @Dt = SUBSTRING(@Date,@PI,CHARINDEX(@Denamitator, @Date, @PI))
						SET @PI = @PI + CHARINDEX(@Denamitator, @Date, 0) 
						SET @Mon = SUBSTRING(@Date,@PI+1,CHARINDEX(@Denamitator, @Date, @PI)-1)
						SET @PI = @PI + CHARINDEX(@Denamitator, @Date, 0)
						SET @Year = SUBSTRING(@Date,@PI+1,CHARINDEX(@Denamitator, @Date, @PI)-1)
						SET @DateFormt = CAST((@Mon + ''-'' + @Dt + ''-'' + @Year) AS DATETIME)
				END CATCH
				SET @CompOffDays = 0
				SET @SumOfOTMins = 0
				SET @OtText = ''''
				IF EXISTS(SELECT CompOff_Eligible FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeId AND IsDeleted = 0 AND CompOff_Eligible = 1 AND CompOff_Eligible IS NOT NULL AND OT_Eligible = 0 AND OT_Eligible IS NOT NULL)
				BEGIN
					DELETE FROM TA_Tbl_OverTimeStatus FROM TA_Tbl_OverTimeStatus OT
						LEFT OUTER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OT.Process_RecID
					WHERE ISNULL(LeaveApplicationId, '''') = '''' AND OT.Employee_Id = @EmployeeId AND ISNULL(PD.Process_Rec_ID, '''') = '''' and ISNULL(OT.isRequest,0)=0
					-- Get Employee code Id based on Employee Id
					SELECT @Employee_code_Id = SwipeCardNo FROM TA_Tbl_Employee WHERE Employee_Id = @EmployeeId AND IsDeleted=0
					--for the below reason Commented by Manikandan.RR on 16-Oct-2020.
					--if we approve past days record after current month data means, quota is not generating. we got this issue in scufe client.					
					--SELECT @FromDate = ISNULL(MAX([Date]) + 1, @FromDate) FROM TA_Tbl_OverTimeStatus OTS WHERE OTS.OverTimeStatus = ''Approved'' AND OTS.CompOffEligible = 1 AND OTS.Employee_Id = @EmployeeId
					-- Get OtMinHrs (Over Time Minimum Hours)
					SELECT 			
						@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,''00:00'', ISNULL(OtMinHrs, ''00:00'')),
						@FullDayOTMins = DATEDIFF(MI,''00:00'',ISNULL(FullDayOTMinHrs, ''00:00'')),
						@ValidDates = ISNULL(LP.CompOffValidDays, 60)
					FROM TA_Tbl_LeavePolicy LP
					INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
					WHERE ELP.EmployeeId = @EmployeeId AND
						ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
							INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
							WHERE YS.IsActive = 1 AND ELP.EmployeeId = @EmployeeId ORDER BY ELP.ToDate DESC)
					-- Get CompOff (Compensation Off) days
					IF(@TypeOfOT=1)
					BEGIN
						SELECT 
							@SumOfOTMins = (@SumOfOTMins + OtMins),
							@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),
							--@OtText = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @OtText ELSE (@OtText + '';'' + CAST(Process_Rec_ID AS VARCHAR(50)) + ''&'' + CONVERT(VARCHAR(11), @MaxDate, 101) + ''&'' + CAST(ISNULL(HrsExtra, ''00:00'') AS VARCHAR(10)) + ''&'' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
							@OtText = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @OtText ELSE (@OtText + '';'' + CAST(Process_Rec_ID AS VARCHAR(50)) + ''&'' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
							@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),
							@MaxDate = NULL
						FROM TA_Tbl_ProcessedData
							WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND OvertimeStatus=''Approved''
							AND (DATEADD(D, @ValidDates, [Date])) >= @DateFormt AND OtMins > 0 AND ISNULL(OtMins, '''') != ''''
						ORDER BY [Date]
						if(@RequestCOff=0)
						begin
							INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest, isDelete)
								SELECT PD.Process_Rec_ID, @EmployeeId, PD.[Date], PD.HrsExtra, T.OverTimeMins, PD.OverTimeStatus, 1, 0, (DATEADD(D, @ValidDates, PD.[Date])), (CASE WHEN T.OverTimeMins >= @FullDayOTMins THEN 1.0 WHEN T.OverTimeMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN T.OverTimeMins >= @FullDayOTMins THEN 1.0 WHEN T.OverTimeMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),PD.[Date]) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END),0,0 FROM TA_Tbl_ProcessedData PD 
									INNER JOIN (SELECT CAST((SUBSTRING(Value, 0, CHARINDEX(''&'', Value,0))) AS INT) Process_RecID, (CAST(SUBSTRING(Value, CHARINDEX(''&'', Value,0)+1, LEN(Value)) AS INT)) OverTimeMins  FROM [dbo].Split(@OtText, '';'') WHERE Value != '''') T ON PD.Process_Rec_ID = T.Process_RecID
								WHERE Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus OS WHERE OS.Employee_Id = @EmployeeId) AND
								([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND
								OvertimeStatus=''Approved'' AND  T.OverTimeMins >= @HalfDayOTMins
						END
					END
					ELSE 
					BEGIN
						if(@RequestCOff=0)
						begin
							INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest, isDelete)
								SELECT Process_Rec_ID, @EmployeeId, [Date], HrsExtra, OtMins, OverTimeStatus, 1, 0, (DATEADD(D, @ValidDates, [Date])), (CASE WHEN OtMins >= @FullDayOTMins THEN 1.0 WHEN OtMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN OtMins >= @FullDayOTMins THEN 1.0 WHEN OtMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END) , (CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),[Date])< GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END),0,0 FROM TA_Tbl_ProcessedData WHERE 
								Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus OS WHERE OS.Employee_Id = @EmployeeId) AND
								([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id AND
								OvertimeStatus=''Approved'' AND  OtMins >= @HalfDayOTMins
						END
					END
				END	
				-- Get Number of CompOff days from Leave Application	
				 update TA_Tbl_ProcessedData set 
			  OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
				SELECT @CompOffDays = ISNULL(SUM(OTS.RemainingDays), 0) FROM TA_Tbl_OverTimeStatus OTS WHERE 
					OTS.OverTimeStatus = ''Approved'' AND ISNULL(OTS.CompOffSatus, ''Not Taken'') = ''Not Taken'' AND
					OTS.CompOffEligible = 1 AND OTS.Employee_Id = @EmployeeId AND
					OTS.[DateToExpired] >= @DateFormt and OTS.Date<=@DateFormt
			IF(@@ERROR = 0)
				COMMIT TRAN
		END TRY
		BEGIN CATCH
		END CATCH
		SELECT (CASE WHEN @CompOffDays < 0 THEN 0 ELSE ISNULL(@CompOffDays, 0) END) [CompOffDays]
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIds]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetCompanyIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetCompanyIds]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName  
	from TA_Tbl_LevelDetails ld inner join TA_Tbl_Level l on l.LevelId=ld.LevelId  
	where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.parentid=0 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetCompanyIdForService]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetCompanyIdForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetCompanyIdForService]
	-- Add the parameters for the stored procedure here
	@LevelId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]=@LevelId
	WHILE((SELECT parentId from TA_tbl_LevelDetails where id=@Levelid)!=0) 
		BEGIN 
			SELECT @Levelid=parentId from TA_tbl_LevelDetails where id=@Levelid
		END
	SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]= @LevelId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCompanyDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCompanyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-11-2016>
-- Description:	<Getting Company Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCompanyDetails]
	@LevelId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT Id,ParentId FROM TA_Tbl_LevelDetails WHERE [id]= @LevelId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org]
(
	@para1 int	
	--@LevelIDs nvarchar(1000)
)
AS
BEGIN
	declare @Query as nvarchar(4000)
	SELECT id,name from Ta_Tbl_levelDetails where parentId=@para1  and isdeleted=0 order by Name
	--set @Query = ''SELECT id,name from Ta_Tbl_levelDetails where parentId='' + cast (@para1 as nvarchar(100)) + ''  and isdeleted=0 and id in ('' + @LevelIDs + '')  order by Name''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org_Updated_MailPopup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated_MailPopup]
(
	@para1 int	,
	@LevelIDs nvarchar(2000)
)
AS
BEGIN
	SELECT id,name from Ta_Tbl_levelDetails where parentId=@para1  and isdeleted=0 order by Name
	--set @Query = ''SELECT id,name from Ta_Tbl_levelDetails where parentId='' + cast (@para1 as nvarchar(100)) + ''  and isdeleted=0 and id in ('' + @LevelIDs + '')  order by id ''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_UpdateBonusLeavesForService]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_UpdateBonusLeavesForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan.
-- Create date: <28-09-2015>
-- Description:	<Updating the Bonus Leave Datas>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_UpdateBonusLeavesForService]	
AS
BEGIN	
	SET NOCOUNT ON;
	CREATE TABLE #TempBonusLeave
	(
		AutoId int identity(1,1),
		EmployeeID int,
		SwipeCardNumber varchar(40),
		BonusLeaveQuota int,
		FromDate smalldatetime,
		ToDate smalldatetime
	)
	INSERT INTO #TempBonusLeave
	SELECT	E.Employee_Id,
			E.SwipeCardNo,
			EBL.BonusLeaveQuota,
			YS.FromDate,
			YS.ToDate FROM Ta_Tbl_EmployeeBonusLeave EBL
	INNER JOIN TA_Tbl_Employee E ON  E.Employee_Id=EBL.EmployeeId
	INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id=EBL.YearSettingId
	WHERE E.IsDeleted=0 and E.Employee_Status=1 and YS.IsActive=1 and EBL.BonusLeaveQuota >0
	DECLARE @intBonusLeaveAvailable INT
	SET @intBonusLeaveAvailable= 0
	DECLARE @ApplicableBLs INT
	DECLARE @Count INT
	DECLARE @start INT
	SET @start=1
	SET @Count=(SELECT COUNT(*)FROM #TempBonusLeave)
	WHILE(@Count>=@start)
		BEGIN			
			DECLARE @SwipeCardNumber VARCHAR(40)
			DECLARE @YS_FromDate SMALLDATETIME
			DECLARE @YS_ToDate SMALLDATETIME
			DECLARE @AvailedBLCount int
			SELECT @SwipeCardNumber=SwipeCardNumber,@YS_FromDate=FromDate,@YS_ToDate=ToDate,@ApplicableBLs=BonusLeaveQuota from #TempBonusLeave where AutoId=@start
			SELECT @AvailedBLCount=Count(Process_Rec_Id) FROM  Ta_Tbl_ProcessedData
			WHERE Employee_Code_Id=@SwipeCardNumber AND (Date BETWEEN @YS_FromDate AND @YS_ToDate) AND Status=''BL''
			SET @intBonusLeaveAvailable = 0
			DECLARE @DynamicQuery VARCHAR(MAX)
			set @DynamicQuery=''''
			IF @ApplicableBLs >@AvailedBLCount
			BEGIN
				SET @intBonusLeaveAvailable = @ApplicableBLs-@AvailedBLCount				
				SET @DynamicQuery=''UPDATE TA_Tbl_ProcessedData SET Attendance = ''''Present'''',Status = ''''BL'''',ProcessFlag = 1, 
				fnAttendanceCode=''''Present'''', anAttendanceCode=''''Present'''' 
				WHERE Process_Rec_Id in
				(
					SELECT TOP ''+CONVERT(VARCHAR(20),@intBonusLeaveAvailable) +'' Process_Rec_Id FROM TA_Tbl_Processeddata 
					WHERE Employee_Code_Id = ''+Convert(varchar(20),@SwipeCardNumber)+'' AND Attendance = ''''Absent'''' AND 
					(Date BETWEEN ''''''+CONVERT(VARCHAR(20),@YS_FromDate) +'''''' AND ''''''+ CONVERT(VARCHAR(20),@YS_ToDate)+'''''') ORDER BY Date ASC
				)''
				Execute(@DynamicQuery)
			End
			SET @start=@start+1
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateAuditTableandFields]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateAuditTableandFields]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Christopher S
-- Create date: 08 Jan 08
-- Description:	Update TABLES TA_Tbl_AuditTable and TA_Tbl_AuditField
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateAuditTableandFields] 
	-- Add the parameters for the stored procedure here
	@tableName nvarchar(100),
    @tableStatus bit,
    @fieldName nvarchar(100),
    @insertBitStatus bit,
    @updateBitStatus bit,
    @deleteBitStatus bit,
    @fieldStatus bit,
    @opr nvarchar
AS
DECLARE @tableId decimal
DECLARE @fieldsTableId decimal
DECLARE @tn nvarchar(100)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
--    if(@opr=''I'')
--       begin
      	   INSERT INTO TA_Tbl_AuditTable(TableName,Status) VALUES(@tableName,@tableStatus) 
           set @tableId = (select @@identity)
--       end
--    else
--      begin
--           UPDATE TA_Tbl_AuditTable SET TableName = @tableName, Status = @tableStatus WHERE TableName = @tableName          
--      end 
    INSERT INTO TA_Tbl_AuditField(TableID,FieldName,InsertBit,UpdateBit,DeleteBit,Status) VALUES(@tableId,@fieldName,@insertBitStatus,@updateBitStatus,@deleteBitStatus,@fieldStatus) 
    set @fieldsTableId = (select @@identity) 
    SELECT @tn = TA_Tbl_AuditTable.TableName FROM TA_Tbl_AuditTable
    INNER JOIN TA_Tbl_AuditField ON TA_Tbl_AuditTable.TableID = TA_Tbl_AuditField.TableID
    WHERE TA_Tbl_AuditField.FieldID = @fieldsTableId   
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_TemporaryWeekDayLevelDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Manikandan.R
-- Create date: 14-Mar-2012
-- Description:	To Get the Temporary Weekdayid''s for Viewing the Details of selected TempIds
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_TemporaryWeekDayLevelDetails]
	-- Add the parameters for the stored procedure here
	 @TempWeekdayId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END 
	select	distinct case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, TempWeekday_FromDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, TempWeekday_FromDate, @dateFormat) end ''TempWeekday_FromDate'',
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, TempWeekday_ToDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, TempWeekday_ToDate, @dateFormat) end ''TempWeekday_ToDate'',			
			ClosingTime,Reason,TL.LevelId from ta_tbl_TemWeekDay TD
			inner join TA_Tbl_Temporary_WeeklyOff_Levels TL on TD.TempWeekday_Id = TL.TempWeekday_Id 
			where TD.TempWeekday_Id=@TempWeekdayId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftDetailsById]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
	Procedure Name : Proc_TA_ShiftDetailsById  
	Description : Get the Shift Details by passing Shift Id
	Tables Included : TA_Tbl_Shift   
	Created By : Janakaraj  
	Created On : 3-Sep-07  
	Modified By : Kumuthini.L
	Modified On :19-Feb-08
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_ShiftDetailsById]
(
@ShiftId INT
)
AS
declare @LevelId as int
BEGIN
	set @LevelId=(select Level_Id FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftId)
	if(@LevelId!=0)
	BEGIN
		SELECT TA_Tbl_Shift.*, TA_Tbl_Leveldetails.Name,CategoryName=(select top 1 CategoryName from TA_Tbl_Category where CategoryId=empCategory) FROM TA_Tbl_Shift 
		INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_Shift.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE Shift_Id=@ShiftId
	END
	ELSE
	BEGIN
		SELECT TA_Tbl_Shift.*, '''' as Name,CategoryName=(select top 1 CategoryName from TA_Tbl_Category where CategoryId=empCategory) FROM TA_Tbl_Shift 
		WHERE Shift_Id=@ShiftId
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTerminalDetailsForEntrance]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTerminalDetailsForEntrance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectTerminalDetailsForEntrance] 
@Type Char(1),
@EntranceId int
AS
--Select Terminal details during Insert 
IF(@Type=''I'')
BEGIN
	SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name FROM TA_Tbl_Terminal T  
	where T.Terminal_Id Not IN (SELECT DISTINCT D.Reader_Id FROM TA_Tbl_Entrance E 
	INNER JOIN TA_Tbl_Entrance_inoutdetails D on E.Entrance_Id=D.Entrance_Id where E.Isdeleted=0)
END
--Select Terminal details during Modify
IF(@Type=''U'')
BEGIN
	SELECT T.Terminal_Id,T.Terminal_ReaderID,T.Terminal_Name FROM TA_Tbl_Terminal T  
	where T.Terminal_Id Not IN (SELECT DISTINCT D.Reader_Id FROM TA_Tbl_Entrance E 
	INNER JOIN TA_Tbl_Entrance_inoutdetails D on E.Entrance_Id=D.Entrance_Id where E.Isdeleted=0 and E.Entrance_id <>  @EntranceId)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectTemplateFilterDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectTemplateFilterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectTemplateFilterDetails]	
	-- Add the parameters for the stored procedure here
	@Templateid int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
	-- Insert statements for procedure here
	Declare @Filters varchar(max)
	Declare @Count int
	Declare @start int
	Declare @TempTable varchar(max)
	Declare @TempTableInsert varchar(max)
	Declare @TempFiltersvalue varchar(max)
	Declare @TempFiltersvalues varchar(max)
	if exists(select Filters  from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid)
	begin
	set @TempTable=''Create Table TempSMSFinalFilters(''
	set @TempTableInsert=''Insert into TempSMSFinalFilters values(''
	set @start=1
	select @Filters=Filters  from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid
	select @Count=COUNT(*) from dbo.Split(@Filters,'','')
	Create table #TempSMSFilters(id int identity(1,1),Filters varchar(max))
	insert into #TempSMSFilters select Value from dbo.Split(@Filters,'','')
	--select * from #TempFilters
	while @start<=@Count 
	begin
		select @TempFiltersvalue=replace(substring(Filters,0,charindex(''='',Filters)),''@'',''''),
		@TempFiltersvalues=replace(substring(Filters,charindex(''='',Filters)+1,LEN(Filters)),''~'','','')
		from #TempSMSFilters where id=@start 
		if(@start!=@Count)
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+'' varchar(max),''
			set @TempTableInsert=@TempTableInsert+''''''''+@TempFiltersvalues+'''''',''
		end
	else
		begin
			set @TempTable=@TempTable+ @TempFiltersvalue+'' varchar(max)''
			set @TempTableInsert=@TempTableInsert+''''''''+@TempFiltersvalues+''''''''
		end			
		set @start=@start+1
	end
	set @TempTable=@TempTable+'')''
	set @TempTableInsert=@TempTableInsert+'')''	
	Execute(@TempTable)
	Execute(@TempTableInsert)
	select * from TempSMSFinalFilters
	Select ReportType from Ta_tbl_SMSTemplateFilters where TemplateId=@Templateid
	drop table TempSMSFinalFilters
	end
	else
	begin
		Create table #TempFinalSMSFilters(id int identity(1,1))
		select * from #TempFinalSMSFilters
		Select 1 as ReportType 
		drop table #TempFinalSMSFilters
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSpouseDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSpouseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectSpouseDetails]
(
@empID INT
)
AS
BEGIN
	SELECT ChildEmp_ID,Emp_ID,Name,CONVERT(NVARCHAR,DOB,101) AS DOB FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID=@empID AND Spouse_Child=''S'' AND Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectSMSTemplateDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectSMSTemplateDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan>
-- Create date: <27-08-2016>
-- Description:	<Get the SMS Template details using TemplateID>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectSMSTemplateDetails]
	-- Add the parameters for the stored procedure here
	@TemplateId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)	
	DECLARE @TimeFormat as nvarchar(25)	
	select @TimeFormat=TimeFormat,@date=DateFormat from TA_Tbl_DateandTimeFormat
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
    -- Insert statements for procedure here
	if @templateid!=0
	begin
		Create table #UsergroupIDs(id int identity(1,1),ids int)
		insert into #UsergroupIDs 
		select Usergroupid from Ta_Tbl_SMSReceivers where TemplateId=@TemplateId
		Declare @i int
		Declare @count int
		Declare @usergroupid int
		Declare @Receivers varchar(max)
		set @Receivers=''''
		set @count=(select COUNT(*) from #UsergroupIDs)
		set @i=1
		while @count>=@i
		begin
			select @usergroupid=ids from #UsergroupIDs where id=@i			
			if @Receivers!=''''
			begin
				set @Receivers=@Receivers+'';''+(select groupName from TA_Tbl_Usergroup where groupId=@usergroupid)
			end
			else
			begin
				set @Receivers=(select groupName from TA_Tbl_Usergroup where groupId=@usergroupid)
			end
			set @i=@i+1
		end	
		SELECT ST.id as Templateid,TemplateName,Message as Message,case when Status=1 then ''Enabled'' else ''Disabled'' end as status,LastModified,ModifiedBy,
		First_TriggeringTime,Second_TriggeringTime,ToEmployee,LessHrsLimitation,Continue_AbsentDays,@Receivers as Receivers,STF.Filters,STF.ReportType,Tags 
		from Ta_Tbl_SMSTemplates ST
		left outer join Ta_tbl_SMSTemplateFilters STF on ST.id=STF.TemplateId
		where ST.id=@TemplateId
	end
	else
	begin
		SELECT id as Templateid,TemplateName,Message+'' ''+ Tags as Message,case when Status=1 then ''Enabled'' else ''Disabled'' end as status,
		case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, LastModified,@dateFormat),'' '',''-'') 
	else CONVERT(VARCHAR, LastModified, @dateFormat) end 
	+'' ''+	
	case	when convert(varchar(20),@TimeFormat)=''hh:mm'' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,LastModified,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),LastModified),13,2),'' '',''''))=1 then ''0''+ replace(substring(CONVERT(varchar(20),LastModified),12,6),'' '','''')
					else substring(CONVERT(varchar(20),LastModified),12,6) end
			+'' '' + substring(CONVERT(varchar(20),LastModified),18,2)
	end LastModified,ModifiedBy,First_TriggeringTime,Second_TriggeringTime,ToEmployee,LessHrsLimitation,Continue_AbsentDays,''''as Receivers 
	,'''' as Filters,'''' ReportType,Tags
	from Ta_Tbl_SMSTemplates 
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShiftAllcation_Import]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShiftAllcation_Import]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	21-Aug-2014
 EXEC [Proc_TA_ShiftAllcation_Import] @ShiftData = ''<Dst_ShiftAlloc>
  <Tbl_ShiftAlloc>
    <Employee_Code_Id>104</Employee_Code_Id>
    <Employee_Name>Anbu </Employee_Name>
    <Company_Name>Shift Company </Company_Name>
    <Year>2017</Year>
    <Mon>Jan</Mon>
    <Day1>EMS</Day1>
    <Day2>EMS</Day2>
    <Day3>EMS</Day3>
    <Day4>EMS</Day4>
    <Day5>EMS</Day5>
    <Day6>EMS</Day6>
    <Day7>EMS</Day7>
    <Day8>EMS</Day8>
    <Day9>EMS</Day9>
    <Day10>EMS</Day10>
    <Day11>EMS</Day11>
    <Day12>EMS</Day12>
    <Day13>EMS</Day13>
    <Day14>EMS</Day14>
    <Day15>EMS</Day15>
    <Day16>EMS</Day16>
    <Day17>EMS</Day17>
    <Day18>EMS</Day18>
    <Day19>EMS</Day19>
    <Day20>EMS</Day20>
    <Day21>EMS</Day21>
    <Day22>EMS</Day22>
    <Day23>EMS</Day23>
    <Day24>EMS</Day24>
    <Day25>EMS</Day25>
    <Day26>EMS</Day26>
    <Day27>EMS</Day27>
    <Day28>EMS</Day28>
    <Day29>EMS</Day29>
    <Day30>EMS</Day30>
    <Day31>EMS</Day31>
  </Tbl_ShiftAlloc></Dst_ShiftAlloc>'', @WeekOff = ''6'', @SkipValid = 0
-- =============================================
*/
CREATE PROCEDURE [dbo].[Proc_TA_ShiftAllcation_Import]
	-- Add the parameters for the stored procedure here
	@ShiftData XML = NULL,
	@WeekOff VARCHAR(15),
	@SkipValid BIT
AS
BEGIN
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX),ImportID bigint)		
	DELETE FROM [TA_Tbl_ImportShiftAllocation]
	BEGIN TRY
		BEGIN TRAN ImportShiftMaster
			SELECT @YearSettingId = [YearSettings_Id], @StartDate = [FromDate] FROM [TA_Tbl_YearSetting] WHERE [IsActive] = 1 
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
			CREATE TABLE #TempImportShiftAllocation(
	[Employee_Id] [int] NULL,
	[Employee_Code_Id] [varchar](100) NULL,
	[Company_Id] [int] NULL,
	[Company_Name] [varchar](250) NULL,
	[Year] [varchar](5) NULL,
	[Mon] [varchar](20) NULL,
	[Day1] [varchar](8) NULL,
	[Day2] [varchar](8) NULL,
	[Day3] [varchar](8) NULL,
	[Day4] [varchar](8) NULL,
	[Day5] [varchar](8) NULL,
	[Day6] [varchar](8) NULL,
	[Day7] [varchar](8) NULL,
	[Day8] [varchar](8) NULL,
	[Day9] [varchar](8) NULL,
	[Day10] [varchar](8) NULL,
	[Day11] [varchar](8) NULL,
	[Day12] [varchar](8) NULL,
	[Day13] [varchar](8) NULL,
	[Day14] [varchar](8) NULL,
	[Day15] [varchar](8) NULL,
	[Day16] [varchar](8) NULL,
	[Day17] [varchar](8) NULL,
	[Day18] [varchar](8) NULL,
	[Day19] [varchar](8) NULL,
	[Day20] [varchar](8) NULL,
	[Day21] [varchar](8) NULL,
	[Day22] [varchar](8) NULL,
	[Day23] [varchar](8) NULL,
	[Day24] [varchar](8) NULL,
	[Day25] [varchar](8) NULL,
	[Day26] [varchar](8) NULL,
	[Day27] [varchar](8) NULL,
	[Day28] [varchar](8) NULL,
	[Day29] [varchar](8) NULL,
	[Day30] [varchar](8) NULL,
	[Day31] [varchar](8) NULL,
	[ImportID] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
			INSERT INTO #TempImportShiftAllocation
				SELECT E.Employee_Id, E.SwipeCardNo, LD.Id, Tbl.Company_Name, [Year], [Mon],
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''01-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day1 END) Day1,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''02-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day2 END) Day2,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''03-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day3 END) Day3,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''04-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day4 END) Day4,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''05-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day5 END) Day5,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''06-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day6 END) Day6,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''07-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day7 END) Day7,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''08-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day8 END) Day8,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''09-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day9 END) Day9,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''10-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day10 END) Day10,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''11-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day11 END) Day11,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''12-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day12 END) Day12,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''13-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day13 END) Day13,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''14-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day14 END) Day14,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''15-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day15 END) Day15,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''16-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day16 END) Day16,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''17-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day17 END) Day17,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''18-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day18 END) Day18,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''19-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day19 END) Day19,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''20-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day20 END) Day20,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''21-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day21 END) Day21,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''22-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day22 END) Day22,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''23-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day23 END) Day23,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''24-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day24 END) Day24,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''25-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day25 END) Day25,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''26-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day26 END) Day26,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''27-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day27 END) Day27,
					(CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''28-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day28 END) Day28,
					(CASE WHEN ([Mon] <> ''Feb'') THEN (CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''29-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day29 END) ELSE (CASE WHEN (([Mon] = ''Feb'') AND (datepart(d,DATEADD(D, -1, (''01-Mar-'' + [Year]))) = 29)) THEN (CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''29-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day29 END) ELSE NULL END) END) Day29,
					(CASE WHEN ([Mon] <> ''Feb'') THEN (CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''30-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day30 END) ELSE NULL END) Day30,
					(CASE WHEN ([Mon] NOT IN (''Feb'', ''Apr'', ''Jun'', ''Sep'', ''Nov'')) THEN (CASE WHEN @WeekOff LIKE ''%'' + CAST(DATEPART(DW, ''31-'' + [Mon] + ''-'' + [Year]) AS VARCHAR(8)) + ''%'' THEN ''Off'' ELSE Day31 END) ELSE NULL END) Day31
				FROM OPENXML (@XMLParams, ''/Dst_ShiftAlloc/Tbl_ShiftAlloc'', 2) WITH 
				  (Employee_Code_Id VARCHAR(50), Company_Name VARCHAR(250), [Year] VARCHAR(5), Mon VARCHAR(20), Day1 VARCHAR(8), Day2 VARCHAR(8), Day3 VARCHAR(8), 
				   Day4 VARCHAR(8), Day5 VARCHAR(8), Day6 VARCHAR(8), Day7 VARCHAR(8), Day8 VARCHAR(8), Day9 VARCHAR(8), Day10 VARCHAR(8),
				   Day11 VARCHAR(8), Day12 VARCHAR(8), Day13 VARCHAR(8), Day14 VARCHAR(8), Day15 VARCHAR(8), Day16 VARCHAR(8), Day17 VARCHAR(8),
				   Day18 VARCHAR(8), Day19 VARCHAR(8), Day20 VARCHAR(8), Day21 VARCHAR(8), Day22 VARCHAR(8), Day23 VARCHAR(8), Day24 VARCHAR(8),
				   Day25 VARCHAR(8), Day26 VARCHAR(8), Day27 VARCHAR(8), Day28 VARCHAR(8), Day29 VARCHAR(8), Day30 VARCHAR(8), Day31 VARCHAR(8)) Tbl
				LEFT OUTER JOIN TA_Tbl_LevelDetails LD ON LD.[Name] = Tbl.Company_Name AND LD.ParentId = 0
				LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
				 AND E.IsDeleted = 0 AND E.Employee_Status = 1
				 insert into [TA_Tbl_ImportShiftAllocation](Employee_Id, Employee_Code_Id, Company_Id, Company_Name, Year, Mon, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day17, Day18, Day19, Day20, Day21, Day22, Day23, Day24, Day25, Day26, Day27, Day28, Day29, Day30, Day31, RecordNumber)
				 select Employee_Id, Employee_Code_Id, Company_Id, Company_Name, Year, Mon, Day1, Day2, Day3, Day4, Day5, Day6, Day7, Day8, Day9, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day17, Day18, Day19, Day20, Day21, Day22, Day23, Day24, Day25, Day26, Day27, Day28, Day29, Day30, Day31,1+ROW_NUMBER()over(order by importid) from #TempImportShiftAllocation
			--It will Remove Duplication Records From Import Table
			--by Manikandan.RR on 11-01-2016 11.12 AM
			--Delete from [TA_Tbl_ImportShiftAllocation] where ImportID in
			--(
			--	SELECT ImportID FROM 
			--	(
			--		SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
			--				ImportID FROM [TA_Tbl_ImportShiftAllocation]
			--	)AS A WHERE duplicate>1
			--)			
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation])
			BEGIN
				SET @ErrMsg = ''There is no record in the file''
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
			END
			IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Employee_Id, '''') = '''')
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], ''Invalid Employee Code Id'',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Employee_Id, '''') = ''''
			END
			IF ((EXISTS(SELECT Company_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Company_Id, '''') = '''')))
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], ''Invalid Company Name'',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE ISNULL(Company_Id, '''') = ''''			
			END
			IF Exists(
			SELECT ImportID FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
						ImportID FROM [TA_Tbl_ImportShiftAllocation]
			)AS A WHERE duplicate>1)
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon],''Duplication Records are Entered'',RecordNumber from
					(
						SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Id,Mon,year ORDER BY Employee_Id ASC)AS duplicate,
						Employee_Code_Id,[Year], [Mon],RecordNumber FROM [TA_Tbl_ImportShiftAllocation] where Employee_Code_Id is not null
					)AS A WHERE duplicate>1
			END
			IF ((EXISTS(SELECT [Year] FROM [TA_Tbl_ImportShiftAllocation] WHERE (CAST((''01-'' + [Mon] + ''-'' + [Year]) AS DATETIME))  < @StartDate)))
			BEGIN
				INSERT INTO @ErrorMsg
					SELECT DISTINCT Employee_Code_Id, [Year], [Mon], ''Past Year Not Allowed'',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE (CAST((''01-'' + [Mon] + ''-'' + [Year]) AS DATETIME))  < @StartDate
			END
			IF(NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			BEGIN
				SELECT @NosId = ISNULL(Shift_Id, -2) FROM TA_Tbl_Shift WHERE Shift_ShortName LIKE ''NOS''
				Declare @i int
				set @i=1
				declare @SQl as nvarchar(MAx)
				set @NosId = ISNULL(@NosId,0)
				while @i<=31
				begin
					set @SQl=''UPDATE [TA_Tbl_ImportShiftAllocation] SET Day''+cast(@i as nvarchar(3)) +'' = (CASE WHEN ISNULL([Day''+cast(@i as nvarchar(3)) +''], '''''''') = '''''''' THEN 0 
					WHEN Day''+cast(@i as nvarchar(3)) +'' = ''''Off'''' THEN -1 
					WHEN Day''+cast(@i as nvarchar(3)) +'' = ''''NOS'''' THEN ''''''+cast(@NosId as nvarchar(3)) +'''''' ELSE ISNULL(S1.Shift_Id, -2) END)
									FROM [TA_Tbl_ImportShiftAllocation] SA
									LEFT JOIN TA_Tbl_Shift S1 ON S1.Shift_ShortName = SA.Day''+cast(@i as nvarchar(3)) +'' AND S1.Level_Id = SA.Company_Id AND S1.Isdeleted = 0''
					Execute(@SQl)
					set @i=@i+1
				end				
				IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE (-2) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31]))
				BEGIN
					INSERT INTO @ErrorMsg
						SELECT DISTINCT Employee_Code_Id, [Year], [Mon], ''Invalid Shift Short Name'',RecordNumber FROM [TA_Tbl_ImportShiftAllocation] WHERE (-2) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31])
				END
			END
			--Commented by Manikandan.R as per the team suggestion on 25-11-2015 11.20 AM
			--IF( NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			--BEGIN
			--	UPDATE [TA_Tbl_ImportShiftAllocation] SET 
			--		Day1 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day1, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day2 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day2, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day3 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day3, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day4 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day4, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day5 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day5, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day6 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day6, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day7 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day7, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day8 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day8, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day9 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day9, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day10 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day10, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day11 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day11, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day12 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day12, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day13 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day13, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day14 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day14, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day15 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day15, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day16 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day16, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day17 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day17, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day18 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day18, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day19 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day19, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day20 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day20, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day21 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day21, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day22 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day22, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day23 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day23, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day24 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day24, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day25 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day25, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day26 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day26, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day27 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day27, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day28 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day28, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day29 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day29, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day30 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day30, (''01-'' + [Mon] + ''-'' + [Year])),
			--		Day31 = Dbo.[Func_TA_GetShiftOverLapped](Employee_Id, Day31, (''01-'' + [Mon] + ''-'' + [Year]))
			--	FROM [TA_Tbl_ImportShiftAllocation]
			--	IF EXISTS(SELECT Employee_Id FROM [TA_Tbl_ImportShiftAllocation] WHERE (-3) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31]))
			--	BEGIN
			--		INSERT INTO @ErrorMsg
			--			SELECT DISTINCT Employee_Code_Id, [Year], [Mon], ''Shift Is Overlapped'' FROM [TA_Tbl_ImportShiftAllocation] WHERE (-3) IN ([Day1], [Day2], [Day3], [Day4], [Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19], [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31])
			--	END
			--END
			IF( NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg))
			BEGIN
				INSERT INTO TA_Tbl_PermanentShiftAllocation
					SELECT SI.Employee_Id, SI.[Year], MONTH(CAST((''01-'' + SI.[Mon] + ''-'' + SI.[Year]) AS DATETIME)), [Day1], [Day2], [Day3], [Day4], 
					[Day5], [Day6], [Day7], [Day8], [Day9], [Day10], [Day11], [Day12], [Day13], [Day14], [Day15], [Day16], [Day17], [Day18], [Day19],
					 [Day20], [Day21], [Day22], [Day23], [Day24], [Day25], [Day26], [Day27], [Day28], [Day29], [Day30], [Day31], 1, GETDATE(), 
					 CAST((''01-'' + SI.[Mon] + ''-'' + SI.[Year]) AS DATETIME) FROM [TA_Tbl_ImportShiftAllocation] SI
						LEFT JOIN TA_Tbl_PermanentShiftAllocation PS ON PS.EmployeeId = SI.Employee_Id AND PS.[Year] = SI.[Year] AND PS.[Month] = MONTH(CAST((''01-'' + SI.[Mon] + ''-'' + SI.[Year]) AS DATETIME))
					WHERE ISNULL(PS.EmployeeId, '''') = ''''
				UPDATE [TA_Tbl_PermanentShiftAllocation] SET
					[Day1Shift] = (CASE WHEN [Day1] = 0 THEN [Day1Shift] ELSE [Day1] END),
					[Day2Shift] = (CASE WHEN [Day2] = 0 THEN [Day2Shift] ELSE [Day2] END),
					[Day3Shift] = (CASE WHEN [Day3] = 0 THEN [Day3Shift] ELSE [Day3] END),
					[Day4Shift] = (CASE WHEN [Day4] = 0 THEN [Day4Shift] ELSE [Day4] END),
					[Day5Shift] = (CASE WHEN [Day5] = 0 THEN [Day5Shift] ELSE [Day5] END),
					[Day6Shift] = (CASE WHEN [Day6] = 0 THEN [Day6Shift] ELSE [Day6] END),
					[Day7Shift] = (CASE WHEN [Day7] = 0 THEN [Day7Shift] ELSE [Day7] END),
					[Day8Shift] = (CASE WHEN [Day8] = 0 THEN [Day8Shift] ELSE [Day8] END),
					[Day9Shift] = (CASE WHEN [Day9] = 0 THEN [Day9Shift] ELSE [Day9] END),
					[Day10Shift] = (CASE WHEN [Day10] = 0 THEN [Day10Shift] ELSE [Day10] END),
					[Day11Shift] = (CASE WHEN [Day11] = 0 THEN [Day11Shift] ELSE [Day11] END),
					[Day12Shift] = (CASE WHEN [Day12] = 0 THEN [Day12Shift] ELSE [Day12] END),
					[Day13Shift] = (CASE WHEN [Day13] = 0 THEN [Day13Shift] ELSE [Day13] END),
					[Day14Shift] = (CASE WHEN [Day14] = 0 THEN [Day14Shift] ELSE [Day14] END),
					[Day15Shift] = (CASE WHEN [Day15] = 0 THEN [Day15Shift] ELSE [Day15] END),
					[Day16Shift] = (CASE WHEN [Day16] = 0 THEN [Day16Shift] ELSE [Day16] END),
					[Day17Shift] = (CASE WHEN [Day17] = 0 THEN [Day17Shift] ELSE [Day17] END),
					[Day18Shift] = (CASE WHEN [Day18] = 0 THEN [Day18Shift] ELSE [Day18] END),
					[Day19Shift] = (CASE WHEN [Day19] = 0 THEN [Day19Shift] ELSE [Day19] END),
					[Day20Shift] = (CASE WHEN [Day20] = 0 THEN [Day20Shift] ELSE [Day20] END),
					[Day21Shift] = (CASE WHEN [Day21] = 0 THEN [Day21Shift] ELSE [Day21] END),
					[Day22Shift] = (CASE WHEN [Day22] = 0 THEN [Day22Shift] ELSE [Day22] END),
					[Day23Shift] = (CASE WHEN [Day23] = 0 THEN [Day23Shift] ELSE [Day23] END),
					[Day24Shift] = (CASE WHEN [Day24] = 0 THEN [Day24Shift] ELSE [Day24] END),
					[Day25Shift] = (CASE WHEN [Day25] = 0 THEN [Day25Shift] ELSE [Day25] END),
					[Day26Shift] = (CASE WHEN [Day26] = 0 THEN [Day26Shift] ELSE [Day26] END),
					[Day27Shift] = (CASE WHEN [Day27] = 0 THEN [Day27Shift] ELSE [Day27] END),
					[Day28Shift] = (CASE WHEN [Day28] = 0 THEN [Day28Shift] ELSE [Day28] END),
					[Day29Shift] = (CASE WHEN [Day29] = 0 THEN [Day29Shift] ELSE [Day29] END),
					[Day30Shift] = (CASE WHEN [Day30] = 0 THEN [Day30Shift] ELSE [Day30] END),
					[Day31Shift] = (CASE WHEN [Day31] = 0 THEN [Day31Shift] ELSE [Day31] END),
					Emp_Id =1,
					[TimeStamp] = GETDATE()
				FROM [TA_Tbl_PermanentShiftAllocation] PS
					LEFT JOIN [TA_Tbl_ImportShiftAllocation] SI ON PS.EmployeeId = SI.Employee_Id AND PS.[Year] = SI.[Year] AND PS.[Month] = MONTH(CAST((''01-'' + SI.[Mon] + ''-'' + SI.[Year]) AS DATETIME))
				WHERE ISNULL(SI.Employee_Id, '''') <> ''''
				Create table #TempShiftImport(Autoid int identity(1,1),Employee_Code_id varchar(50),date datetime)
				insert into #TempShiftImport 
				select employee_code_id,''01-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day1!=0 union all
				select employee_code_id,''02-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day2!=0 union all
				select employee_code_id,''03-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day3!=0 union all
				select employee_code_id,''04-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day4!=0 union all
				select employee_code_id,''05-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day5!=0 union all
				select employee_code_id,''06-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day6!=0 union all
				select employee_code_id,''07-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day7!=0 union all
				select employee_code_id,''08-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day8!=0 union all
				select employee_code_id,''09-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day9!=0 union all
				select employee_code_id,''10-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day10!=0 union all
				select employee_code_id,''11-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day11!=0 union all
				select employee_code_id,''12-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day12!=0 union all
				select employee_code_id,''13-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day13!=0 union all
				select employee_code_id,''14-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day14!=0 union all
				select employee_code_id,''15-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day15!=0 union all
				select employee_code_id,''16-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day16!=0 union all
				select employee_code_id,''17-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day17!=0 union all
				select employee_code_id,''18-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day18!=0 union all
				select employee_code_id,''19-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day19!=0 union all
				select employee_code_id,''20-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day20!=0 union all
				select employee_code_id,''21-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day21!=0 union all
				select employee_code_id,''22-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day22!=0 union all
				select employee_code_id,''23-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day23!=0 union all
				select employee_code_id,''24-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day24!=0 union all
				select employee_code_id,''25-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day25!=0 union all
				select employee_code_id,''26-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day26!=0 union all
				select employee_code_id,''27-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day27!=0 union all
				select employee_code_id,''28-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day28!=0 union all
				select employee_code_id,''29-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day29!=0 union all
				select employee_code_id,''30-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day30!=0 union all
				select employee_code_id,''31-''+MON+''-''+Year as date from TA_Tbl_ImportShiftAllocation where Day31!=0 
				--Delete The [TA_Tbl_ProcessedData] To Reprocess The Allocated Days
				DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=SI.date
				--DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=DATEADD(d,1,SI.date)
				--DELETE FROM [TA_Tbl_ProcessedData] FROM [TA_Tbl_ProcessedData] PD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Employee_Code_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.[Date]=DATEADD(d,-1,SI.date)
				--Delete The [ta_tbl_MatchedPunches] To Reprocess The Allocated Days
				--Added By Manikandan.R -- on 04-09-2014
				DELETE FROM [ta_tbl_MatchedPunches] FROM [ta_tbl_MatchedPunches] PD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = PD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND PD.Clk_Date=SI.date
				--Delete The [TA_Tbl_ClockDetails] To Reprocess The Allocated Days
				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_Date=SI.date
				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_InDate=DATEADD(d,0,SI.date)
				DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD 
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = CD.Clk_EmpId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND CD.Clk_OutDate=DATEADD(d,0,SI.date)
				--Update The Clk_Process = ''N'' To [TA_Tbl_ManualTimeEntry] To Reprocess The Allocated Days
				UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' FROM TA_Tbl_ManualTimeEntry MTE 
				INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND MTE.ManualTimeEntry_InDate=SI.date
				UPDATE TA_Tbl_ManualTimeEntry SET Clk_Process = ''N'' FROM TA_Tbl_ManualTimeEntry MTE 
				INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND MTE.ManualTimeEntry_OutDate=SI.date
				--Update The Clk_Flag = 0, Clk_Process = 0 To [TA_Tbl_Clk_RawData] To Reprocess The Allocated Days
				UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND 
				Clk_Date BETWEEN DateAdd(d,-1,SI.date) AND DateAdd(d,1,SI.date)				
				--UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND RD.Clk_Date=SI.date
				--UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0, Clk_Process = 0 FROM TA_Tbl_Clk_RawData RD
				--INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo = RD.Clk_CardId AND E.IsDeleted = 0 AND E.Employee_Status = 1
				--INNER JOIN #TempShiftImport SI ON E.SwipeCardNo = SI.Employee_Code_Id AND RD.Clk_Date=SI.date
				DELETE FROM [TA_Tbl_ImportShiftAllocation]						
			END
			ELSE 
			BEGIN
				update IM set IM.Employee_Id=E.Employee_Code_ID from @ErrorMsg IM inner join TA_Tbl_Employee E on E.SwipeCardNo=IM.Employee_Id
				SELECT * FROM @ErrorMsg
			END
		COMMIT TRAN ImportShiftMaster
			SELECT ''Msg:ShiftImportSuccessfully'' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = (CASE WHEN ERROR_MESSAGE() LIKE ''Conversion failed%'' THEN ''Kindly Check Year/Month Format'' ELSE ERROR_MESSAGE() END )
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportShiftMaster
		RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
		--SELECT ''Error:'' + (CASE WHEN @ErrMsg LIKE ''Conversion failed when converting date and/or time from character string.'' THEN ''Kindly Check Year/Month Format'' ELSE @ErrMsg END) [Message]
	END CATCH	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectUsergroupDetailsForSMS]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectUsergroupDetailsForSMS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <07-09-2016>
-- Description:	<Getting Usergroup details for sms template using templateID>
-- execute Proc_TA_SelectUsergroupDetailsForSMS 3
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectUsergroupDetailsForSMS] 
	-- Add the parameters for the stored procedure here
	@TemplateID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if not exists(select Usergroupid from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID)
	begin
		select groupId,groupName,0 as Status from TA_Tbl_Usergroup where isDeleted=0
	end
	else
	begin
		select groupId,groupName,
		isnull((select 1 from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID and Usergroupid=ug.groupId),0)as status from TA_Tbl_Usergroup ug
		where isDeleted=0
	end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplicationConversation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionApplicationConversation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdatePermissionApplicationConversation]
	-- Add the parameters for the stored procedure here
	@PermissionApplicationId int,
	@status nvarchar(50), 
	@commentsBy int,
	@remarks nvarchar(1050),
	@empAutoId int
AS
DECLARE @leaveConversationCount as int 
DECLARE @orderBy as int 
BEGIN
	SET NOCOUNT ON;
	SELECT @leaveConversationCount=COUNT(*) FROM TA_Tbl_PermissionConversation WHERE PermissionId = @PermissionApplicationId
	SET @orderBy = @leaveConversationCount + 1
	INSERT INTO TA_Tbl_PermissionConversation(PermissionId,CommentsBy,Comments,OrderBy,Emp_Id) VALUES(@PermissionApplicationId, @commentsBy, @remarks, @orderBy, @empAutoId)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdatePermissionApplication]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdatePermissionApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_UpdatePermissionApplication
Description	:	Update Permisssion Details of Employees Based on their Permission_Id
Tables Included	:	TA_Tbl_Permission
Created By	:	Prabakaran
Created On	:	20-Jul-07
Modified By	:	Prabakaran.P
Modified On	:	17-Mar-08
--Proc_TA_UpdatePermissionApplication
*/
CREATE procedure [dbo].[Proc_TA_UpdatePermissionApplication]
	@Permission_Id bigint,
	@PermissionType nvarchar(30),
	@PermissionDate datetime,
	@Permission_FromTime datetime,
	@Permission_EndTime datetime,
	@Reason nvarchar(1000),
	@auEmpId nvarchar(50),
	@status nvarchar(25),
	@CCMail varchar(3000),
	@Permission_Hours varchar(5),
	@YearSettingId varchar(5)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(4000)
	declare @IsDeleted int
	set @Isdeleted=0
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@PermissionDate as nvarchar(50)), 102) and EL.LevelId is not null
	--set @sql=''''
	--set @sql=''update TA_Tbl_Permission set Permission_Date='''''' + convert(nvarchar(20),@PermissionDate,101) +'''''',
	--Permission_Type=N'''''' + @PermissionType + '''''',Permission_FromTime='''''' + cast(@Permission_FromTime as nvarchar(100)) + '''''',Permission_ToTime='''''' + cast(@Permission_EndTime as nvarchar(100)) + '''''',''
	--if(@status=''Pending'' or @status=''Forwarded'')
	--begin
	--set @sql=@sql + ''Permission_Reason='''''' + @Reason + '''''',''
	--end
	--set @sql=@sql + ''Permission_Status='''''' + @status + '''''',CCMail='''''' + @CCMail + '''''',No_Of_Hours='''''' + @Permission_Hours + '''''',Permission_Hours='''''' + @Permission_Hours + '''''',IsDeleted='''''' + cast(@Isdeleted as nvarchar(10)) + '''''',Emp_Id=N''''''+ @auEmpId+'''''',YearSettings_Id='''''' +@YearSettingId+'''''' 
	--where Permission_Id='''''' + cast(@Permission_Id as nvarchar(25)) + '''''' ''
	----where Permission_Id='''''' + cast(@Permission_Id as nvarchar(25)) + '''''' and Permission_Status='''''' + ''Pending''+ '''''' ''
	--exec(@sql)
	
	update TA_Tbl_Permission set Permission_Date=convert(nvarchar(20),@PermissionDate,101),
	Permission_Type=@PermissionType,
	Permission_FromTime=cast(@Permission_FromTime as nvarchar(100)),
	Permission_ToTime=cast(@Permission_EndTime as nvarchar(100)),
	Permission_Reason=@Reason,	
	Permission_Status=@status,
	CCMail=@CCMail,
	No_Of_Hours=@Permission_Hours,
	Permission_Hours=@Permission_Hours,
	IsDeleted=cast(@Isdeleted as nvarchar(10)),
	Emp_Id=@auEmpId,
	YearSettings_Id=@YearSettingId
	where Permission_Id=cast(@Permission_Id as nvarchar(25))
	
	SELECT P.Permission_Id, LD.Id AS LevelId,P.Permission_Reason as Reason,P.Unplanned FROM TA_Tbl_Permission P
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = P.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
	INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
	WHERE P.Permission_Id = @Permission_Id
	--Remove the temporary tables here  
	drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateHoliday]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_UpdateHoliday](@HolidayId int,@Type char(1),@HolidayType nvarchar(2),@Holiday_FromDate nvarchar(15),@Holiday_Todate nvarchar(15),@Holiday_Description nvarchar(255) )  
AS
BEGIN
	UPDATE TA_Tbl_Holiday SET Holiday_Type=@HolidayType,Holiday_FromDate=@Holiday_FromDate,Holiday_ToDate=@Holiday_Todate,Holiday_Description=@Holiday_Description  WHERE Holiday_Id=@HolidayId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateEncashmentDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateEncashmentDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
Procedure Name : Proc_TA_UpdateEncashmentDetails    
Description : update Records in TA_Tbl_Encashment    
Tables Included : TA_Tbl_Encashment    
Created By : Prabakaran    
Created On : 23-Mar-09  
Modified By :    
Modified On :    
*/    
CREATE procedure [dbo].[Proc_TA_UpdateEncashmentDetails]    
@EncashmentId bigint,    
@NumberOfDays decimal(18,1),    
@Reason nvarchar(50)    
as    
declare @YearSettingId bigint    
begin    
update TA_Tbl_Encashment set NumberOfDays=@NumberOfDays,Reason=@Reason where EncashmentId=@EncashmentId  
end    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDepartmentToCCMailIds]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By	: Prabakaran.P
Created On	: 17-Dec-09
*/
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDepartmentToCCMailIds]
@LevelId int,  
@ToMailIds varchar(4000), 
@CCMailIds varchar(4000)
AS
BEGIN
Update TA_Tbl_LevelDetails set ToMailIds=@ToMailIds,
CCMailIds=@CCMailIds where Id=@LevelId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ValidateOndutyForImport]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ValidateOndutyForImport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <06-Apr-2019 07:16PM>
-- Description:	<Checking whether onduty entry already available or not>
-- Proc_TA_ValidateOndutyForImport ''787'',3,''2019-04-01''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ValidateOndutyForImport]
	@EmpCode varchar(50),
	@ShiftID int,
	@Date varchar(12)
AS
BEGIN
	SET NOCOUNT ON;
	Declare @Shift_StartTime varchar(6)
	Declare @Shift_EndTime varchar(6)
	SELECT @Shift_StartTime=Shift_StartTime,@Shift_EndTime=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID
	DECLARE	@return_value int
	EXEC	[dbo].[Proc_TA_CheckManualODEntry]
	@EmpCode = @EmpCode,@ManualInDate = @Date,@ManualInTime = @Shift_StartTime,@ManualOutDate = @Date,@ManualOutTime = @Shift_EndTime
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateSMSTemplateDetails]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateSMSTemplateDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <06-09-2016>
-- Description:	<Updating Receivers Details for single Templates>
-- select Value from dbo.Split(''Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights'','';'')
-- Proc_TA_UpdateSMSTemplateDetails 2,''Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights'',''01:00'',''01:00'',''Dear {User Name}, The following employees are late comers today,{Employee ID}-{Employee Name}-{Late By Hrs}.'',1
-- Proc_TA_UpdateSMSTemplateDetails 2,''Individual User Testing;Sanction User I Level;Sanction User II Level;Special User without rights'',''01:00'',''01:00'',''Dear {User Name}, The following employees are late comers today,{Employee ID}-{Employee Name}-{Late By Hrs}.'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateSMSTemplateDetails]
	-- Add the parameters for the stored procedure here
	@TemplateID int,
	@Receivers varchar(max),
	@firstNotification varchar(5),
	@secondNotification varchar(5),
	@Message varchar(max),
	@ModifiedBy varchar(50),
	@ToEmployee int,
	@LessHrsLimitation varchar(5),
	@Continue_AbsentDays int,
	@RepoFilters varchar(max),
	@ReportType varchar(50),
	@Tags varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	if exists(select COUNT(*) from Ta_Tbl_SMSTemplates where id=@TemplateID)
	begin
		update Ta_Tbl_SMSTemplates set Message=@Message,LastModified=GETDATE(),ModifiedBy=@ModifiedBy,First_TriggeringTime=@firstNotification,
		Second_TriggeringTime=@secondNotification,ToEmployee=@ToEmployee,LessHrsLimitation=@LessHrsLimitation,Continue_AbsentDays=@Continue_AbsentDays
		,Tags=@Tags
		where id=@TemplateID
		if exists(select * from Ta_tbl_SMSTemplateFilters where TemplateId=@TemplateID)
		begin
			update Ta_tbl_SMSTemplateFilters set Filters= @RepoFilters,ReportType=@ReportType where TemplateId=@TemplateID
		end
		else
		begin
			if(@RepoFilters!='''')
			begin
				insert into Ta_tbl_SMSTemplateFilters values(@TemplateID,@RepoFilters,@ReportType)
			end
		end
		Create table #SplittedgrpIDs(id int identity(1,1),ids varchar(max))
		insert into #SplittedgrpIDs select Value from dbo.Split(@Receivers,'';'')
		delete from Ta_Tbl_SMSReceivers where TemplateId=@TemplateID		
		Declare @Count int
		Declare @Start int
		Declare @Ids varchar(100)
		SET @Start=1
		SET @Count=(select COUNT(*) from #SplittedgrpIDs)		
		while @Count>=@Start
		begin			
			select @ids=ids from #SplittedgrpIDs where id=@Start
			if exists(select groupId from TA_Tbl_Usergroup where groupName=@Ids)
			begin
				insert into Ta_Tbl_SMSReceivers values((select top 1 groupId from TA_Tbl_Usergroup where groupName=@Ids),@TemplateID,GETDATE(),@ModifiedBy)
			end
			set @Start=@Start+1
		end		
	end  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <19/07/2019>
-- Description:	<Update Shift Id in permenent table for Vaigai - Reg Auto Shift Configuration>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateShiftinPermenentShiftAllocation]
@Shift_Id int, @EmployeeCodeId varchar(40), @ShiftDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @year INT
	DECLARE @month INT
	DECLARE @day INT
	DECLARE @DynamicQuery VARCHAR(MAX)
	declare @EmployeeId int
	SELECT @year=DATEPART(YEAR,@ShiftDate),@month=DATEPART(MONTH,@ShiftDate),@day=DATEPART(DAY,@ShiftDate) 
	select @EmployeeId = isnull(Employee_Id,0) from TA_Tbl_Employee where Employee_Code_Id = @EmployeeCodeId
	SET @DynamicQuery =''''
	--update in permenent shift allcoation table for reuse of same shift id in process data service reg auto shift configuration
	IF EXISTS(Select isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration where EmployeeId = @EmployeeId)
	Begin
		if exists(select employeeId from TA_Tbl_PermanentShiftAllocation where month=@month and year=@year and employeeid=@EmployeeId)
		begin
			SET @DynamicQuery =@DynamicQuery +''update TA_Tbl_PermanentShiftAllocation set day''+CONVERT(VARCHAR(2),@day)+''shift=''+CONVERT(VARCHAR(2),@Shift_Id)+ '' where
			month=''+CONVERT(VARCHAR(2),@month)+'' and year=''+CONVERT(VARCHAR(4),@year)+'' and employeeid=''+CONVERT(VARCHAR(40),@EmployeeId)
		end
		else
		begin
			SET @DynamicQuery =@DynamicQuery +''insert into TA_Tbl_PermanentShiftAllocation (day''+CONVERT(VARCHAR(2),@day)+''shift,month,year,employeeid,Emp_id,dateshift)
			values(''+CONVERT(VARCHAR(2),@Shift_Id)+ '',''+CONVERT(VARCHAR(2),@month)+'',''+CONVERT(VARCHAR(4),@year)+'',''+CONVERT(VARCHAR(40),@EmployeeId)+'',1,''''''+Convert(varchar(11),DATEADD(dd,-(DAY(getdate())-1),getdate()))+'''''')''
		end
		exec (@DynamicQuery)
	End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectChildrenDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectChildrenDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectChildrenDetails]
(
@empID INT
)
AS
BEGIN
	SELECT ChildEmp_ID,Emp_ID,Name,CONVERT(NVARCHAR,DOB,101) AS DOB FROM TA_Tbl_EmpChildrenDetails WHERE Emp_ID=@empID AND Spouse_Child=''C'' AND Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailIDByLevel]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailIDByLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmailIDByLevel] 
	@id as int
AS
BEGIN
	select TomailIds, CcMailIDs from ta_tbl_leveldetails where id=@id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectDiscrepancy]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectDiscrepancy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- [Proc_TA_SelectDiscrepancy] ''788'',''09/02/2014''
--	Modified by		:	Manjula.P
--	ModifiedOn		:	10-May-2014
--	Descriptinos	:	Changing this procedure for PRODUCT Migration from angler timecheckv1.5
CREATE    PROCEDURE [dbo].[Proc_TA_SelectDiscrepancy]      
(
	@EmployeeID VarChar(50), 	
	@Date VarChar(50)
)      
AS      
BEGIN  
	SET NOCOUNT ON;
    create table #TempProcessedData(Shift_Id int,Date datetime,Employee_Code_Id varchar(20))
    insert into  #TempProcessedData 
	select TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
	from TA_Tbl_ProcessedData where Date = CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102)
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
		 Declare @SelectSQL As Varchar(6000)      
		 Set @SelectSQL = '' ''        
		 Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id AS CardNo,ED.employee_id AS EmployeeAutoId, ''      
		 Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		 Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''EmpName'''', ''      
		Set @SelectSQL = @SelectSQL + ''CD.Clk_InDeviceId as InReaderID,ITer.Terminal_Name as InTerminalName,
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, Clk_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, Clk_InDate, ''+cast(@dateFormat as varchar(100))+'') end
		as InDate, 
		case	when (''''''+@TimeFormat+'''''')=''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Clk_InTime,0)), 114)
			    else	substring(convert(varchar(20),Clk_InTime),13,5)+'''' '''' + substring(convert(varchar(20),Clk_InTime),18,2) 					
		end as InTime ,''
		Set @SelectSQL = @SelectSQL + ''CD.Clk_OutDeviceId as OutReaderID,OTer.Terminal_Name as OutTerminalName,
			case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, Clk_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, Clk_OutDate, ''+cast(@dateFormat as varchar(100))+'') end as OutDate, 
	case	when (''''''+@TimeFormat+'''''')=''''hh:mm'''' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Clk_OutTime,0)), 114)
			    else	substring(convert(varchar(20),Clk_OutTime),13,5)+'''' '''' + substring(convert(varchar(20),Clk_OutTime),18,2) 					
		end
	as OutTime,
			case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, Clk_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, Clk_Date, ''+cast(@dateFormat as varchar(100))+'') end  ClockDate,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime FROM TA_Tbl_Employee ED ''      
        Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_ClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
        set @SelectSQL = @SelectSQL + '' inner join #TempProcessedData on #TempProcessedData.Employee_Code_Id = ED.SwipeCardNo and #TempProcessedData.Date = CD.CLK_Date''  
        set @SelectSQL = @SelectSQL + '' left join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id'' 
		Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID ''       
		Set @SelectSQL = @SelectSQL + '' Where CD.IsVoid = 0 AND ED.IsDeleted = ''''0'''' and ED.report_exclude=0''
		 If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + ''And ED.swipecardno = '''''' + @EmployeeId + '''''' ''      
		 End      
		 If (@Date <> '''')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + ''And CD.Clk_Date = '''''' + @Date + '''''' ''      
		 End      
		  Set @SelectSQL = @SelectSQL + '' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc''      
 	Exec (@SelectSQL)            
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
 =============================================    
 Author:  Arun vinoth    
 ALTER  date: 30/07/2007    
 Description: select Emp Leave Policy details  
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Procedure Name	:	Proc_TA_SelectEmp_LeavePolicyDetais 5
Description	:	Display Employee Leave Policy of active year Based on employee Leave
			Policy Year Setting Id
 =============================================    
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectEmp_LeavePolicyDetais]    
 -- Add the parameters for the stored procedure here    
@EmpID INT    
AS    
BEGIN    
 SET NOCOUNT ON;    
SELECT ELP.LeavePolicy_Id,LP.PolicyName,CONVERT(NVARCHAR,ELP.FromDate,101) AS FromDate,CONVERT(NVARCHAR,ELP.ToDate,101) AS ToDate   
FROM TA_Tbl_Emp_LeavePolicy ELP  
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id   
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND YS.Isactive=1  order by ELP.Emp_LeavePolicyId 
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmailScheduleBasedOnId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- Proc_TA_SelectEmailScheduleBasedOnId 42
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmailScheduleBasedOnId]
(
  @ScheduleId int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @ToEmailList VARCHAR(8000)
	DECLARE @CCEmailList VARCHAR(8000)
	SELECT @ToEmailList = COALESCE(@ToEmailList + '';'', '''') + CAST(EmailID AS VARCHAR(100))
	FROM   TA_tbl_MailIdsForTriggeringEmail
	WHERE  ScheduleId = @ScheduleId and MailType = ''To''
	SELECT @CCEmailList = COALESCE(@CCEmailList + '';'', '''') + CAST(EmailID AS VARCHAR(100))
	FROM   TA_tbl_MailIdsForTriggeringEmail
	WHERE  ScheduleId = @ScheduleId and MailType = ''CC''
    select *,@ToEmailList as ToEmailList,@CCEmailList as CCEmailList from TA_Tbl_EmailSchedule ES
    inner join TA_Tbl_EmailTemplate ET on ES.ScheduleId = ET.ScheduleId
    inner join TA_Tbl_EmailScheduleFilters F on ES.ScheduleId = F.ScheduleId
    inner join TA_Tbl_Page P on P.pageId = ES.ReportId
    inner Join TA_Tbl_Employee E on E.Employee_Id=ES.EmployeeId
    where ES.ScheduleId = @ScheduleId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeesForBL]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectEmployeesForBL]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectEmployeesForBL]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select TA_Tbl_Employee.Employee_Id,TA_Tbl_Employee.SwipeCardNo,Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota,TA_Tbl_YearSetting.FromDate,TA_Tbl_YearSetting.ToDate from Ta_Tbl_EmployeeBonusLeave
    INNER JOIN TA_Tbl_Employee ON  TA_Tbl_Employee.Employee_Id=Ta_Tbl_EmployeeBonusLeave.EmployeeId
    INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearSetting.YearSettings_Id=Ta_Tbl_EmployeeBonusLeave.YearSettingId
    Where TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_YearSetting.IsActive=1 and Ta_Tbl_EmployeeBonusLeave.BonusLeaveQuota >0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By	:  R.Manikandan
Modified On 	:  22-11-2016 16.53
*/
-- Proc_TA_SelectEntranceDetails ''A'', 0, ''SuperAdmin'' 
CREATE PROCEDURE [dbo].[Proc_TA_SelectEntranceDetails]
(    
	@TYPE CHAR(1)='''',    
	@EntranceID INT,
	@UserGroupName nVarchar(50)    
)    
AS  
BEGIN    
	set nocount on
	DECLARE @Isdeleted INT
	SET @Isdeleted=0
	Create table #tempEntrance(ID int,Name nvarchar(510),Entrance_Id int,Entrance_Name nvarchar(100),Entrance_Description nvarchar(500),
	NoOfInTerminals int,NoOfOutTerminals int,IsDeleted nvarchar(10),flag int)
	Create table #Tempclkrawdata(id int identity(1,1),CLK_DEVICEID varchar(30))
	CREATE NONCLUSTERED INDEX IDX_CLK_DEVICEID ON [dbo].#Tempclkrawdata(CLK_DEVICEID ASC) ON [PRIMARY]
	insert into #Tempclkrawdata	
	select distinct CLK_DEVICEID from TA_Tbl_Clk_RawData
	where CLK_DEVICEID not in
	(
		select T.Terminal_ReaderID from TA_Tbl_Terminal T
		inner join TA_Tbl_Entrance_INOUTDetails EIO on T.Terminal_Id=EIO.Reader_Id
		inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
		where flag=1
	)
	update TA_Tbl_Entrance set flag=1 from TA_Tbl_Entrance E
	inner join TA_Tbl_Entrance_INOUTDetails EIO on E.Entrance_Id=EIO.Entrance_Id
	inner join TA_Tbl_Terminal T on T.Terminal_Id=EIO.Reader_Id
	inner join #Tempclkrawdata TC on TC.CLK_DEVICEID=T.Terminal_ReaderID
	where E.flag!=1
	update TA_Tbl_Entrance set flag=1 from TA_Tbl_Entrance E
	inner join TA_Tbl_Entrance_INOUTDetails EIO on E.Entrance_Id=EIO.Entrance_Id
	inner join TA_Tbl_ManualTimeEntry M on (EIO.Reader_Id = M.ManualTimeEntry_InReaderID OR EIO.Reader_Id = M.ManualTimeEntry_OutReaderID)
	where E.flag!=1
	IF (@TYPE=''A'')    
	BEGIN
		IF(@UserGroupName = ''SuperAdmin'')
			BEGIN 
				insert into #tempEntrance
				SELECT '''',O.levelName,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,'''','''',
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E     
				LEFT OUTER JOIN TA_Tbl_Level O ON O.levelID=E.OrgLevel_Id where E.Entrance_Name!=''TimecheckPhase''
			END
		ELSE
			BEGIN   
				insert into #tempEntrance
				SELECT '''',O.levelName,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,'''','''',
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_Level O ON O.levelID=E.OrgLevel_Id WHERE E.Isdeleted=@Isdeleted
				and E.Entrance_Name!=''TimecheckPhase''   
			END
	END
	ELSE IF (@TYPE=''P'')    
	BEGIN
		IF(@UserGroupName = ''SuperAdmin'')
			BEGIN 
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID
				and E.Entrance_Name!=''TimecheckPhase''
			END
		ELSE
			BEGIN
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID AND E.IsDeleted=@Isdeleted    
				and E.Entrance_Name!=''TimecheckPhase''   
			END
	END
	ELSE If (@TYPE=''I'')    
	BEGIN
		IF(@UserGroupName = ''SuperAdmin'')
			BEGIN 
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE Entrance_Id=@EntranceID 
				and E.Entrance_Name!=''TimecheckPhase''   
			END
		ELSE
			BEGIN
				insert into #tempEntrance
				SELECT O.ID,O.Name,E.Entrance_Id,E.Entrance_Name,E.Entrance_Description,E.NoOfInTerminals,E.NoOfOutTerminals,
				case when E.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(E.Flag,0) FROM TA_Tbl_Entrance E    
				LEFT OUTER JOIN TA_Tbl_LevelDetails O ON O.ID=E.OrgLevel_Id WHERE E.Isdeleted=@Isdeleted AND Entrance_Id=@EntranceID    
				and E.Entrance_Name!=''TimecheckPhase''   
			END
	END
    select * from #tempEntrance
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectforcheckLP]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectforcheckLP]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectforcheckLP]
@EmpID INT
as
Begin
select LeavePolicy_Id from ta_tbl_emp_Leavepolicy where EmployeeId=@EmpID
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEntranceINOUTDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEntranceINOUTDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Procedure Name : Proc_TA_SelectEntranceINOUTDetails
-- Tables Used : TA_Tbl_Entrance_InOutDetails,TA_Tbl_Terminal
-- Author : Kumuthini.L
-- Created On : 17-Mar-2008
-- Modified by:Manikandan.R
-- on: 22-11-2016 17.36
-- Purpose : Used to get the In Terminal or Out Terminal Details based on the Entrance Id and Type
CREATE  PROCEDURE [dbo].[Proc_TA_SelectEntranceINOUTDetails]
(
	@Entrance_Id INT,
	@PunchType nVarchar(10) 
)
AS
BEGIN
	SET NOCOUNT ON
    SELECT T.Terminal_Name,T.Terminal_ReaderID,E.Reader_Id FROM TA_Tbl_Entrance_InOutDetails E
	Inner join TA_Tbl_Terminal T on E.Reader_Id = T.Terminal_Id 
    WHERE E.Entrance_Id = @Entrance_Id AND Type = @PunchType
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveDetails_YearClosure]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveDetails_YearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_SelectLeaveDetails_YearClosure] 
(  
@EmpID INT,  
@YearID INT  
)  
AS  
select LPD.* from TA_Tbl_LeavePolicydetails LPD  
INNER JOIN TA_Tbl_Emp_LeavePolicy ELP on ELP.LeavePolicy_Id=LPD.Policy_Id  
INNER JOIN TA_Tbl_LeavePolicy LP ON LPD.Policy_Id=LP.Policy_Id  
where ELP.EmployeeId=@EmpID   
and ELP.YearSettingId=@YearID  and ELP.Isdeleted=0 and LP.IsDeleted=0
and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmpID 
order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- Create date: 29 June 2007
-- Description:	Leave policy - select
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetails] 
	-- Add the parameters for the stored procedure here
	@Policy_ID Varchar(50)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	BEGIN
		SELECT L.LeaveType,L.LeaveDescription,LP.*,isnull(L.isWFH,0) as isWFH FROM TA_Tbl_LeavePolicyDetails LP
		inner join TA_Tbl_LeaveType L ON LP.LeaveType_Id =L.LeaveType_Id
		WHERE LP.Policy_Id=@Policy_ID
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicy]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
    -- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: 29 June 2007  
-- Description: Leave policy - select  
-- Modified By : Kumuthini.L
-- Modified On : 06-Feb-2008
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
Modified by	:	Manikandan.R
Modified on	:	15-Oct-11
Description	:	Year closure changes
[Proc_TA_SelectLeavePolicy] ''A'',0,''Superadmin''
-- =============================================  
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeavePolicy]   
 @Type CHAR(1)='''',  
 @Policy_Id INT=0,  
 @UserGroupName nVarchar(250)
AS  
BEGIN  
	SET NOCOUNT ON;  
	IF (@Type=''A'')
		BEGIN  
			IF(@UserGroupName = ''SuperAdmin'')
				BEGIN
					SELECT LP.*,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'''') into #tempLeavePolicy FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					Update #tempLeavePolicy set flag=0 from #tempLeavePolicy TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePolicy		
				END
			ELSE
				BEGIN
					SELECT LP.*,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'''') into #tempLeavePol FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					WHERE LP.IsDeleted=0 
					Update #tempLeavePol set flag=0 from #tempLeavePol TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol	
				END  
		END
	ELSE IF (@Type=''P'')  
		BEGIN  
			IF(@UserGroupName = ''SuperAdmin'')
				BEGIN
					SELECT LP.*, getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'''') into #tempLeavePol2  FROM TA_Tbl_LeavePolicy LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id
					WHERE Policy_Id=@Policy_Id
					Update #tempLeavePol2 set flag=0 from #tempLeavePol2 TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol2	
				END
			ELSE
				BEGIN
					SELECT LP.*,getdate() as YearSetting,(select categoryname from TA_Tbl_Category where CategoryId=EmployeeCategory)as EmployeeCategorys,
					(select Typename from TA_Tbl_Type where TypeId=EmployeeType)as EmployeeTypes,
					(select Name from TA_Tbl_Religion where ID=Religion)as Religions,1 as flag,CompanyName=isnull(LD.name,'''') into #tempLeavePol3  FROM TA_Tbl_LeavePolicy  LP
					Left Outer join Ta_Tbl_levelDetails LD on LP.companyid=LD.id	
					WHERE Policy_Id=@Policy_Id AND LP.IsDeleted=0
					Update #tempLeavePol3 set flag=0 from #tempLeavePol3 TL inner join TA_Tbl_Emp_LeavePolicy ELP on TL.Policy_id=ELP.LeavePolicy_Id
					select * from #tempLeavePol3	 
				END
		END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationById]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectLeaveApplicationById 10
Modified by		:	Prabakaran.P
Modified on		:	20-Feb-08
Description		:	Select Leave Application details based on Leave Application Id
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationById]
(
	@LeaveApplication_Id int
)
AS
	declare @strLeaveType as nvarchar(50)
BEGIN
	SET NOCOUNT ON;
	set @strLeaveType=(select Type from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and isdeleted=0)
	if(@strLeaveType=''Leave'' or @strLeaveType=''LOP'')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			lt.LeaveType as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id,
			isnull(lt.isWFH,0) as isWFH
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_LeaveType lt   
			on la.LeaveType_Id = lt.LeaveType_Id   
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and lt.Isdeleted=0
		end
	else if(@strLeaveType=''Comp Off'' or @strLeaveType=''ESI'')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			''Others'' as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id ,
			0 as isWFH
			from  TA_Tbl_LeaveApplication la  
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0
		end
	if(@strLeaveType=''Restricted Holiday'')
		begin
			select la.LeaveApplication_Id as LeaveApplication_Id,
			la.Employee_Id as Employee_Id,
			la.Leave_ApplicationDate as Leave_ApplicationDate,
			la.LeaveType_id as LeaveType_id,
			la.Type as Type,
			h.Holiday_Description as LeaveType,
			la.Leave_FromDate as Leave_FromDate,
			la.Leave_ToDate as Leave_ToDate,
			la.Leave_SessionFrom as Leave_SessionFrom,
			la.Leave_SessionTo as Leave_SessionTo,
			la.NumberOfDays as NumberOfDays,
			la.Reason as Reason,
			la.Status as Status,
			la.IsDeleted as IsDeleted,
			la.Remarks as Remarks,
			la.IsBorrow as IsBorrow,
			la.YearSettings_Id,
			0 as isWFH
			from  TA_Tbl_LeaveApplication la  
			inner join  TA_Tbl_Holiday h  
			on la.LeaveType_Id = h.Holiday_Id   
			where la.LeaveApplication_Id = @LeaveApplication_Id and la.IsDeleted=0 and h.Isdeleted=0
		end
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth_Testing]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxDayMonth_Testing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE   PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth_Testing]    
 -- Add the parameters for the stored procedure here    
@EmpID INT ,
@intLeaveTypeId INT,
@FromDate datetime ,
@isAccumulated bit,
@LeaveApplicationId int=0
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON; 
 declare @LeaveTypeId int=0;
 set @LeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType=''CL'');
 declare @Todate as datetime;
 declare @YearSettingId as int
 set @YearSettingId = (select YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate)   
 set @Todate=(SELECT isnull(max(Leave_ToDate),@FromDate) FROM TA_Tbl_LeaveApplication WHERE Employee_Id = @EmpID AND Status<>''Rejected'' 
 and IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>''LOP'' and YearSettings_Id=@YearSettingId)
if(@Todate>= @FromDate)
set @Todate=@Todate
else
set @Todate=@FromDate
    -- Insert statements for procedure here    
declare @fltMaxDays as decimal(18,2)
set @fltMaxDays =(SELECT top 1 isnull(cast(LPD.MaxDays_applicable as float)/12,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
--Following code commented by Prabakaran.P on 15-Feb-08, changes based on Year closure modification
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id 
-- inner join Ta_tbl_Yearsetting YS on LP.Policy_Year=YS.YearSettings_Id  
--LEFT OUTER JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id=EL.LeavePolicy_Id    
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
--for getting accumulated months availabel leaves By Manjula.P on 27-May-2013
declare @TotalMonth as int
set @TotalMonth=(
select ISNULL( DATEDIFF(MONTH,YS.FromDate,@Todate),0) as month from TA_Tbl_YearSetting YS
where YS.YearSettings_Id=@YearSettingId )
set @TotalMonth= @TotalMonth+1
--getting applied leave days count
declare @AppliedDays as decimal(18,2)=0;
IF (EXISTS(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
where 
Leave_ToDate between YS.FromDate and @Todate
and 
Employee_Id=@EmpID 
and 
LA.Status<>''Rejected'' and LA.IsDeleted=0  and LeaveType_id =@LeaveTypeId and type<>''LOP'' and type<>''Comp Off'' and LeaveApplication_Id<>@LeaveApplicationId
and YS.YearSettings_Id=@YearSettingId
) and @intLeaveTypeId = @LeaveTypeId)
	begin
	set @AppliedDays=(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
	where 
	Leave_ToDate between YS.FromDate and @Todate 
	and 
	Employee_Id=@EmpID 
	and 
	LA.Status<>''Rejected'' and LA.IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>''LOP'' and type<>''Comp Off'' and LeaveApplication_Id<>@LeaveApplicationId
	and YS.YearSettings_Id=@YearSettingId
	--group by LA.NumberOfDays
	)
	end
---/////////////////////////////////////////////
if(@isAccumulated=1 and @intLeaveTypeId=@LeaveTypeId)
begin
select isnull((isnull(@fltMaxDays,0.0)*@TotalMonth)-(@AppliedDays),0) as MaxDays_Month
end
else
select (isnull(@fltMaxDays,0.0)) as MaxDays_Month
END    ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxDayMonth]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxDayMonth]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_SelectMaxDayMonth 72,9,''06/Aug/2013'',1,0
/*
Modified By			:	Manjula.P
Modified Date		:	01-Aug-2013
Descriptions		:	Adding SL Concepts with max applicable days 
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectMaxDayMonth]    
 -- Add the parameters for the stored procedure here    
@EmpID INT ,
@intLeaveTypeId INT,
@FromDate datetime ,
@isAccumulated bit,
@LeaveApplicationId int=0
AS    
BEGIN    
 -- SET NOCOUNT ON added to prevent extra result sets from    
 -- interfering with SELECT statements.    
 SET NOCOUNT ON; 
 declare @LeaveTypeId int=0;
 declare @SLLeaveTypeId int=0;
 set @LeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType=''CL'');
 --adding for SL by MAnjula.P on 08-Aug-2013
 set @SLLeaveTypeId=(select LeaveType_Id from TA_Tbl_LeaveType where LeaveType=''SL'');
 declare @Todate as datetime;
 declare @YearSettingId as int
 set @YearSettingId = (select YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate)   
 set @Todate=(SELECT isnull(max(Leave_ToDate),@FromDate) FROM TA_Tbl_LeaveApplication WHERE Employee_Id = @EmpID AND Status<>''Rejected'' 
 and IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>''LOP'' and YearSettings_Id=@YearSettingId)
if(@Todate>= @FromDate)
set @Todate=@Todate
else
set @Todate=@FromDate
    -- Insert statements for procedure here    
declare @fltMaxDays as decimal(18,2)
 --adding for SL by MAnjula.P on 08-Aug-2013
declare @SLfltMaxDays as decimal(18,2)=0;
set @fltMaxDays =(SELECT top 1 isnull(cast(LPD.MaxDays_applicable as float)/12,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
--Following code commented by Prabakaran.P on 15-Feb-08, changes based on Year closure modification
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id  
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id  
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
 --adding for SL by MAnjula.P on 08-Aug-2013
set @SLfltMaxDays =(SELECT top 1 isnull(LPD.MaxDays_applicable,0) as MaxDays_Month
FROM TA_Tbl_Emp_LeavePolicy ELP  
inner join  TA_Tbl_Employee E on E.Employee_Id=ELP.EmployeeId and E.Isdeleted=0
inner join Ta_tbl_LeavePolicy LP on ELP.LeavePolicy_Id =LP.Policy_Id
inner join Ta_tbl_LeavePolicyDetails LPD on LP.Policy_Id = LPD.Policy_Id
inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id      
WHERE ELP.EmployeeId=@EmpID AND LPD.LeaveType_Id = @intLeaveTypeId 
and ISNULL( DATEDIFF(MONTH, E.DateOfJoining,@FromDate),0)>=2
AND YS.YearSettings_Id=@YearSettingId order by ELP.ToDate desc)
--for getting accumulated months availabel leaves By Manjula.P on 27-May-2013
declare @TotalMonth as int
set @TotalMonth=(
select ISNULL( DATEDIFF(MONTH,YS.FromDate,@Todate),0) as month from TA_Tbl_YearSetting YS
where YS.YearSettings_Id=@YearSettingId )
set @TotalMonth= @TotalMonth+1
--getting applied leave days count
declare @AppliedDays as decimal(18,2)=0;
IF (EXISTS(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
where 
Leave_ToDate between YS.FromDate and @Todate
and 
Employee_Id=@EmpID 
and 
LA.Status<>''Rejected'' and LA.IsDeleted=0  and LeaveType_id =@LeaveTypeId and type<>''LOP'' and type<>''Comp Off'' and LeaveApplication_Id<>@LeaveApplicationId
and YS.YearSettings_Id=@YearSettingId
) and @intLeaveTypeId = @LeaveTypeId)
	begin
	set @AppliedDays=(select isnull(SUM(LA.NumberOfDays),0) from TA_Tbl_LeaveApplication LA
	inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id=LA.YearSettings_Id
	where 
	Leave_ToDate between YS.FromDate and @Todate 
	and 
	Employee_Id=@EmpID 
	and 
	LA.Status<>''Rejected'' and LA.IsDeleted=0 and LeaveType_id=@LeaveTypeId and type<>''LOP'' and type<>''Comp Off'' and LeaveApplication_Id<>@LeaveApplicationId
	and YS.YearSettings_Id=@YearSettingId
	--group by LA.NumberOfDays
	)
	end
---/////////////////////////////////////////////
if(@isAccumulated=1 and @intLeaveTypeId=@LeaveTypeId)
	begin
	select isnull((isnull(@fltMaxDays,0.0)*@TotalMonth)-(@AppliedDays),0) as MaxDays_Month
	end
	 --adding for SL by MAnjula.P on 08-Aug-2013
else if(@intLeaveTypeId=@SLLeaveTypeId)
	BEGIN
	 select ISNULL( @SLfltMaxDays-@AppliedDays,0) as MaxDays_Month
	END
	--*******************************************
	else
	select (isnull(@fltMaxDays,0.0)) as MaxDays_Month
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMatchingDevice]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMatchingDevice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  <Author,,Name>  
-- Create date: <Create Date,,>  
-- Description: <Description,,>  
-- [Proc_TA_SelectMatchingDevice]''28'', ''In''  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_SelectMatchingDevice]  
 @ReaderID as varchar(25),  
 @Para as varchar(25)  
AS  
BEGIN  
 declare @DeviceID as int  
 set @DeviceID = (Select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=@ReaderID)  
 if @Para=''In''  
 Begin  
  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type=''Out''  
  Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type=''In''  
 End  
 if @Para=''Out''  
 Begin  
  --Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Reader_Id=@ReaderID and Type=''In''  
  Select Top 1 Reader_Id from TA_Tbl_Entrance_INOUTDetails where  Entrance_Id= (select top 1 Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_ID= @DeviceID) and Type=''Out''  
 End  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated] ''09/01/2008'',''09/30/2008'',''151''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyIDUpdated] 
@FromDate datetime,
@ToDate datetime,
@EmployeeID as int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--SELECT MAX(Emp_LeavePolicyId) AS MaxID FROM TA_Tbl_Emp_LeavePolicy
	 select Emp_LeavePolicyId as MaxID from TA_Tbl_Emp_LeavePolicy where fromdate=@fromDate and todate=@todate and EmployeeId=@employeeid
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMAXEmpLeavepolicyID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMAXEmpLeavepolicyID] 
AS
BEGIN
	SET NOCOUNT ON;
	SELECT MAX(Emp_LeavePolicyId) AS MaxID FROM TA_Tbl_Emp_LeavePolicy
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMinLevel]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMinLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectMinLevel 1,0
CREATE PROCEDURE [dbo].[Proc_TA_SelectMinLevel]
(
 @orgLevelId int,
 @ParentLevelId int
)
AS
BEGIN
	Create Table #TempLevel(LevelId int)
	Declare @ParentID varchar(20)
	declare @orgID_ToAdd int 
	declare @orgID_ParentSelected int
	declare @TopOrgId int
	Select @ParentID=parentLevelID from TA_Tbl_Level where levelID=@orgLevelId and isDeleted=0
	while @ParentID<>0
		begin
			Insert into #TempLevel values(@ParentID)
			Select @ParentID=parentLevelID from TA_Tbl_Level where levelID=@ParentID and isDeleted=0
		end
	set @orgID_ToAdd = (select top 1 LevelId from #TempLevel where LevelId<@orgLevelId)
	set @orgID_ParentSelected = (select levelId from Ta_Tbl_levelDetails where id=@ParentLevelId)
	--select min(levelID) as MinLevel from ta_tbl_level  where isdeleted=0
	if(@orgID_ToAdd = @orgID_ParentSelected)
		BEGIN
			select 1 as Result
		END
	else
		BEGIN			
			set @TopOrgId = (select parentLevelId from TA_Tbl_Level where levelId=@orgLevelId)
			if(@TopOrgId = 0)
				BEGIN
					select 1  as Result
				END
			else
				BEGIN
					select 0  as Result
				END
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_selectOrgDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_selectOrgDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_selectOrgDetails]
(
	@id int
)
AS
BEGIN
	select * from ta_tbl_levelDetails where id=@id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/****************************************************************************************/            
-- Name    : Proc_TA_SelectPolicyAllocatedEmployeeDetails
-- Desc    : To select the enties from TA_Tbl_TempGroupPolicyAllocation            
-- Company : Angler Technologies            
-- Author  : R.Manikandan
-- Date    : 25-Feb-2012
-- Update History :   [Date Updated By (Initials) Reason]            
/****************************************************************************************/
CREATE PROCEDURE [dbo].[Proc_TA_SelectPolicyAllocatedEmployeeDetails]
@EmployeeId int       
AS      
BEGIN       
	SET NOCOUNT ON;      
	if Exists(select LeavePolicy_Id from TA_Tbl_Emp_LeavePolicy where employeeid=@EmployeeId)
		begin
			select ''Exists''
		end
	else
		begin
			select ''NotExists''
		end 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan 787,''03/25/2019''
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetailsWithShiftStartAndInTime_EastMan]
(
	@Employee_Code_Id nvarchar(50) = null, 
	@PermissionStartDate datetime = ''01/01/1900'' 
)
as  
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	Declare @sql varchar(max)
	Declare @startDate datetime
	Declare @EndDate datetime
	Declare @intime varchar(20)
	Declare @lateInHours varchar(20)
	Declare @ShiftStartTime varchar(20)
	Declare @Shift_SecondHalf_StartTime datetime
	Declare @Shift_Id int
	Declare @Difference varchar(10)
	select	@startDate=DATEADD(month,DATEDIFF(MONTH,0,@PermissionStartDate),0),
			@EndDate=DATEADD(d, -1, DATEADD(month, DATEDIFF(month, 0, @PermissionStartDate)+1, 0))
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	--if the employee is absent on first session, need to take the second timing as shift in time
	IF EXISTS(SELECT Shift_Id from TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
	and Date=@PermissionStartDate and (FNAttendanceCode!=''Present''))
	BEGIN
		SELECT @Shift_Id=Shift_Id
		FROM TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
		and Date=@PermissionStartDate and (FNAttendanceCode!=''Present'')
		select @Shift_SecondHalf_StartTime= cast(Shift_SecondHalf_StartTime as datetime) from TA_Tbl_Shift where Shift_Id =@Shift_Id and Isdeleted=0
	END
	SELECT	@intime=CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114),1,5)
							ELSE SUBSTRING(convert(varchar(20),InTime),1,5)
					END,
			@ShiftStartTime=CASE	WHEN FNAttendanceCode=''Present'' THEN
											CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Shift_StartTime,0)), 114),1,5)
													ELSE SUBSTRING(convert(varchar(20),Shift_StartTime),1,5)
											END			
									ELSE convert(varchar(20),@Shift_SecondHalf_StartTime)
							END,
			@lateInHours=LateIn
	FROM TA_Tbl_ProcessedData where ProcessFlag=1 and Employee_Code_Id=@Employee_Code_Id
	and Date=@PermissionStartDate and (FNAttendanceCode=''Present'' or ANAttendanceCode=''Present'')
	select @intime=@PermissionStartDate+@intime,@ShiftStartTime=@PermissionStartDate+@ShiftStartTime
	select @Difference=DATEDIFF(minute,CONVERT(datetime,@ShiftStartTime),CONVERT(datetime,@intime))
	+DATEDIFF(HOUR,CONVERT(datetime,@ShiftStartTime),CONVERT(datetime,@intime))*60
	if(@Difference<0)
	begin
		set @Difference=0
	end
	select P.Permission_Id,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, p.Permission_AppliedDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, p.Permission_AppliedDate, @dateFormat) 
	end  AS Permission_AppliedDate,
	case	when cast(@dateFormat as varchar(100))=106 then	REPLACE(CONVERT(VARCHAR, p.Permission_Date,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, p.Permission_Date, @dateFormat) 
	end  AS Permission_Date,
	CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Permission_FromTime,0)), 114),1,5)
						ELSE SUBSTRING(convert(varchar(20),Permission_FromTime),13,5)+'' '' + SUBSTRING(convert(varchar(20),Permission_FromTime),18,2) 					
				END Permission_FromTime,
	CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN SUBSTRING(CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,Permission_ToTime,0)), 114),1,5)
						ELSE SUBSTRING(convert(varchar(20),Permission_ToTime),13,5)+'' '' + SUBSTRING(convert(varchar(20),Permission_ToTime),18,2) 					
				END Permission_ToTime,
	p.No_Of_Hours ,	
	p.Permission_Reason,
	p.Permission_Status,
	Isavailable=case when CONVERT(datetime,@PermissionStartDate)=CONVERT(datetime,Permission_Date) then 1 else 0 end,
	pd.InTime
	from TA_Tbl_ProcessedData pd 
	inner join Ta_tbl_employee e on e.SwipeCardNo=pd.Employee_Code_Id
	inner join TA_Tbl_Permission p on (p.Employee_Id=e.Employee_Id and p.Permission_Date=pd.Date)
	inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id
	where ys.IsActive=1 and p.IsDeleted=''0''  and e.isdeleted=''0''
	and e.Employee_Code_Id = cast(@Employee_Code_Id as nvarchar(50))
	and (p.Permission_FromTime between convert(datetime,cast(@startDate as nvarchar(11)) + '' 00:00:00.000'', 102) and convert(datetime,cast(@EndDate as nvarchar(11)) + '' 23:59:59.999'',102)
	or p.Permission_ToTime between convert(datetime, cast(@startDate as nvarchar(11)) + '' 00:00:00.000'', 102) and convert(datetime,cast(@EndDate as nvarchar(11)) + '' 23:59:59.999'',102))
	Order By Permission_Id Desc
	Declare @Isavailable int
	select @Isavailable=case when CONVERT(datetime,@PermissionStartDate)=CONVERT(datetime,Permission_Date) then 1 else 0 end
	from TA_Tbl_Permission p  
	inner join Ta_tbl_employee e on e.Employee_Id=p.Employee_Id  
	inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id
	where ys.IsActive=1 and p.IsDeleted=''0''  and e.isdeleted=''0''
	and e.Employee_Code_Id = cast(@Employee_Code_Id as nvarchar(50))
	and (p.Permission_FromTime between convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'', 102) and convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + '' 23:59:59.999'',102)
	or p.Permission_ToTime between convert(datetime, cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'', 102) and convert(datetime,cast(@PermissionStartDate as nvarchar(11)) + '' 23:59:59.999'',102))
	Order By Permission_Id Desc
	select @Difference=isnull(@Difference,''''),@Isavailable=isnull(@Isavailable,0)
	select
	ShiftStartTime=
	CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,@ShiftStartTime,0)), 114)
						ELSE SUBSTRING(@ShiftStartTime,13,5)+'' '' + SUBSTRING(@ShiftStartTime,18,2) 					
				END,
				CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,@intime,0)), 114)
						ELSE SUBSTRING(@intime,13,5)+'' '' + SUBSTRING(@intime,18,2) 					
				END intime,
	Differences=@lateInHours,
	Isavailable=@Isavailable
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectReceiversForSMS]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectReceiversForSMS]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Manikandan.R>
-- Create date: <05-09-2016 14:46>
-- Description:	<Getting the existing Receivers Details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectReceiversForSMS]
@TemplateID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
    -- Insert statements for procedure here
	select sr.Usergroupid,ug.groupName,1 Status from TA_Tbl_Usergroup ug
	inner join Ta_Tbl_SMSReceivers SR on ug.groupId=sr.Usergroupid 
	where sr.TemplateId=@TemplateID and ug.isDeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPunchTypes]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- [dbo].[Proc_TA_SelectPunchTypes] ''A'',0,''Superadmin''
CREATE PROCEDURE [dbo].[Proc_TA_SelectPunchTypes] 
(
	@Type CHAR,
	@PunchType_Id INT,
	@UserGroupName nVarchar(50)
)
AS
BEGIN
	SET NOCOUNT ON
	Create table #TA_Tbl_PunchTypes(PunchType_Id int,Terminal_Id int,Terminal_ReaderID nvarchar(20),
	PunchType nvarchar(50),[Value] nvarchar(50),IsDeleted nvarchar(10),flag int)
	update TA_Tbl_PunchTypes set flag=1 from TA_Tbl_PunchTypes P inner join TA_Tbl_ManualTimeEntry M 
	on
	(
		(P.Terminal_Id = M.ManualTimeEntry_InReaderID AND P.PunchType = M.ManualTimeEntry_InPunchType) OR 
		(P.Terminal_Id = M.ManualTimeEntry_OutReaderID AND P.PunchType = M.ManualTimeEntry_OutPunchType)
	)
	where isnull(flag,0)!=1
	update TA_Tbl_PunchTypes set flag=1 FROM TA_Tbl_PunchTypes P 
	inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id 
	inner join TA_Tbl_ClockDetails c 
	on
	(
		(T.Terminal_ReaderID= c.Clk_InDeviceId AND P.PunchType=c.Clk_InPunchType) OR 
		(T.Terminal_ReaderID = c.Clk_OutDeviceId AND P.PunchType =c.Clk_OutPunchType)
	)
	where isnull(flag,0)!=1
	-- Select all Punch Type Details
	IF (@Type=''A'')
		BEGIN
			IF(@UserGroupName = ''SuperAdmin'')
				BEGIN
					--checking here
					insert into #TA_Tbl_PunchTypes				
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE CONVERT(varchar(20),T.Terminal_ReaderID) not in(''787'',''788'')
				END
			ELSE
				BEGIN
				--here also
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE P.Isdeleted = 0 and CONVERT(varchar(20),T.Terminal_ReaderID) not in(''787'',''788'')
				END
		END
	-- Select Punch Type Details based on the Punch Type Id
	IF (@Type=''I'')
		BEGIN
			IF(@UserGroupName = ''SuperAdmin'')         
				BEGIN
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE  P.PunchType_Id = @PunchType_Id and CONVERT(varchar(20),T.Terminal_ReaderID) not in(''787'',''788'')
				END
			ELSE        
				BEGIN
					insert into #TA_Tbl_PunchTypes
					SELECT P.PunchType_Id,P.Terminal_Id,CONVERT(varchar(20),T.Terminal_ReaderID),P.PunchType,P.[Value],
					case when P.IsDeleted=1 then ''True'' else ''False'' end IsDeleted,isnull(flag,0)
					FROM TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id = T.Terminal_Id
					WHERE  P.PunchType_Id = @PunchType_Id AND P.Isdeleted = 0 and CONVERT(varchar(20),T.Terminal_ReaderID) not in(''787'',''788'')
				END
		END
		select * from #TA_Tbl_PunchTypes
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectRestrictedHolidayDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectRestrictedHolidayDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectRestrictedHolidayDetails
Description		:	Get Restricted Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeaveApplication,TA_Tbl_Holiday
Created By		:	Prabakaran
Created On		:	13-Aug-07
Modified By		:
Modified On		:
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectRestrictedHolidayDetails](@Employee_Id int)
AS
select la.LeaveApplication_Id,CONVERT(VARCHAR, la.Leave_ApplicationDate, 101) AS Leave_ApplicationDate,CONVERT(VARCHAR, la.Leave_FromDate,101) + '' - '' + CONVERT(VARCHAR, la.Leave_ToDate, 101) AS Duration,h.Holiday_Description,la.Status,la.Reason  from TA_Tbl_Holiday h
inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id
inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id
where ys.IsActive=1 and la.type=''Restricted Holiday'' and la.Employee_Id=@Employee_Id and la.Isdeleted=0' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftNotAllocated]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftNotAllocated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_SelectShiftNotAllocated ''day1shift'',60013,2010,1    
CREATE  PROCEDURE [dbo].[Proc_TA_SelectShiftNotAllocated]    
(    
@ColName varchar(20),    
@EmpId int,    
@Year int,    
@Month int    
)    
AS    
BEGIN    
declare @ShiftCount as int    
SET @ShiftCount =(select  count(EmployeeId) as shiftCount  from TA_Tbl_PermanentShiftAllocation where ( @ColName  <> ''0''  or  @ColName is null) and EmployeeId=@Empid and [Month]=@Month and [Year]=@Year )    
if(@ShiftCount<=0)    
BEGIN    
SET @ShiftCount =(select  count(EmployeeId) as shiftCount  from TA_Tbl_TemporaryShiftAllocation where ( @ColName  <> ''0''  or  @ColName is null) and EmployeeId=@Empid and [Month]=@Month and [Year]=@Year )    
END    
select @ShiftCount    
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_OrgEdit]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_OrgEdit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_OrgEdit]
(
	@lid int
)
AS
BEGIN
	DECLARE @lelid int, @lelName varchar(50)
	declare @pid as int
	SELECT @lelName = name, @pid=ParentID FROM ta_tbl_levelDetails WHERE id = @lid
	INSERT INTO TA_Tbl_ParentIDs ( LevelID,LevelName,pid ) VALUES (@lid,@lelName,@pid)
	SELECT @lelid=parentID FROM ta_tbl_levelDetails WHERE id = @lid
	if (@lelid >0)
	BEGIN
		EXEC dbo.Proc_TA_OrgEdit @lelid
	END		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofYearlyHolidays]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_NumberofYearlyHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_NumberofYearlyHolidays]
AS
BEGIN
	select count(*) as Y from TA_Tbl_Holiday where Holiday_Type=''Y'' and Isdeleted=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_NumberofGolbalHolidays]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_NumberofGolbalHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_NumberofGolbalHolidays]
AS
BEGIN
	select count(*) as G from TA_Tbl_Holiday where Holiday_Type=''G'' and Isdeleted=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ListofProjects]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ListofProjects]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <04-Jan-2020>
-- Description:	<Prjoect List page fields getting using this procedure>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ListofProjects]
@UserId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @UsergroupId bigint
	declare @UsergroupName varchar(25)
	select @UsergroupId = isnull(UserGroup_Id,0) from TA_Tbl_Employee where Employee_Id = @UserId
	select @UsergroupName = isnull(groupName,'''') from TA_Tbl_Usergroup where groupId= @UsergroupId

	select isnull(Project_Id,0) as Project_Id,
	isnull(Project_Code,'''') as Project_Code,
	isnull(Project_Name,'''') as Project_Name,
	Project_StartTime,
	Project_EndTime,
	isnull(Project_Status,'''') as Project_Status,
	(case when (@UsergroupName = ''SuperAdmin'' and Project_Status = ''Completed'') then 1 else 0 end) as IsDeleteAllowed,
	case when LevelID is not null and LevelID<>0 then (Select name from Ta_Tbl_levelDetails l where l.id=TA_Tbl_Project.LevelID) else '''' end as LevelName,
	Mandays,ManHours
	From TA_Tbl_Project
	where (IsDeleted = 0)

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Levels_Modify]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Levels_Modify]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Levels_Modify]
	(
	@levelId int,
	@levelName varchar(100),
	--@parentLevelId int,
	@description varchar(255),
	@city varchar(100),
	@state varchar(100),
	@country varchar(100),
	@zip varchar(50),
	@phone1 varchar(50),
	@phone2 varchar(50),
	@fax varchar(50),
	@mobile varchar(50),
	@email varchar(100),
	@web varchar(100)
)
AS
Begin
	update ta_tbl_level set levelname=@levelName where levelid=@levelID;
	declare @levId int;
	set @levId = (select levelid from ta_tbl_levelDetails where levelid=@levelId );
	if (@levId is null or @levID='''')
		Begin
			insert into Ta_tbl_levelDetails (levelid,description,city,state,country,zip,phone1,phone2,fax1,fax2,email,webaddress) values (@levelId,@description,@city,@state,@country,@zip,@phone1,@phone2,@fax,@mobile,@email,@web);
		End
	else
		Begin
			update Ta_tbl_levelDetails set description=@description,city=@city,state=@state,country=@country,zip=@zip,phone1=@phone1,phone2=@phone2,fax1=@fax,fax2=@mobile,email=@email,webaddress=@web where levelId=@levelid
		End	
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadingPunchTypes]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadingPunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_LoadingPunchTypes ''2 OutTermi'',''In''
-- select * from ta_tbl_punchtypes
-- =============================================
-- Author:		<Angeswaran.S>
-- Create date: <14-Mar-2012>
-- Description:	<Loading the PunchType based on the terminal>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_LoadingPunchTypes] 
	@TerminalReaderId varchar(20),
	@TerminalType varchar(10)
AS
BEGIN	
		SET NOCOUNT ON;
		Declare @TerminalId int
		set @TerminalId =(select terminal_Id from ta_tbl_terminal where Terminal_ReaderId=''''+ @TerminalReaderId+'''')
		if(@TerminalType=''Out'')
			begin
				if(@TerminalReaderId=''18000000'')
					begin
						select distinct P.PunchType_Id,T.Terminal_Name+ ''-'' + PunchType as PunchType from ta_tbl_punchtypes P
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in 
						(''Out'',''Shift Out'',''Break Out'',''Lunch Out'',''Official Out'',''In Duty'') 
						AND P.Isdeleted = 0
					end
				else
					begin
						select PunchType_Id,T.Terminal_Name+ ''-'' + P.PunchType as PunchType from ta_tbl_punchtypes  P inner join 
						(select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Type=''Out'' and	entrance_id in 
						(select Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@TerminalId)) as A on P.Terminal_Id=A.Reader_Id 
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in  
						(''Out'',''Shift Out'',''Break Out'',''Lunch Out'',''Official Out'',''In Duty'') AND P.Isdeleted = 0
					end
			end
		else if(@TerminalType=''In'')
			begin
				if(@TerminalReaderId=''18000000'')
					begin
						select distinct P.PunchType_Id,T.Terminal_Name+ ''-'' + PunchType as PunchType from ta_tbl_punchtypes P
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in 
						(''In'',''Shift In'',''Break In'',''Lunch In'',''Official In'',''Out Duty'') AND P.Isdeleted = 0
					end
				else
					begin
						select PunchType_Id,T.Terminal_Name+ ''-'' + P.PunchType as PunchType from ta_tbl_punchtypes  P inner join 
						(select Reader_Id from TA_Tbl_Entrance_INOUTDetails where Type=''In'' and	entrance_id in 
						(select Entrance_Id from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@TerminalId)) as A on P.Terminal_Id=A.Reader_Id 
						inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id
						where P.PunchType in  
						(''In'',''Shift In'',''Break In'',''Lunch In'',''Official In'',''Out Duty'') AND P.Isdeleted = 0
					end
			end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailTemplate]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailTemplate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailTemplate]
(
	@ScheduleId int,
	@Subject varchar(300),
	@EmailContent varchar(max),
	@Type varchar(2)
)
AS
BEGIN
	SET NOCOUNT ON;
    IF(@Type  = ''I'')
		BEGIN
			INSERT INTO TA_Tbl_EmailTemplate (ScheduleId,Subject,EmailContent) VALUES (@ScheduleId,@Subject,@EmailContent)
		END
	ELSE
		BEGIN
		    UPDATE TA_Tbl_EmailTemplate SET subject= @Subject, EmailContent = @EmailContent WHERE ScheduleId = @ScheduleId
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateEmailScheduleFilters]
(
	@ScheduleId int,
	@Filters varchar(max),
	@ReportType varchar(25),
	@Type varchar(2),
	@CompanyId int
)
AS
BEGIN
	SET NOCOUNT ON;
    if(@Type  = ''I'')
		BEGIN
			insert into TA_Tbl_EmailScheduleFilters (ScheduleId,Filters,ReportType,CompanyId) values (@ScheduleId,@Filters,@ReportType,@CompanyId)
		END
	else
		BEGIN
			update TA_Tbl_EmailScheduleFilters set Filters=@Filters, ReportType=@ReportType,
			CompanyId= @CompanyId where ScheduleId=@ScheduleId
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTerminalDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE 	[dbo].[Proc_TA_InsertTerminalDetails]
(
	@type CHAR(1),
	@TerminalId INT=0,
	@TerminalReaderId NVARCHAR(10)='''',
	@TerminalName NVARCHAR(50)='''',
	@TerminalDescription NVARCHAR(255)='''',
	@RawDataFormat int=0,
	@Emp_Id int
)
AS
BEGIN
	Declare @EntranceIdentity int
	Declare @TerminalAutoId int
	Declare @RawDataId int
	Declare @LevelId int
	IF (@type=''I'')
	BEGIN
		DECLARE @sql nvarchar(2000)
		SET @sql=''INSERT INTO TA_Tbl_Terminal (Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,IsDeleted) 
		VALUES ('''''' + cast(@TerminalReaderId as nvarchar(20)) +'''''',N'''''' + @TerminalName + '''''',N'''''' + @TerminalDescription + '''''','' + cast(@RawDataFormat as nvarchar(20)) + '',''''''+cast(@Emp_Id as nvarchar(10))+'''''',0)''
		EXEC(@sql)			
		--Dummy values for manual time entry			
		set @RawDataId=(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where IsDeleted=0)
		set @LevelId=(select top 1 id from Ta_Tbl_levelDetails where IsDeleted=0 and parentId=0)
		if not exists(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
			begin			
				insert into TA_Tbl_Terminal values(''787'',''787'',''787'',@RawDataId,GETDATE(),1,0)
				select @TerminalAutoId=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0
				insert into TA_Tbl_Entrance values(''TimecheckPhase'',''TimecheckPhase'',@LevelId,1,1,0,GETDATE(),1,0)			
				select @EntranceIdentity=Entrance_Id from TA_Tbl_Entrance where Entrance_Name=''TimecheckPhase'' and IsDeleted=0
				insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,''In'')	
				insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,''Out'')
			end
		--Commented by Manikandan.RR on 06Feb2020 07:59 PM due to some issue related to freescan logic
		--if not exists(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
		--	BEGIN
		--		INSERT INTO TA_Tbl_Terminal values(''788'',''788'',''788'',@RawDataId,GETDATE(),1,0)			
		--		select @TerminalAutoId=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0
		--		select @EntranceIdentity=Entrance_Id from TA_Tbl_Entrance where Entrance_Name=''TimecheckPhase'' and IsDeleted=0
		--		insert into TA_Tbl_Entrance_INOUTDetails values(@EntranceIdentity,@TerminalAutoId,''Out'')
		--	END
		declare @IsFreeScan int
		set @IsFreeScan=(select IsFreeScan from TA_tbl_TerminalDatatype where TerminalDatatype_ID=@RawDataFormat)
		if(@IsFreeScan=1)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID=''787'' and P.IsDeleted=0 and P.PunchType=''In'')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)						
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,''Shift In'',0,0,1,GETDATE(),''A'')
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,''Shift Out'',1,0,1,GETDATE(),''A'')
					end
				--if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID=''788'' and P.IsDeleted=0 and P.PunchType=''Out'')
				--	begin
				--		set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
				--		INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,''Shift Out'',1,0,1,GETDATE(),''A'')
				--	end
			end
	END
	-- update
	ELSE IF (@type=''U'')
	BEGIN
		set @sql=''UPDATE TA_Tbl_Terminal 
		SET Terminal_Name=N'''''' + @TerminalName + '''''' ,Terminal_ReaderID='''''' + cast(@TerminalReaderId as nvarchar(20)) + '''''',Terminal_Description=N'''''' + @TerminalDescription + '''''',TerminalDatatype_ID='' + cast(@RawDataFormat as nvarchar(20)) + '',Emp_ID = ''''''+cast(@Emp_Id as nvarchar(10))+''''''
		WHERE Terminal_Id='' + cast(@TerminalId as nvarchar(20)) + ''''
		EXEC(@sql) 
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTerminalDatatype]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTerminalDatatype]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/********************************************************************
    Purpose  - Inserting and Updating Terminal DataTypes
    Author     - Kumuthini.L 
   Proc_TA_InsertTerminalDatatype	''U'',40,''RDBMS-001'',''RDBMS'','''','''','''',0,'''','''','''','''',2,'''','''','''','''','''',0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,''Provider=SQLOLEDB.1;Data Source=Angler39\sqlexpress;Initial Catalog=BioAdminDataSQL1;User Id=epic;pwd=epic;'',''tb_reportslist'','''','''',2,'''','''','''','''','''',''ndeviceid'',''nuserid'',1,'''','''',''dtDateTime'',''nTNAEvent'',''nEvent'',''susername'',0,''mm/dd/yyyy hh:mm:ss ttsdf'','''','''',0,1,55,1,''10/13/2008 15:53:05 PM''
**********************************************************************/
CREATE PROCEDURE 	[dbo].[Proc_TA_InsertTerminalDatatype]
(
	@type CHAR(1),
	@TerminalDatatypeId INT=0,
	@RawDataFormat NVARCHAR(25),
	@FileType NVARCHAR(15), 
	@FileSourcePath NVARCHAR(2000), 
	@FileBackupPath NVARCHAR(2000), 
	@FileBackupType NVARCHAR(10), 
	@NoOfFields INT, 
	@Delimiter CHAR(5),  
	@StringEnclosedBy CHAR(5),  
	@Del_ReaderNo NVARCHAR(10),  
	@Del_CardNo NVARCHAR(10),  
	@Del_DateTimeBit int,  
	@Del_Date NVARCHAR(10),  
	@Del_Time NVARCHAR(10),  
	@Del_DateTime NVARCHAR(10),  
	@Del_Type NVARCHAR(10),  
	@Del_TransIdentifier NVARCHAR(10),
	@FL_ReaderNoFrom INT,  
	@FL_ReaderNoTo INT,   
	@FL_CardNoFrom INT,  
	@FL_CardNoTo INT,  
	@FL_DateTimeBit INT,  
	@FL_DateFrom INT,  
	@FL_DateTo INT,  
	@FL_TimeFrom INT,  
	@FL_TimeTo INT,  
	@FL_DateTimeFrom INT,  
	@FL_DateTimeTo INT,  
	@FL_TypeFrom INT,  
	@FL_TypeTo INT,  
	@FL_TransIdentifierFrom INT,  
	@FL_TransIdentifierTo INT,  
	@ConnectionString  NVARCHAR(2000),  
	@TableName NVARCHAR(50),  
	@MDB_ReaderNo NVARCHAR(25),  
	@MDB_CardNo NVARCHAR(25),  
	@MDB_DateTimeBit INT,  
	@MDB_Date NVARCHAR(25),   
	@MDB_Time NVARCHAR(25),  
	@MDB_DateTime NVARCHAR(25),  
	@MDB_Type NVARCHAR(25), 
	@MDB_TransIdentifier NVARCHAR(25), 
	@RDBMS_ReaderNo NVARCHAR(25),  
	@RDBMS_CardNo NVARCHAR(25),  
	@RDBMS_DateTimeBit INT,
	@RDBMS_Date NVARCHAR(25), 
	@RDBMS_Time NVARCHAR(25),
	@RDBMS_DateTime NVARCHAR(25), 
	@RDBMS_Type NVARCHAR(25), 
	@RDBMS_TransIdentifier NVARCHAR(25), 
	@RDBMS_MDB_Flag NVARCHAR(25),
	@IsEmployeeIdBit INT,
	@DateTimeFormat NVARCHAR(40),
	@DateFormat NVARCHAR(15),
	@TimeFormat NVARCHAR(15),
	@IsEncryptedBit INT,
	@TransactionIdentifierBit INT,
	@TransactionIdentifierValue NVARCHAR(50),
	@Empid  INT,
	@BrandType varchar(500),
	@IsFreeScan varchar(500)
)
AS
BEGIN
	declare @EntryDate as datetime
	set @EntryDate=getdate()
	DECLARE @sql AS NVARCHAR(2000)
	IF (@type=''I'')
	BEGIN
	  declare @BrandId as int
	  set @BrandId=(select BrandID from TA_Tbl_TerminalBrand where KeyValue=@BrandType)  	  
	  SET @sql=''INSERT INTO TA_tbl_TerminalDatatype (Raw_Data_Format,FileType,File_SourcePath,File_BackupPath,File_BackupType,Delimiter_NoOfFields,Delimiter_Delimiter,Delimiter_StringEnclosedBy,Delimiter_ReaderNo,''
	  SET @sql=@sql + ''Delimiter_CardNo,Delimiter_DateTimeBit,Delimiter_Date,Delimiter_Time,Delimiter_DateTime,Delimiter_Type,Delimiter_TransactionIdentifier,FixedLength_ReaderNoFrom,FixedLength_ReaderNoTo,FixedLength_CardNoFrom,''
	  SET @sql=@sql + '' FixedLength_CardNoTo,FixedLength_DateTimeBit,FixedLength_DateFrom,FixedLength_DateTo,FixedLength_TimeFrom,FixedLength_TimeTo,FixedLength_DateTimeFrom,FixedLength_DateTimeTo,FixedLength_TypeFrom,''
	  SET @sql=@sql + '' FixedLength_TypeTo,FixedLength_TransactionIdentifierFrom,FixedLength_TransactionIdentifierTo,ConnectionString,TableName,MDB_ReaderNo,MDB_CardNo,MDB_DateTimeBit,MDB_Date,MDB_Time,MDB_DateTime,''
	  SET @sql=@sql + '' MDB_Type,MDB_TransactionIdentifier,RDBMS_ReaderNo,RDBMS_CardNo,RDBMS_DateTimeBit,RDBMS_Date,RDBMS_Time,RDBMS_DateTime,RDBMS_Type,RDBMS_TransactionIdentifier,RDBMS_MDB_Flag,IsEmployeeId,DateTimeFormat,DateFormat,TimeFormat,IsEncrypted,''
	  SET @sql=@sql + '' TransactionIdentifierBit,TransactionIdentifierValue,Emp_Id,[TimeStamp],IsDeleted,BrandID,IsFreeScan) VALUES( '' 
	  SET @sql=@sql + '' N'''''' + @RawDataFormat + '''''',N'''''' + @FileType + '''''',N'''''' + @FileSourcePath + '''''',N'''''' + @FileBackupPath + '''''',''''''  
	  SET @sql=@sql + @FileBackupType + '''''','' + cast(@NoOfFields as nvarchar(20)) + '','''''' + @Delimiter + '''''','''''' +  @StringEnclosedBy + '''''', N'''''' + @Del_ReaderNo + '''''', N'''''' + @Del_CardNo + '''''', '' 
	  SET @sql=@sql + cast(@Del_DateTimeBit as nvarchar(20)) + '',N'''''' + @Del_Date + '''''',N'''''' + @Del_Time + '''''' ''
	  SET @sql=@sql + '',N''''''  + @Del_DateTime + '''''',N'''''' + @Del_Type + '''''','''''' + @Del_TransIdentifier +'''''' ''
	  SET @sql=@sql + '',''+ cast(@FL_ReaderNoFrom as nvarchar(20)) + '','' + cast(@FL_ReaderNoTo as nvarchar(20)) + '','' + cast(@FL_CardNoFrom as nvarchar(20)) + '','' + cast(@FL_CardNoTo as nvarchar(20)) + '','' + cast(@FL_DateTimeBit as nvarchar(20)) + '','' + cast(@FL_DateFrom as nvarchar(20)) + '','' + cast(@FL_DateTo as nvarchar(20)) + '','' + cast(@FL_TimeFrom as nvarchar(20)) + '', ''
	  SET @sql=@sql + cast(@FL_TimeTo as nvarchar(20)) + '','' + cast(@FL_DateTimeFrom as nvarchar(20)) + '','' + cast(@FL_DateTimeTo as nvarchar(20))+ '','' + cast(@FL_TypeFrom as nvarchar(20)) + '','' + cast(@FL_TypeTo as nvarchar(20)) + '','' + cast(@FL_TransIdentifierFrom as nvarchar(20)) + '','' + cast(@FL_TransIdentifierTo as nvarchar(20)) +'',N'''''' + @ConnectionString + '''''',N'''''' + @TableName + '''''',N'''''' + @MDB_ReaderNo + '''''',N'''''' + @MDB_CardNo + '''''','' + cast(@MDB_DateTimeBit as nvarchar(20)) + '',N'''''' + @MDB_Date + '''''',N'''''' +  @MDB_Time + '''''',  ''
	  SET @sql=@sql + ''N'''''' + @MDB_DateTime + '''''',N'''''' + @MDB_Type + '''''','''''' + @MDB_TransIdentifier + '''''',N'''''' + @RDBMS_ReaderNo + '''''',N'''''' + @RDBMS_CardNo + '''''','' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + '',N'''''' + @RDBMS_Date + '''''', N'''''' + @RDBMS_Time + '''''',N'''''' + @RDBMS_DateTime + '''''',N'''''' + @RDBMS_Type + '''''','''''' + @RDBMS_TransIdentifier + '''''','''''' + @RDBMS_MDB_Flag + '''''','' + cast(@IsEmployeeIdBit as nvarchar(5)) + '','''''' + @DateTimeFormat + '''''','''''' + @DateFormat + '''''','''''' + @TimeFormat + '''''','' + cast(@IsEncryptedBit as nvarchar(5)) + '','' + cast(@TransactionIdentifierBit as nvarchar(10)) + '','''''' + @TransactionIdentifierValue +'''''','' + cast(@Empid as nvarchar(20)) + '','''''' + cast(@EntryDate as nvarchar(20)) + '''''',0,'''''' + cast(@BrandId as nvarchar(20)) + '''''','''''' + cast(@IsFreeScan as nvarchar(4))+ '''''')''
	END
	ELSE IF (@type=''U'')
	BEGIN		
		SET @sql=''UPDATE TA_tbl_TerminalDatatype SET File_SourcePath=N'''''' + @FileSourcePath + '''''',File_BackupPath=N'''''' + @FileBackupPath + '''''',File_BackupType='''''' + @FileBackupType + '''''',
		Delimiter_NoOfFields='' + cast(@NoOfFields as nvarchar(20)) + '',Delimiter_Delimiter=N'''''' + @Delimiter + '''''',Delimiter_StringEnclosedBy=N'''''' +  @StringEnclosedBy + '''''',Delimiter_ReaderNo=N'''''' + @Del_ReaderNo + '''''',
		Delimiter_CardNo=N'''''' + @Del_CardNo + '''''',Delimiter_DateTimeBit='' + cast(@Del_DateTimeBit as nvarchar(20)) + '',Delimiter_Date=N'''''' + @Del_Date + '''''',Delimiter_Time=N'''''' + @Del_Time + '''''',Delimiter_DateTime=N'''''' + @Del_DateTime + '''''',
		Delimiter_Type=N'''''' + @Del_Type + '''''',Delimiter_TransactionIdentifier='''''' + @Del_TransIdentifier + '''''',FixedLength_ReaderNoFrom='' + cast(@FL_ReaderNoFrom as nvarchar(20)) + '',FixedLength_ReaderNoTo='' + cast(@FL_ReaderNoTo as nvarchar(20)) + '',
		FixedLength_CardNoFrom='' + cast(@FL_CardNoFrom as nvarchar(20)) + '',FixedLength_CardNoTo='' + cast(@FL_CardNoTo as nvarchar(20)) + '',FixedLength_DateTimeBit='' + cast(@FL_DateTimeBit as nvarchar(20)) + '',
		FixedLength_DateFrom='' + cast(@FL_DateFrom as nvarchar(20)) + '',FixedLength_DateTo='' + cast(@FL_DateTo as nvarchar(20)) + '',FixedLength_TimeFrom='' + cast(@FL_TimeFrom as nvarchar(20)) + '',
		FixedLength_TimeTo='' + cast(@FL_TimeTo as nvarchar(20)) + '',FixedLength_DateTimeFrom='' + cast(@FL_DateTimeFrom as nvarchar(20)) + '',FixedLength_DateTimeTo='' + cast(@FL_DateTimeTo as nvarchar(20))+ '',
		FixedLength_TypeFrom='' + cast(@FL_TypeFrom as nvarchar(20)) + '',FixedLength_TypeTo='' + cast(@FL_TypeTo as nvarchar(20)) +'',FixedLength_TransactionIdentifierFrom='' + cast(@FL_TransIdentifierFrom as nvarchar(20)) + '',
		FixedLength_TransactionIdentifierTo='' + cast(@FL_TransIdentifierTo as nvarchar(20)) +'',ConnectionString=N'''''' + @ConnectionString + '''''',TableName=N'''''' + @TableName + '''''',MDB_ReaderNo=N'''''' + @MDB_ReaderNo + '''''',
		MDB_CardNo=N'''''' + @MDB_CardNo + '''''',MDB_DateTimeBit='' + cast(@MDB_DateTimeBit as nvarchar(20)) + '',MDB_Date=N'''''' + @MDB_Date + '''''',MDB_Time=N'''''' +  @MDB_Time + '''''',MDB_DateTime= N'''''' + @MDB_DateTime + '''''',
		MDB_Type=N'''''' + @MDB_Type + '''''',MDB_TransactionIdentifier='''''' + @MDB_TransIdentifier + '''''',RDBMS_ReaderNo=N'''''' + @RDBMS_ReaderNo + '''''',RDBMS_CardNo=N'''''' + @RDBMS_CardNo + '''''',
		RDBMS_DateTimeBit='' + cast(@RDBMS_DateTimeBit as nvarchar(20)) + '',RDBMS_Date=N'''''' + @RDBMS_Date + '''''',RDBMS_Time=N'''''' + @RDBMS_Time + '''''',RDBMS_DateTime=N'''''' + @RDBMS_DateTime + '''''',
		RDBMS_Type=N'''''' + @RDBMS_Type + '''''',RDBMS_TransactionIdentifier='''''' + @RDBMS_TransIdentifier + '''''',RDBMS_MDB_Flag='''''' + @RDBMS_MDB_Flag + '''''',IsEmployeeId='' + cast(@IsEmployeeIdBit as nvarchar(5)) + '',DateTimeFormat='''''' + @DateTimeFormat + '''''',DateFormat='''''' + @DateFormat + '''''',TimeFormat='''''' + @TimeFormat + '''''',IsEncrypted = '' + cast(@IsEncryptedBit as nvarchar(5)) + '',
		TransactionIdentifierBit='' + cast(@TransactionIdentifierBit as nvarchar(20)) + '',TransactionIdentifierValue='''''' + @TransactionIdentifierValue + '''''',Emp_Id='' + cast(@Empid as nvarchar(20)) + '',IsFreeScan='' + cast(@IsFreeScan as nvarchar(4)) + '',
		[TimeStamp]='''''' + cast(@EntryDate as nvarchar(20)) + '''''' WHERE TerminalDatatype_ID= '' + cast(@TerminalDatatypeId as nvarchar(20)) + '' and Raw_Data_Format=N'''''' + @RawDataFormat + '''''' and FileType=N'''''' + @FileType + ''''''''
	END
	EXEC(@sql)
	if(@IsFreeScan=1)
		begin
		declare @TerminalAutoID int
		declare @EntranceIdentity int
		Declare @RawDataId int
		Declare @LevelId int
		--If "IS Free Scan" is "Yes" then the IN and OUT punch type create automatically add by karthikeyan.R
		if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID=''787'' and P.IsDeleted=0 and P.PunchType=''In'')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) 
						VALUES(@TerminalAutoID,''In'',0,0,1,GETDATE(),''A'')
					end
			end
		if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
			begin
				if not exists(select * from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id where Terminal_ReaderID=''788'' and P.IsDeleted=0 and P.PunchType=''Out'')
					begin
						set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
						INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,''Out'',1,0,1,GETDATE(),''A'')
					end
			end  
		End	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertTempWeekday]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertTempWeekday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Manjula.P
Modified On		:	27-Dec-2013
Descriptions	:	Adding ShiftId parameter in TA_Tbl_TemWeekday tables and procedures
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertTempWeekday]
(
@TempWeekdayFromDate nvarchar(20),
@TempWeekdayToDate nvarchar(20),
@ClosingTime nvarchar(15),
@Reason nvarchar(255),
@Employee_Id int,
@XMLdata xml,
@TempWeeklyoffId int,
---Added by Manjula.P on 27-Dec-2013 for adding shiftId parameter
@ShiftId nvarchar(max)
)
AS
BEGIN
	declare @sql nvarchar(500)
	SET NOCOUNT ON;
	declare @TempId int
	DECLARE @Index int
	if(@TempWeeklyoffId  <>0)
		BEGIN
			select TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason from TA_Tbl_TemWeekday 
			where TempWeekday_Id=@TempWeeklyoffId		
			select LevelId from Ta_Tbl_Temporary_WeeklyOff_Levels where TempWeekday_Id=@TempWeeklyoffId		
		END
	ELSE
		BEGIN
			INSERT INTO TA_Tbl_TemWeekday(TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason,Emp_Id,Isdeleted,ShiftId) 
			VALUES(@TempWeekdayFromDate,@TempWeekdayToDate,@ClosingTime,@Reason,@Employee_Id,0,@ShiftId)
			set @TempId= (select @@Identity)	
			set @Index = 0 
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO Ta_Tbl_Temporary_WeeklyOff_Levels
			select @TempId, xm.LevelId from OPENXML(@Index, ''/DocumentElement/Ta_Tbl_Temporary_WeeklyOff_Levels'')
			with (LevelId int ''LevelId'') as xm
			exec sp_xml_removedocument @Index
			--UPDATE TA_Tbl_ProcessedData SET ProcessFlag=0 FROM TA_Tbl_ProcessedData P 
			--INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON P.LevelId=WL.LevelId 
			--inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id
			--WHERE WL.TempWeekday_Id=@TempId and P.date between TW.TempWeekday_FromDate
			--and TempWeekday_ToDate			
			Update ta_tbl_ProcessedData set ProcessFlag=0 from ta_tbl_processeddata p inner join (
			select SwipeCardNo,TW.TempWeekday_FromDate,TW.TempWeekday_ToDate from ta_tbl_employee E
			inner join ta_tbl_employeelevel EL on E.Employee_id=EL.Employeeid
			INNER JOIN Ta_Tbl_Temporary_WeeklyOff_Levels WL ON EL.LevelId=WL.LevelId 
			inner join ta_tbl_Temweekday TW ON WL.TempWeekday_Id=TW.TempWeekday_Id
			WHERE WL.TempWeekday_Id=@TempId) as TemEmployee  On P.Employee_Code_id=TemEmployee.SwipeCardNo and P.date between TemEmployee.TempWeekday_FromDate
			and TemEmployee.TempWeekday_ToDate			
			select ''1'' 		
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertShiftAllocation]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_InsertShiftAllocation 2014,8,1,''05/02/2011 09:07:50 AM'',''05/01/2011'',
--declare @p6 xml
--set @p6=convert(xml,N''<DocumentElement><Table><EmpID>25</EmpID><EmployeeId>787</EmployeeId><EmployeeName>Manikandan Rajendran</EmployeeName><LoginEmployeeId>1</LoginEmployeeId><OverLapped>false</OverLapped></Table></DocumentElement>'')
--exec Proc_TA_InsertShiftAllocation @Year=2014,@Month=8,@UserId=1,@EntryDate=N''08/25/2019 11:49:55 AM'',@DateShift=N''8/1/2014'',@xml=@p6
--Select * from TA_Tbl_PermanentShiftAllocation Where EmployeeId=25 and Month=8
CREATE PROCEDURE [dbo].[Proc_TA_InsertShiftAllocation] 
(
   @Year Int,
   @Month Int,
   @UserId Int,
   @EntryDate nVarchar(25),
   @DateShift nVarchar(25),
   @xml xml
)
AS
BEGIN
	  --create table #TempEmployeeDetails(EmployeeID int)
	  Declare @Index int
	  Set @Index = 0;
	  EXEC sp_xml_preparedocument @Index OUTPUT, @xml
		  insert into TA_Tbl_PermanentShiftAllocation (EmployeeId,[Year],[Month],[Emp_Id],[TimeStamp],DateShift)
		  select EmpID,cast(@Year as nvarchar),cast(@Month as nvarchar),cast(@UserId as nvarchar),@EntryDate,@DateShift 
		  from OpenXML(@Index, ''/DocumentElement/Table'')
		  With (EmpID Bigint ''EmpID'') 
		  where not exists (select EmployeeId  FROM TA_Tbl_PermanentShiftAllocation WHERE EmployeeId = EmpID AND [Year] = @Year AND [Month] = @Month)
	  Exec sp_xml_removedocument @Index
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAuditField]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAuditField]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_InsertAuditField  
Description : insert into TA_Tbl_AuditField with required information
Tables Included : TA_Tbl_AuditField
Created By : Christopher.S   
Created On : 04-Jan-2008  
Modified By :  Christopher.S
Modified On :  14-Jan-2008
*/  
CREATE PROCEDURE [dbo].[Proc_TA_InsertAuditField] 
	-- Add the parameters for the stored procedure here
	@tableId decimal,
    @fieldName nvarchar(100),
	@fieldDescription nvarchar(100),
    @insertBitStatus bit,
    @updateBitStatus bit,
    @deleteBitStatus bit,
    @fieldStatus bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @recCount as int
	set @recCount = (select count(*) from Ta_tbl_AuditField where TableID=@tableId and FieldName=@fieldName)
	Declare @TableName varchar(max)
	Declare @DataType varchar(40)
	set @TableName=(select TableName from TA_Tbl_AuditTable where TableID=@tableId)
	select @DataType=name from sys.types where user_type_id=(
	select user_type_id from sys.columns where object_id=(select object_id from sys.tables where name=CONVERT(varchar(max),@TableName))
	and name=+convert(varchar(max),@fieldName))
	if (@recCount>0)
		Begin
			update TA_Tbl_AuditField set DataType=@DataType,InsertBit=@insertBitStatus,UpdateBit=@updateBitStatus,DeleteBit=@deleteBitStatus,Status= @fieldStatus where TableID=@tableId and FieldName=@fieldName
		End
	Else
		Begin
			INSERT INTO TA_Tbl_AuditField(TableID,FieldName,FieldDescription,InsertBit,UpdateBit,DeleteBit,Status,DataType) VALUES(@tableId,@fieldName,@fieldDescription,@insertBitStatus,@updateBitStatus,@deleteBitStatus,@fieldStatus,@DataType)
		End
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified BY : Manikandan.R
-- Modified Date: 15-Mar-2012
--	Modified By		:	Manjula.P
--	Modified On		:	05-Oct-2013
--	Descriptions	:	Checking additioanl weekly off already exit with levels and isdeleted
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertAddtionalWeeklyOffLevels] 
-- Add the parameters for the stored procedure here
@AdditionalWeekOffDay nvarchar(50),
@AdditionalWeekOffWeek nvarchar(50),
@EmpId int,
@XMLdata xml,
@Addl_WeeklyOff_Id int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	declare @AddWeekId int
	--Added by MAnjula.P on 05-Oct-2013
	create table #TempXML
	(
	Addl_WeeklyOff_Id int,
	LevelId int
	)
	DECLARE @IndexTemp int
	set @IndexTemp = 0 
	set @AddWeekId=@Addl_WeeklyOff_Id
	EXEC sp_xml_preparedocument @IndexTemp OUTPUT, @XMLdata
	insert into #TempXML
	select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@IndexTemp, ''/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels'')
	with (Addl_WeeklyOff_Id int ''Addl_WeeklyOff_Id'') as xm
	Exec sp_xml_removedocument @IndexTemp
	--*******************************************
	--select * from #TempXML
	if(@Addl_WeeklyOff_Id <>0)
		begin
		--Changing select with inner joins by Manjula.P on 05-Oct-2013
			if not exists(select * from TA_Tbl_Additional_WeeklyOff AW 
			inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
			inner join #TempXML on #TempXML.LevelId=AWL.LevelId 
			where Addl_WeekOff_Day=@AdditionalWeekOffDay and Addl_WeekOff_Week=@AdditionalWeekOffWeek and AW.Addl_WeeklyOff_Id<>@Addl_WeeklyOff_Id
			and IsDeleted=0 )
				begin
					update ta_tbl_Additional_weeklyoff set Addl_WeekOff_Day=@AdditionalWeekOffDay 
					, Addl_WeekOff_Week=@AdditionalWeekOffWeek where Addl_WeeklyOff_Id=@Addl_WeeklyOff_Id
					set @AddWeekId=@Addl_WeeklyOff_Id
					delete from TA_Tbl_Additional_WeeklyOff_Levels where Addl_WeeklyOff_Id=@Addl_WeeklyOff_Id
					DECLARE @Index1 int
					set @Index1 = 0 
					EXEC sp_xml_preparedocument @Index1 OUTPUT, @XMLdata
					insert into TA_Tbl_Additional_WeeklyOff_Levels
					select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@Index1, ''/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels'')
					with (Addl_WeeklyOff_Id int ''Addl_WeeklyOff_Id'') as xm
					Exec sp_xml_removedocument @Index1
					select ''1''
				end
			else
				begin
					select ''0''
				end
		end
	else
		begin
		--Changing select with inner joins by Manjula.P on 05-Oct-2013
			if not exists(select * from TA_Tbl_Additional_WeeklyOff AW 
			inner join TA_Tbl_Additional_WeeklyOff_Levels AWL on AWL.Addl_WeeklyOff_Id=AW.Addl_WeeklyOff_Id
			inner join #TempXML on #TempXML.LevelId=AWL.LevelId 
			where Addl_WeekOff_Day=@AdditionalWeekOffDay and Addl_WeekOff_Week=@AdditionalWeekOffWeek and IsDeleted=0)
				begin
					Insert into ta_tbl_Additional_weeklyoff(Addl_WeekOff_Day,Addl_WeekOff_Week,Emp_Id,IsDeleted) 
					values(@AdditionalWeekOffDay,@AdditionalWeekOffWeek,@EmpId,0)
					set @AddWeekId= (select @@Identity)
					DECLARE @Index int
					set @Index = 0 
					EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
					insert into TA_Tbl_Additional_WeeklyOff_Levels
					select @AddWeekId, xm.Addl_WeeklyOff_Id from OPENXML(@Index, ''/DocumentElement/TA_Tbl_Additional_WeeklyOff_Levels'')
					with (Addl_WeeklyOff_Id int ''Addl_WeeklyOff_Id'') as xm
					Exec sp_xml_removedocument @Index
					select ''1''
				end
			else
				begin
					select ''0''
				end
		end
		drop table #TempXML
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_Update_PunchTypes]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_Update_PunchTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_Insert_Update_PunchTypes]''I'',0,12,''Out Duty'',34,1
--Select * from ta_tbl_punchtypes
CREATE PROCEDURE [dbo].[Proc_TA_Insert_Update_PunchTypes] 
(
	@type CHAR,
	@PunchType_Id INT,
    @Terminal_Id INT,
	@PunchType  NVARCHAR(25),
	@Value NVARCHAR(25),
	@Emp_Id INT
)
AS
BEGIN
	DECLARE @sql as nvarchar(3000)
	DECLARE @Isdeleted BIT
	DECLARE @count INT
	DECLARE @result INT
	DECLARE @InOrOutEntry nvarchar(1)
	SET @Isdeleted=0
	SET @result=0
	IF(@PunchType = ''In'' OR @PunchType = ''Shift In'' OR @PunchType = ''Break In'' OR @PunchType = ''Lunch In'' OR @PunchType = ''Out Duty'' OR @PunchType = ''Official In'')
		BEGIN
			 SET @InOrOutEntry =  ''I''
		END
	ELSE IF(@PunchType = ''Out'' OR @PunchType = ''Shift Out'' OR @PunchType = ''Break Out'' OR @PunchType = ''Lunch Out'' OR @PunchType = ''In Duty'' OR @PunchType = ''Official Out'')
		BEGIN
			 SET @InOrOutEntry =  ''O''
		END
	--Insert
	IF (@type=''I'')
		BEGIN
			SET @count=(SELECT count(*) FROM TA_Tbl_PunchTypes WHERE ((Terminal_Id = @Terminal_Id AND PunchType = @PunchType)  OR (Terminal_Id = @Terminal_Id AND [Value] = @Value))  AND @Isdeleted=0)
			IF (@count=0)
				BEGIN
					INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(cast(@Terminal_Id as nvarchar(25)),@PunchType,@Value,cast(@Isdeleted as nvarchar(25)),cast(@Emp_Id as nvarchar(25)),cast(getdate() as nvarchar(25)),''A'')
					Declare @TerminalAutoID int
					if(@InOrOutEntry=''I'')
						begin
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID=''787'' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),''A'')
										end
								end            
						end
					if(@InOrOutEntry=''O'')
						begin
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID=''788'' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''788'' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),''A'')
										end
								end
							if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
								begin
									if not exists(select * from TA_Tbl_PunchTypes P
									inner join TA_Tbl_Terminal T on P.Terminal_Id=T.Terminal_Id
									where Terminal_ReaderID=''787'' and P.IsDeleted=0 and P.PunchType=@PunchType)
										begin
											set @TerminalAutoID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787'' and IsDeleted=0)
											INSERT INTO TA_Tbl_PunchTypes (Terminal_Id,PunchType,[Value],Isdeleted,Emp_Id,Time_Stamp,Addedby) VALUES(@TerminalAutoID,
											@PunchType,@Value,0,1,GETDATE(),''A'')
										end
								end        
						end
				END
			ELSE
				BEGIN
					SET @result=1
				END
		END
	-- Update
	IF (@type=''U'')
		BEGIN
			SELECT @count=count(*) FROM TA_Tbl_PunchTypes where ((Terminal_Id = @Terminal_Id AND PunchType = @PunchType)  OR (Terminal_Id = @Terminal_Id AND [Value] = @Value))  AND PunchType_Id <> @PunchType_Id AND @Isdeleted=0
			IF (@count=0)
				BEGIN
					UPDATE TA_Tbl_PunchTypes SET Terminal_Id = cast(@Terminal_Id as nvarchar(25)),
					PunchType = @PunchType,[Value] = @Value,
					Emp_Id = cast(@Emp_Id as nvarchar(25)),
					Time_Stamp = cast(getdate() as nvarchar(25)) 
					WHERE PunchType_Id = cast(@PunchType_Id as nvarchar(25))					
				END
			ELSE
				BEGIN
					SET @result=1
				END
		END
	SELECT @result
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_EntranceDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_EntranceDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Exec Proc_TA_Insert_EntranceDetails ''U'',6,''Testing Entrance Insert'',''Testing Entrance Insert'',1,4,4,''9'',''9'',1
CREATE PROCEDURE [dbo].[Proc_TA_Insert_EntranceDetails]
(        
	@TYPE CHAR(1)='''',
	@EntranceID INT=0,    
	@EntranceName NVARCHAR(50)='''',     
	@EntranceDesc NVARCHAR(255)='''',
	@OrgLevelId INT=0,    
	@NoOfInTerminals INT=0,
	@NoOfOutTerminals INT=0,
	@InTerminals NVARCHAR(max),
	@OutTerminals NVARCHAR(max),
	@EmpAutoID int=0        
)        
AS   
BEGIN
	SET NOCOUNT ON
	DECLARE @sql nvarchar(2000)	
	IF (@TYPE=''I'')
	BEGIN        
		-- Query to insert the Details into Entrance Table                           
		SET @sql = ''INSERT INTO TA_Tbl_Entrance(Entrance_Name, Entrance_Description, OrgLevel_Id,NoOfInTerminals,NoOfOutTerminals,IsDeleted,Emp_ID)        
	              VALUES(N'''''' + @EntranceName + '''''',N'''''' + @EntranceDesc + '''''','' + cast(@OrgLevelId as nvarchar(20)) + '','' + cast(@NoOfInTerminals as nvarchar(20)) + '','' + cast(@NoOfOutTerminals as nvarchar(20)) + '',0,''+cast(@EmpAutoID  as nvarchar(20))+'')''   
		EXEC(@sql)	
		SELECT @EntranceID = Entrance_Id FROM TA_Tbl_Entrance WHERE Entrance_Name=@EntranceName 
		AND Entrance_Description=@EntranceDesc AND OrgLevel_Id=@OrgLevelId AND NoOfInTerminals=@NoOfInTerminals AND NoOfOutTerminals=@NoOfOutTerminals
	END
	ELSE IF (@TYPE=''U'')
	BEGIN
 		-- Query to update the Details in the Entrance Table for a particular Entrance Id                        
		SET @sql = ''UPDATE TA_Tbl_Entrance SET Entrance_Name=N'''''' + @EntranceName + '''''', Entrance_Description=N'''''' + @EntranceDesc + '''''' ,OrgLevel_Id='' + cast(@OrgLevelId as nvarchar(20)) + '', NoOfInTerminals='' + cast(@NoOfInTerminals as nvarchar(20)) + '', NoOfOutTerminals='' + cast(@NoOfOutTerminals as nvarchar(20)) + '',Time_Stamp='''''' + cast(getdate() as nvarchar(20)) + '''''',Emp_ID=''+cast(@EmpAutoID  as nvarchar(20))+''
	              WHERE Entrance_Id='' + cast(@EntranceID as nvarchar(20)) + ''''
		EXEC(@sql)		
		-- Delete the IN/OUT Details from the Entrance INOUT Details Table  for a particular Entrance Id                    
		DELETE FROM TA_Tbl_Entrance_INOUTDetails WHERE Entrance_Id = @EntranceID
	END
	-- Split the Comma seperated IN Terminals and insert the Terminal Id and Type into the Entrance INOUT Details Table		
	INSERT INTO TA_Tbl_Entrance_INOUTDetails(Entrance_Id,Reader_Id,Type) 
	select @EntranceID,[Value],''In'' from [dbo].[Split](@InTerminals,'','')
	INSERT INTO TA_Tbl_Entrance_INOUTDetails(Entrance_Id,Reader_Id,Type) 
	select @EntranceID,[Value],''Out'' from [dbo].[Split](@OutTerminals,'','')
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GroupManualEntryEmployees]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GroupManualEntryEmployees]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- select * from TA_Tbl_TemporaryShiftAllocation
-- select * from TA_Tbl_PermanentShiftAllocation where year=2010 and Month=12
-- =============================================
-- Author:		senthil Proc_TA_RptTemporaryShift ''2010/10/05'',''5'','''','''',0,0,''SuperAdmin'',''0'','''',''2'',0
-- ALTER  date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_TA_GroupManualEntryEmployees]  
(
	@fromDate datetime,	
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@EmployeeName varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ShiftId varchar(10),
	@EmpAutoId bigint   		          
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Basic Pay Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
	(
		[PayId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--Employee Pay insert in Temporary table
	insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
	select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
	inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpBpay
	inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
	AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EPay.PayId is not null
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + '' SELECT dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,dbo.TA_Tbl_Shift.Shift_Name,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''''&amp;'''',''''&'''') as Shift_ShortName,dbo.TA_Tbl_Shift.Shift_StartTime,dbo.TA_Tbl_Shift.Shift_EndTime,dbo.TA_Tbl_Employee.Employee_FirstName + Space(1) + ''      
    set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Employee_LastName as empname, dbo.Ta_Tbl_levelDetails.name, dbo.TA_Tbl_Title.TitleName,isnull(TA_Tbl_ProcessedData.InTime,'''''''') as InTime,TA_Tbl_ProcessedData.Attendance'' 
    set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation LEFT OUTER JOIN''  
        		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN''
        		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
   			set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''      
			set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner JOIN dbo.TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' left outer join dbo.TA_Tbl_ProcessedData ON dbo.TA_Tbl_Employee.SwipeCardNo = dbo.TA_Tbl_ProcessedData.Employee_Code_Id''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
        set @sqlQuery = @sqlQuery + '' WHERE (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''
		set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
	if not(@EmployeeId='''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and (ta_tbl_Employee.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
		end 
	if not(@EmployeeName='''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end  
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
		end
    if(@EmpAutoId = 0)
    BEGIN
	if not(@LevelID='''' or @LevelID=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '') '' 
		end	
	END
	ELSE
		BEGIN
		   set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if not(@ShiftId='''' or @ShiftId=''0'' or @ShiftId=''All'')  
	begin  
		set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Shift.Shift_Id = '''''' + @ShiftId + '''''')''  
	end 
		set @sqlQuery = @sqlQuery + '' order by TA_Tbl_Employee.Employee_Code_Id'' 
exec (@sqlQuery)
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_HolidayRecursion]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_HolidayRecursion]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
					Proc_TA_HolidayRecursion ''03/16/2013''
Created By		:	Manjula.P
Created Date	:	23-May-2013
Descriptons		:	Creating proc for recursing to check local holiday by date by date.
*/
CREATE procedure [dbo].[Proc_TA_HolidayRecursion]
(
@date datetime
)
as
begin
	select * from TA_Tbl_Holiday where @date between Holiday_FromDate and Holiday_ToDate and Isdeleted=0
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_InsertEmp_LeavePolicy_YearClosure
Description	:	It is used to insert values for Employeee Leave Policy
Tables used	:	TA_Tbl_Emp_LeavePolicy and Ta_Tbl_YearSetting
Created by	:	Prabakaran.P
Created on	:	15-Feb-08
Proc_TA_InsertEmp_LeavePolicy_YearClosure 5,161,''01/01/2009'',''12/31/2009'',5,37
*/
CREATE   PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy_YearClosure]   
 @EmpID INT,  
 @LeavePolicyID INT,  
 @Fromdate NVARCHAR(15),  
 @Todate NVARCHAR(15),  
 @auEmployeeID INT,
 @YearSettingId int
AS  
declare @sql as nvarchar(3000)  
BEGIN  
 SET NOCOUNT ON;  
declare @count int 
set @count = (select count(*) from TA_Tbl_Emp_LeavePolicy where EmployeeId = @EmpID and LeavePolicy_Id=@LeavePolicyID and FromDate =@Fromdate and ToDate=@Todate)
if (@count=0)
	begin
		set @sql = ''INSERT INTO TA_Tbl_Emp_LeavePolicy (EmployeeId,LeavePolicy_Id,FromDate,ToDate,Isdeleted,Emp_Id,YearSettingId) VALUES (''+cast(@EmpID as nvarchar(25))+'',''+cast(@LeavePolicyID as nvarchar(25))+'',N''''''+@Fromdate+'''''',N''''''+@Todate+'''''',0,''+cast(@auEmployeeID as nvarchar(25))+'','' + cast(@YearSettingId as nvarchar(25)) + '')''  
		exec(@sql)
	end
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmp_LeavePolicy]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmp_LeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  Arun vinoth  
-- ALTER  date: <ALTER  Date,,>  
-- Description: <Description,,>  
-- Modified by : Prabakaran.P
-- Modified on : 24-Mar-08
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmp_LeavePolicy]   
 @EmployeeId INT,  
 @LeavePolicyID INT,  
 @Fromdate NVARCHAR(15),  
 @Todate NVARCHAR(15),  
 @auEmpId INT   
AS  
BEGIN  
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)  
	declare @count int 
	declare @YearSettingId as int
	select @count =count(*) from TA_Tbl_Emp_LeavePolicy where EmployeeId = @EmployeeId and  
	((FromDate between @Fromdate and @todate) or (ToDate between @fromDate and @Todate))	
	if (@count=0)
	begin
		select @YearSettingId=YearSettings_Id from Ta_Tbl_YearSetting where IsActive=1
		set @sql = ''INSERT INTO TA_Tbl_Emp_LeavePolicy (EmployeeId,LeavePolicy_Id,FromDate,ToDate,Isdeleted,Emp_Id,YearSettingId)  
					 VALUES (''+cast(@EmployeeId as nvarchar(25))+'',''+cast(@LeavePolicyID as nvarchar(25))+'',N''''''+@Fromdate+'''''',N''''''+@Todate+'''''',0,''+cast(@auEmpId as nvarchar(25))+'','' + cast(@YearSettingId as nvarchar(25)) + '')''  
		exec(@sql) 
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmailIdsForMailTriggering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmailIdsForMailTriggering]
(
	@ScheduleId int,
	@MailType varchar(5),
	@EmailId varchar(250)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	insert into TA_tbl_MailIdsForTriggeringEmail (ScheduleId,MailType,EmailID) values (@ScheduleId,@MailType,@EmailId)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_insertCompOffOTStatus]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_insertCompOffOTStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_EmployeeOTStatus  
Description		:	To Update the OverTime Status in ta_tbl_processedData  table
Tables Included :	ta_tbl_ProcessedData,ta_tbl_Employee  
Created By		:	Karthikeyan.R
Created On		:	21-Mar-2017
Proc_TA_insertCompOffOTStatus 23685,45,''2017/04/11'',''2017/04/02'',''12:00'',720,''Approved'',1,''Weekly Off'',''09:00'',''21:00'',''Test'',0,''I''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_insertCompOffOTStatus]
	@Process_Rec_ID BIGINT ,
	@Employee_Id INT ,
	@ApplicationDate datetime ,
	@Date datetime ,
	@HrsExtra VARCHAR(5) ,
	@ExtraMins INT ,
	@Status VARCHAR(50) ,
	@TopLevelId INT,
	@DaysWorked nvarchar(25),
	@InTime nvarchar(20),
	@OutTime nvarchar(20),
	@Reason nvarchar(250),
	@ExtraTime_Id bigint,
	@tag nvarchar(2)
As
BEGIN 
	set nocount on
	declare @ProcessID as bigint
	DECLARE @Index INT 
		set @Index= 0
		DECLARE @HalfDayOTMins BIGINT, @FullDayOTMins BIGINT, @TypeOfOT BIGINT,@OtText VARCHAR(MAX)
		DECLARE @CompOffDays FLOAT, @SumOfOTMins FLOAT,@MaxDate DATETIME
		DECLARE @ValidDates INT
		DECLARE @FromDate DATETIME, @ToDate DATETIME
		DECLARE @Employee_code_Id NVARCHAR(50)
		SET @CompOffDays = 0
		SET @SumOfOTMins = 0
		SET @OtText = ''''
	--IF Update then delete the record and insert again.
	IF(@tag=''D'')
	BEGIN
		IF NOT EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE Employee_Id=@Employee_Id and isdelete=0 and Date=@Date)
		BEGIN
			select @ProcessID=Process_RecID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
			update TA_Tbl_ProcessedData set OvertimeStatus=null where Process_Rec_ID=@ProcessID
			delete from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
		END
		else
		BEGIn
			IF EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE ExtraTime_Id=@ExtraTime_Id)
			BEGIn
				select @ProcessID=Process_RecID from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
				update TA_Tbl_ProcessedData set OvertimeStatus=null where Process_Rec_ID=@ProcessID
				delete from TA_Tbl_OverTimeStatus where ExtraTime_Id=@ExtraTime_Id
			END
			else
			BEGIN
				SELECT ''0''
			END
		END
	END
	IF NOT EXISTS(SELECT ExtraTime_Id FROM TA_Tbl_OverTimeStatus WHERE Employee_Id=@Employee_Id and isdelete=0 and Date=@Date)
	BEGIN
		--Declare the temp table for the insert and update perpose.
		DECLARE @TblRecords TABLE(Process_RecID BIGINT, Employee_Id INT,ApplicationDate varchar(20),[Date] varchar(20), HrsExtra VARCHAR(5), ExtraMins INT, OverTimeStatus VARCHAR(50), CompOffEligible BIT, OTEligible BIT, DateToExpired DATETIME, NoOfDays NUMERIC(18,1), RemainingDays NUMERIC(18,1), CompOffSatus VARCHAR(30), TopLevelId INT, UpdatedRow VARCHAR(1),DaysWorked nvarchar(20),InTime nvarchar(20),OutTime nvarchar(20),Reason nvarchar(250))
		-- Insert the values from variable
		INSERT INTO @TblRecords(Process_RecID, Employee_Id,ApplicationDate, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, TopLevelId,DaysWorked, InTime, OutTime,Reason) values (@Process_Rec_ID,@Employee_Id,@ApplicationDate,@Date ,@HrsExtra ,@ExtraMins,@Status,1,0,@TopLevelId,@DaysWorked,@InTime,@OutTime,@Reason)
		SELECT @Employee_code_Id = Employee_Code_Id FROM TA_Tbl_Employee WHERE Employee_Id = @Employee_Id AND IsDeleted=0
		SELECT @FromDate = FromDate,@ToDate = ToDate FROM TA_Tbl_YearSetting WHERE YearSettings_Id in (select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)
			SELECT		@TypeOfOT = OtHourWise,
						@HalfDayOTMins = DATEDIFF(MI,''00:00'', ISNULL(OtMinHrs, ''00:00'')),
						@FullDayOTMins = DATEDIFF(MI,''00:00'',ISNULL(FullDayOTMinHrs, ''00:00'')),
						@ValidDates = ISNULL(LP.CompOffValidDays, 60)
						FROM TA_Tbl_LeavePolicy LP INNER JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.LeavePolicy_Id = LP.Policy_Id
						WHERE ELP.EmployeeId = @Employee_Id AND ELP.ToDate = (SELECT TOP 1 ELP.ToDate FROM TA_Tbl_Emp_LeavePolicy ELP
						INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
						WHERE YS.IsActive = 1 AND ELP.EmployeeId = @Employee_Id ORDER BY ELP.ToDate DESC)
		update @TblRecords set DateToExpired=(DATEADD(D, @ValidDates, [Date])),NoOfDays=(CASE WHEN ExtraMins >= @FullDayOTMins THEN 1.0 WHEN ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),RemainingDays=(CASE WHEN ExtraMins >= @FullDayOTMins THEN 1.0 WHEN ExtraMins >= @HalfDayOTMins THEN 0.5 ELSE 0.0 END),CompOffSatus=(CASE WHEN DATEADD(D,ISNULL(@ValidDates, 0),[Date]) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END)
		--Comment by karthikeyan.R 
		--IF(@TypeOfOT=1)
				--	BEGIN
				--		SELECT 
				--			@SumOfOTMins = (@SumOfOTMins + OtMins),
				--			@MaxDate = (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN [Date] WHEN @SumOfOTMins >= @HalfDayOTMins THEN [Date] ELSE NULL END),
				--			@OtText = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @OtText ELSE (@OtText + '';'' + CAST(Process_Rec_ID AS VARCHAR(50)) + ''&'' + CAST((CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN @FullDayOTMins WHEN @SumOfOTMins >= @HalfDayOTMins THEN @HalfDayOTMins ELSE @SumOfOTMins END) AS VARCHAR(10))) END),
				--			@SumOfOTMins = (CASE WHEN ISNULL(@MaxDate, '''') = '''' THEN @SumOfOTMins ELSE (CASE WHEN @SumOfOTMins >= @FullDayOTMins THEN 0 WHEN @SumOfOTMins >= @HalfDayOTMins THEN (@SumOfOTMins - @HalfDayOTMins) ELSE @SumOfOTMins END) END),
				--			@MaxDate = NULL
				--		FROM TA_Tbl_ProcessedData
				--			WHERE ([Date] BETWEEN @FromDate AND @ToDate) AND Employee_Code_Id = @Employee_code_Id 
				--			AND (DATEADD(D, @ValidDates, [Date])) >= @Date AND OtMins > 0 AND ISNULL(OtMins, '''') != ''''
				--		ORDER BY [Date]
				--	END
			--UPDATE @TblRecords SET 
		--	DateToExpired = CASE WHEN (TR.OverTimeStatus = ''Pending'' or TR.OverTimeStatus = ''Forwarded'' or TR.OverTimeStatus = ''Approved'')
		--	AND TR.CompOffEligible = 1 THEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0), CONVERT(datetime,TR.[Date],103)) END,
		--	NoOfDays =	CASE WHEN (TR.OverTimeStatus = ''Pending'' or TR.OverTimeStatus = ''Forwarded'' or TR.OverTimeStatus = ''Approved'') AND TR.CompOffEligible = 1 THEN	
		--									(	CASE	WHEN TR.ExtraMins / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN ''1.0'' 
		--													WHEN TR.ExtraMins/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' 
		--										END
		--									) 
		--							END,
		--	RemainingDays = CASE WHEN (TR.OverTimeStatus = ''Pending'' or TR.OverTimeStatus = ''Forwarded'' or TR.OverTimeStatus = ''Approved'') AND TR.CompOffEligible = 1 THEN (CASE WHEN TR.ExtraMins / DATEDIFF(MI,''00:00'' ,SS.FullDayCompOff) > 0 THEN ''1.0'' WHEN TR.ExtraMins/ DATEDIFF(MI,''00:00'' ,SS.HalfDayCompOff) > 0 THEN ''0.5'' END) END,
		--	CompOffSatus = CASE WHEN (TR.OverTimeStatus = ''Pending'' or TR.OverTimeStatus = ''Forwarded'' or TR.OverTimeStatus = ''Approved'') AND TR.CompOffEligible = 1 THEN (CASE WHEN DATEADD(D,ISNULL(SS.VaildityCompOffDays, 0),CONVERT(datetime,TR.[Date],103)) < GETDATE() THEN ''Expired'' ELSE ''Not Taken'' END) END
		--FROM @TblRecords TR
		--INNER JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = TR.Process_RecID
		--LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = TR.TopLevelId
		--select * from @TblRecords
		INSERT INTO TA_Tbl_OverTimeStatus(Process_RecID, Employee_Id,ApplicationDate, [Date], HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, DateToExpired, NoOfDays, RemainingDays, CompOffSatus,isRequest,DaysWorked,InTime, OutTime,Reason,isDelete)
			SELECT Process_RecID, Employee_Id,CONVERT(datetime,ApplicationDate,103),CONVERT(datetime,[Date],103), 
			HrsExtra, ExtraMins, OverTimeStatus, CompOffEligible, OTEligible, 
			DateToExpired, NoOfDays, RemainingDays, CompOffSatus,1,DaysWorked,InTime,OutTime,Reason,0 FROM @TblRecords 
			--select * from @TblRecords
		SELECT ''1'' 
	END	 
	else
	begin
		SELECT ''0''    
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertCompensationEntry]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertCompensationEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/**********************************************************
Updated by    :A.Amsaveni  on 02/07/2013
Description   : added and Isdeleted=0  
***********************************************************/
-- Proc_TA_InsertCompensationEntry ''654'',''2017-01-19'',''2016-12-04'',1,''Test'',''Pending for Approval'',''10:51 AM'',''05:51 PM'',''07:00'',''Weekly Off'','''',1,-1
Create PROCEDURE [dbo].[Proc_TA_InsertCompensationEntry]
	@Employee_Id NVARCHAR(20),
	@ApplicationDate DATETIME,
	@FromDate DATETIME,
	@Status NVARCHAR(20),
	@InTime NVARCHAR(20),
	@OutTime NVARCHAR(20),
	@WorkedHours NVARCHAR(20),
	@DayWorked NVARCHAR(20),
	@ExpDate DATETIME,
	@Quota float, 
	@Empid bigint
AS      
BEGIN      
	SET NOCOUNT ON;		  
	IF NOT EXISTS(SELECT Compensation_Id FROM ta_tbl_compensation WHERE Employee_Id=@Employee_Id and Fromdate=@FromDate and Isdeleted=0)    
	BEGIN
		DECLARE @EmployeeId INT
		DECLARE @levelId AS BIGINT
		Declare @ExpiryDuration int
		Declare @HalfDayCompOff int
		Declare @FullDayCompOff int
		Declare @TotWorkedMins int		
		--Added by manikandan.R on 19-11-2016
		select * from TA_Tbl_ShiftSettings
		--Get Exp date
		select @ExpiryDuration=VaildityCompOffDays from TA_Tbl_ShiftSettings	
		-- Get Employee ID from employee master
		SELECT @EmployeeId=Employee_Id  FROM ta_tbl_employee WHERE employee_code_Id=@Employee_Id  and Isdeleted=0 
		--Get Level Id from employee leave table
		select @levelId=LevelId from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId order by EffectiveDate
		set @TotWorkedMins=SUBSTRING(@WorkedHours,0,CHARINDEX('':'',@WorkedHours))*60+SUBSTRING(@WorkedHours,CHARINDEX('':'',@WorkedHours)+1,LEN(@WorkedHours))
		set @ExpDate=DATEADD(d,@ExpiryDuration,@FromDate)	
		INSERT INTO TA_Tbl_Compensation
		(
			Employee_Id,
			ApplicationDate,
			FromDate,				
			LevelId,
			status,
			InTime,
			OutTime,
			WorkedHours,
			DayWorked,
			ExpiredDate,
			Quota,
			empid,
			ApprovedBy,
			ApprovedDate,				
			TimeStamp,
			Isdeleted,
			RemainingLeave
		)
		VALUES
		(
			@Employee_Id,
			@ApplicationDate,
			@FromDate,
			@levelId,
			@Status,
			@InTime,
			@OutTime,
			@WorkedHours,
			@DayWorked,
			@ExpDate,
			case when @TotWorkedMins>=@FullDayCompOff then 1 else 0.5 end,
			@Empid,
			case when @Status=''Approved'' then @Empid else null end,
			case when @Status=''Approved'' then getdate() else null end,
			GETDATE(),
			0,
			case when @TotWorkedMins>=@FullDayCompOff then 1 else 0.5 end
		)
		SELECT ''1'' 
	END  
	ELSE    
	BEGIN    
		SELECT ''0''    
	END    
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPunchTypes_FromDevice_New]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Karthikeyan.R
Created On		:	05-Mar-2016
Descriptions	:	Inserting punch types directly from the device using window service (Collect Raw Data)
exec Proc_TA_InsertPunchTypes_FromDevice_New @ConnString=N''Provider=SQLOLEDB.1;Data Source=angler97\sqlexpress;Initial Catalog=biostar;User Id=sa;pwd=angler123;''
*/
CREATE proc [dbo].[Proc_TA_InsertPunchTypes_FromDevice_New] 
@ConnString as nvarchar(Max)
as
begin
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
	BEGIN
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	--@sql2 for application db query
	DECLARE @sql2 nvarchar(max)
	--@sql1 for device db query
	DECLARE @sql1 nvarchar(max)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	--Creating temprary table for getting terminal data values 
	create table #Temp_PunchType
	(
	ID int identity(1,1),
	strName nvarchar(32),
	nTNAEvent int not null,
	ndeviceid nvarchar(10),
	TerminalId int
	)
	--**********************************************************
				SET @ConnectionString=@ConnString
				--Create table To splitup the Server and database name
				--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
				IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
					BEGIN
						INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
						SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=2				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=3)				
						UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=4)
						--select * from Ta_tbl_DeviceServerDetails			
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=5)				
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						--select * from  Ta_tbl_DeviceServerDetails
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
					END			
				SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails	
				--exec sp_addlinkedserver @ServerName;
				--creating linked server and linkedserverlogin by Manjula.P on 06-Feb-2014
				if not exists(select * from sys.servers where name = N''''+@ServerName+'''')
				begin
					EXEC sp_addlinkedserver @server=@ServerName
				end
					declare @suser_sname nvarchar(256)
					set  @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N''False'',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------				
				select * from Ta_tbl_DeviceServerDetails			
				CREATE TABLE #test(exist int,TableName varchar(500))
				Create table #DeviceDetailsMovedToTimecheck(name varchar(50))
				--TB_EVENT_LOG,	TB_TA_DEVICE_EVENT_KEY= in BioStar Device 
				--tb_userevent = in BioAdmin Device			
				set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''TB_EVENT_LOG'''',''''TB_TA_DEVICE_EVENT_KEY'''',''''tb_userevent'''')''
				Insert into #test exec(@sql)
				--select * from #test				
				--It means the connected device checked whether its BioAdmin			
				if ((select COUNT(*) from #test where TableName =''tb_userevent'')>0)
					begin						
						set @sql1=''''
						set @sql1='' select distinct(RL.ndeviceid),RL.ndeviceid,RL.ndeviceid,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_reportslist RL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent  where RL.ndeviceid not in(''
						set @sql2='' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 ) ''						
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						--INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	     --               SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType=''RDBMS''),1,GETDATE(),0 from #Temp_PunchType
	     --               update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	     --               inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''''
						set @sql1=''select distinct(strName),UE.nIndex,ndeviceid,T.Terminal_Id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_reportslist RL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RL.nDeviceID and T.isDeleted=0 and isnumeric(Terminal_ReaderID)=1 where strName not in( ''
						set @sql2='' select PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join  [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=P.Value  where P.Isdeleted=0  and T.Isdeleted=0 and P.Terminal_Id=T.Terminal_Id and P.Value=UE.nindex ) group by strName,UE.nIndex,ndeviceid,T.Terminal_Id''
						delete from #Temp_PunchType;
						insert into #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                   -- where nTNAEvent not in (select Value from TA_Tbl_PunchTypes)	              
					end
				--It means the connected device checked whether its BioStar
				else if((select COUNT(*) from #test where TableName in (''TB_EVENT_LOG'',''TB_TA_DEVICE_EVENT_KEY''))>1)
					begin						
						set @sql1=''''
						set @sql1=''select distinct(EL.nReaderIdn) as strName,EL.nReaderIdn,EL.nReaderIdn as ndeviceid,0  from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_EVENT_LOG EL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  ''
						set @sql1=@sql1+''  where convert(varchar(20),EL.nReaderIdn) not in( ''
						set @sql2='' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )order by ndeviceid ''
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
	     --               update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	     --               inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''''
						set @sql1=''select distinct(sEventName) as strName,DEK.nKeyIdn,EL.nReaderIdn as ndeviceid,T.Terminal_Id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_EVENT_LOG EL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  ''
						set @sql1=@sql1+''  inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=EL.nReaderIdn and T.Isdeleted=0 and isnumeric(Terminal_ReaderID)=1 where sEventName not in( ''
						set @sql2='' select PunchType  from TA_Tbl_PunchTypes P  inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on  DEK.nReaderIdn=T.Terminal_ReaderID where P.Isdeleted=0 and T.Isdeleted=0 and P.Terminal_Id =T.Terminal_Id and P.PunchType=sEventName and P.Value=DEK.nKeyIdn ) group by sEventName,DEK.nKeyIdn ,EL.nReaderIdn,T.Terminal_Id''
						delete from #Temp_PunchType;
						insert into #Temp_PunchType						
						--select * from #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE(),''S''  from  #Temp_PunchType
	                    --Insert the punch type for the default terminal like 787 and 788
						declare @InTerminalID int
						declare @OutTerminalID int
						set @InTerminalID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=787)
						set @OutTerminalID=(select Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=788)
						INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select distinct @InTerminalID,strName,nTNAEvent,0,1,GETDATE(),''S''  from  #Temp_PunchType  inner join TA_Tbl_PunchTypes on TA_Tbl_PunchTypes.Value != #Temp_PunchType.nTNAEvent and #Temp_PunchType.strName != TA_Tbl_PunchTypes.PunchType  where strName like ''%IN%'' and Terminal_Id=@InTerminalID 
						INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp,Addedby)
	                    select distinct @OutTerminalID,strName,nTNAEvent,0,1,GETDATE(),''S''  from  #Temp_PunchType inner join TA_Tbl_PunchTypes on TA_Tbl_PunchTypes.Value != #Temp_PunchType.nTNAEvent and #Temp_PunchType.strName != TA_Tbl_PunchTypes.PunchType  where strName like ''%OUT%'' and Terminal_Id=@OutTerminalID  
					end
					--select * from #Temp_PunchType
					delete from Ta_tbl_DeviceServerDetails
	--Drop temp tables
	drop table #Temp_PunchType
	end	
end
-------------------------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertPunchTypes_FromDevice]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertPunchTypes_FromDevice]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created On		:	27-Nov-2013
Descriptions	:	Inserting punch types directly from the device using window service (Collect Raw Data)
*/
CREATE proc [dbo].[Proc_TA_InsertPunchTypes_FromDevice]
as
begin
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	IF((SELECT count(FileType) FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)>0)
	BEGIN
	DECLARE @sql VARCHAR(2000)
	DECLARE @UpdateToTimecheckFlag varchar(8000)
	--@sql2 for application db query
	DECLARE @sql2 nvarchar(max)
	--@sql1 for device db query
	DECLARE @sql1 nvarchar(max)
	DECLARE @ConnectionString NVARCHAR(2000)
	DECLARE @ServerName NVARCHAR(2000)
	DECLARE @DatabaseName NVARCHAR(2000)
	DECLARE @UserId NVARCHAR(100)
	DECLARE @Password NVARCHAR(100)
	--Creating temprary table for getting terminal data values 
	create table #Temp_PunchType
	(
	strName nvarchar(32),
	nTNAEvent int not null,
	ndeviceid nvarchar(10),
	TerminalId int
	)
	--**********************************************************
		IF((SELECT top 1 FileType FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=''RDBMS'' and (SELECT top 1 BrandId FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0)=3)
			BEGIN
				SET @ConnectionString=(SELECT ConnectionString FROM TA_tbl_TerminalDatatype WHERE IsDeleted=0 and FileType=''RDBMS'' and BrandId=3)
				--Create table To splitup the Server and database name
				--Create table Ta_tbl_DeviceServerDetails(ServerName nvarchar(1000),DatabaseName nvarchar(1000))
				IF ((SELECT COUNT(*) FROM Ta_tbl_DeviceServerDetails)=0)
					BEGIN
						INSERT INTO Ta_tbl_DeviceServerDetails(ServerName)
						SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=2				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=3)				
						UPDATE Ta_tbl_DeviceServerDetails SET ServerName=(SELECT Value FROM(SELECT * FROM Split((SELECT servername FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)				
						UPDATE Ta_tbl_DeviceServerDetails SET DatabaseName=(SELECT Value FROM(SELECT * FROM Split((SELECT DatabaseName FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=4)
						--select * from Ta_tbl_DeviceServerDetails			
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split(@ConnectionString,'';''))AS A WHERE Id=5)				
						UPDATE Ta_tbl_DeviceServerDetails SET UserId=(SELECT Value FROM(SELECT * FROM Split((SELECT UserId FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
						--select * from  Ta_tbl_DeviceServerDetails
						UPDATE Ta_tbl_DeviceServerDetails SET Password=(SELECT Value FROM(SELECT * FROM Split((SELECT Password FROM Ta_tbl_DeviceServerDetails),''=''))AS B WHERE Id=2)
					END			
				SELECT @ServerName=ServerName,@DatabaseName=DatabaseName,@UserId=UserId,@Password=Password FROM Ta_tbl_DeviceServerDetails	
				--exec sp_addlinkedserver @ServerName;
				--creating linked server and linkedserverlogin by Manjula.P on 06-Feb-2014
				if not exists(select * from sys.servers where name = N''''+@ServerName+'''')
				begin
					EXEC sp_addlinkedserver @server=@ServerName
				end
					declare @suser_sname nvarchar(256)
					set  @suser_sname= suser_sname()
					EXEC master.dbo.sp_addlinkedsrvlogin 
					@rmtsrvname=@ServerName,
					@useself=N''False'',
					@locallogin=@suser_sname,
					@rmtuser=@UserId,
					@rmtpassword=@Password
				--------------------------------------------				
				select * from Ta_tbl_DeviceServerDetails			
				CREATE TABLE #test(exist int,TableName varchar(500))
				Create table #DeviceDetailsMovedToTimecheck(name varchar(50))
				--TB_EVENT_LOG,	TB_TA_DEVICE_EVENT_KEY= in BioStar Device 
				--tb_userevent = in BioAdmin Device			
				set @sql=''SELECT object_id,name FROM [''+ @ServerName +''].[''+ @DatabaseName+''].sys.tables WHERE name in(''''TB_EVENT_LOG'''',''''TB_TA_DEVICE_EVENT_KEY'''',''''tb_userevent'''')''
				Insert into #test exec(@sql)
				--select * from #test				
				--It means the connected device checked whether its BioAdmin			
				if ((select COUNT(*) from #test where TableName =''tb_userevent'')>0)
					begin						
						set @sql1=''''
						set @sql1='' select distinct(RL.ndeviceid),RL.ndeviceid,RL.ndeviceid,0 from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_reportslist RL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent  where RL.ndeviceid not in(''
						set @sql2='' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 ) ''						
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	                    SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType=''RDBMS''),1,GETDATE(),0 from #Temp_PunchType
	                    update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	                    inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''''
						set @sql1=''select distinct(strName),UE.nIndex,ndeviceid,T.Terminal_Id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_reportslist RL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=RL.nTNAEvent inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RL.nDeviceID and T.isDeleted=0 and isnumeric(Terminal_ReaderID)=1 where strName not in( ''
						set @sql2='' select PunchType from TA_Tbl_PunchTypes P inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join  [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.tb_userevent UE on UE.nIndex=P.Value  where P.Isdeleted=0  and T.Isdeleted=0 and P.Terminal_Id=T.Terminal_Id and P.Value=UE.nindex ) group by strName,UE.nIndex,ndeviceid,T.Terminal_Id''
						delete from #Temp_PunchType;
						insert into #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                   -- where nTNAEvent not in (select Value from TA_Tbl_PunchTypes)	              
					end
				--It means the connected device checked whether its BioStar
				else if((select COUNT(*) from #test where TableName in (''TB_EVENT_LOG'',''TB_TA_DEVICE_EVENT_KEY''))>1)
					begin						
						set @sql1=''''
						set @sql1=''select distinct(EL.nReaderIdn) as strName,EL.nReaderIdn,EL.nReaderIdn as ndeviceid,0  from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_EVENT_LOG EL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  ''
						set @sql1=@sql1+''  where convert(varchar(20),EL.nReaderIdn) not in( ''
						set @sql2='' select Terminal_ReaderID from ta_tbl_terminal where isDeleted=0 and isnumeric(Terminal_ReaderID)=1 )order by ndeviceid ''
						insert into #Temp_PunchType
						exec(@sql1+@sql2);
						--select * from #Temp_PunchType
						--Inserting trerminal id for punch type mapping with terminal if the device is not saved in db
						INSERT INTO TA_Tbl_Terminal(Terminal_ReaderID,Terminal_Name,Terminal_Description,TerminalDatatype_ID,Emp_ID,Time_Stamp,IsDeleted)
	                    SELECT ndeviceid ,ndeviceid,ndeviceid,(select top 1 TerminalDatatype_ID from TA_tbl_TerminalDatatype where FileType=''RDBMS'' and BrandId=3 and IsDeleted=0),1,GETDATE(),0 from #Temp_PunchType
	                    update Temp set TerminalId=T.Terminal_Id from #Temp_PunchType Temp
	                    inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=Temp.ndeviceid
	                    --Inserting punch type
	                    set @sql1=''''
						set @sql1=''select distinct(sEventName) as strName,DEK.nKeyIdn,EL.nReaderIdn as ndeviceid,T.Terminal_Id from [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_EVENT_LOG EL inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on DEK.nReaderIdn=EL.nReaderIdn  ''
						set @sql1=@sql1+''  inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=EL.nReaderIdn and T.Isdeleted=0 and isnumeric(Terminal_ReaderID)=1 where sEventName not in( ''
						set @sql2='' select PunchType  from TA_Tbl_PunchTypes P  inner join TA_Tbl_Terminal T on T.Terminal_Id=P.Terminal_Id inner join [''+ @ServerName +''].[''+ @DatabaseName+''].dbo.TB_TA_DEVICE_EVENT_KEY DEK on  DEK.nReaderIdn=T.Terminal_ReaderID where P.Isdeleted=0 and T.Isdeleted=0 and P.Terminal_Id =T.Terminal_Id and P.PunchType=sEventName and P.Value=DEK.nKeyIdn ) group by sEventName,DEK.nKeyIdn ,EL.nReaderIdn,T.Terminal_Id''
						delete from #Temp_PunchType;
						insert into #Temp_PunchType						
						--select * from #Temp_PunchType
						exec(@sql1+@sql2); 
	                    INSERT INTO TA_Tbl_PunchTypes(Terminal_Id,PunchType,Value,Isdeleted,Emp_Id,Time_Stamp)
	                    select TerminalId,strName,nTNAEvent,0,1,GETDATE()  from  #Temp_PunchType
	                    --where nTNAEvent not in (select Value from TA_Tbl_PunchTypes )	and TerminalId not in (select TerminalId from TA_Tbl_PunchTypes)              
					end
					delete from Ta_tbl_DeviceServerDetails
			end
	--Drop temp tables
	drop table #Temp_PunchType
	end	
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeavePolicyDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeavePolicyDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- ALTER  date: 13 Jan 2010
-- Description:	Leave Policy details Insert
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeavePolicyDetails]
	-- Add the parameters for the stored procedure here
		@Policy_Id INT,
		@LeaveType_Id INT,
		@MaxDays_applicable FLOAT=0,
        @MaxDaysPerMonth FLOAT=0,
		@MaxDays_avail FLOAT=0,
		@MinDays_avail FLOAT=0,
		@Spells INT,
		@MaxDays_Acc FLOAT=0,
		@LossOfPay BIT,
		@Max_LOP_Days FLOAT=0,
		@Count_BeforeWeeklyOff BIT,
		@Count_AfterWeeklyOff BIT,
		@Count_Intervening BIT,
		@Borrow_FromNextYear BIT,
		@Carry_ToNextYear BIT,
		@Encashment BIT,
		@Calc_Factor FLOAT=0,
		@MinWorkDays FLOAT=0,
		@WeekDays BIT,
		@WeekOff BIT,
		@Leave BIT,
		@Holidays BIT,
		@ApplicableAfterDays FLOAT,
		@Employee_Id INT,
		@AvailServicePeriod int
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TA_Tbl_LeavePolicyDetails (Policy_Id,LeaveType_Id,MaxDays_applicable,MaxDays_Month,MaxDays_avail,MinDays_avail,Spells,MaxDays_Acc,LossOfPay,Max_LOP_Days,Count_BeforeWeeklyOff,Count_AfterWeeklyOff,Count_Intervening,Borrow_FromNextYear,Carry_ToNextYear,Encashment,Calc_Factor,MinWorkDays,WeekDays,WeekOff,Leave,Holidays,ApplicableAfterDays,Emp_Id,AvailServicePeriod)
	VALUES (@Policy_Id,@LeaveType_Id,@MaxDays_applicable,@MaxDaysPerMonth,@MaxDays_avail,@MinDays_avail,@Spells,@MaxDays_Acc,@LossOfPay,@Max_LOP_Days,@Count_BeforeWeeklyOff,@Count_AfterWeeklyOff,@Count_Intervening,@Borrow_FromNextYear,@Carry_ToNextYear,@Encashment,@Calc_Factor,@MinWorkDays,@WeekDays,@WeekOff,@Leave,@Holidays,@ApplicableAfterDays,@Employee_Id,@AvailServicePeriod)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplication_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_InsertLeaveApplication  ''5'',''03/17/2008'',''52'',''Leave'',''03/17/2008'',''03/17/2008'',''First Session'',''Second Session'',1.0,''TEst Reason'',0,6,''''
--exec Proc_TA_InsertLeaveApplication @leaveApplicationId=628,@EmployeeID=35,@Leave_ApplicationDate=''2013-07-02 00:00:00'',@LeaveType_id=1,@Type=N''Leave'',@Leave_FromDate=''2013-07-05 00:00:00'',@Leave_ToDate=''2013-07-05 00:00:00'',@Leave_SessionFrom=N''First Half'',@Leave_SessionTo=N''Second Half'',@NumberOfDays=1.00,@Reason=N''Test Chennai....'',@IsBorrow=0,@auEmpId=N''1'',@YearSettings_Id=N''6'',@LeaveStatus=N'''',@intimationType=N''P'',@CCMail='''',@InformTo=''''
CREATE     PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication_Angler]  
(
  --Proc_TA_InsertLeaveApplication  '''','''','''',''صباح'','''','''',''صerبewrاح'',''صباewrحrewr'',1.0,''صبerاح''
@leaveApplicationId int,
@EmployeeID int,
@Leave_ApplicationDate datetime,
@LeaveType_id int,
@Type nvarchar(20),
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@Leave_SessionFrom nvarchar(20),
@Leave_SessionTo nvarchar(20),
@NumberOfDays decimal(8,2),
@Reason nvarchar(1050),
@IsBorrow int,
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@InformTo VARCHAR(MAX) = NULL
)  
as  
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF(@intimationType != ''UP-WI'')
BEGIN
	SET @InformTo = NULL
END
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Leave_ToDate as nvarchar(50)), 102) and EL.LevelId is not null
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @CountRecord as int  
set @CountRecord=(select count(*) from Ta_tbl_employee where Leave_Sanc_Authority=Reporting_to and Employee_Id=@EmployeeID)  
declare @sql nvarchar(2000)
set @sql=''''
	begin
		if(@LeaveStatus='''' and @CountRecord>0)
			BEGIN
			set @LeaveStatus=''Forwarded''
			END
		else if (@LeaveStatus='''' and @CountRecord=0)
			BEGIN
			set @LeaveStatus=''Pending''
			END
	--Insert Method  
	begin  
if(@LeaveStatus!=''Reply'')
BEGIN
		set @sql= @sql + ''INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Reason,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)''
		set @sql= @sql + ''VALUES('''''' + cast(@leaveApplicationId as nvarchar(20)) + '''''','''''' + cast(@EmployeeID as nvarchar(20)) + '''''','''''' + cast(@Leave_ApplicationDate as nvarchar(20)) + '''''',''''''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + '''''',N'''''' + @Type + '''''','''''' + cast(@Leave_FromDate as nvarchar(20))+ '''''',''''''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ '''''',N'''''' + @Leave_SessionFrom + '''''',N'''''' + @Leave_SessionTo + '''''','''''' + cast(@NumberOfDays as nvarchar(20)) + '''''',N''''''
		set @sql= @sql + @Reason + '''''',N'''''' + @LeaveStatus + '''''','''''' + cast(@Isdeleted as nvarchar(10)) +  '''''','''''' + cast(@IsBorrow as nvarchar(10)) +  '''''',N'''''' + @auEmpId + '''''',N'''''' + @YearSettings_Id + '''''',N'''''' + @intimationType + '''''', '''''' + ISNULL(@InformTo, '''') + '''''')''
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplicationMaster set Status=@LeaveStatus,IntimationType=@intimationType,Emp_Id=@auEmpId,CCMail=@CCMail where LeaveApplication_Id=@leaveApplicationId
END
else
BEGIN
set @sql= @sql + ''INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)''
		set @sql= @sql + ''VALUES('''''' + cast(@leaveApplicationId as nvarchar(20)) + '''''','''''' + cast(@EmployeeID as nvarchar(20)) + '''''','''''' + cast(@Leave_ApplicationDate as nvarchar(20)) + '''''',''''''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + '''''',N'''''' + @Type + '''''','''''' + cast(@Leave_FromDate as nvarchar(20))+ '''''',''''''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ '''''',N'''''' + @Leave_SessionFrom + '''''',N'''''' + @Leave_SessionTo + '''''','''''' + cast(@NumberOfDays as nvarchar(20)) + '''''',N''''''
		set @sql= @sql + @LeaveStatus + '''''','''''' + cast(@Isdeleted as nvarchar(10)) +  '''''','''''' + cast(@IsBorrow as nvarchar(10)) +  '''''',N'''''' + @auEmpId + '''''',N'''''' + @YearSettings_Id + '''''',N'''''' + @intimationType + '''''', '''''' + ISNULL(@InformTo, '''') + '''''')''
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplication set Reason=t2.Reason
		from TA_Tbl_LeaveApplicationMaster t2
		inner join TA_Tbl_LeaveApplication t1 on t2.LeaveApplication_Id=t1.LeaveApplication_Id
		UPDATE TA_Tbl_LeaveApplicationMaster set Status=@LeaveStatus,IntimationType=@intimationType,Emp_Id=@auEmpId,CCMail=@CCMail where LeaveApplication_Id=@leaveApplicationId
END
        SELECT LA.LeaveApplication_Id, LD.Id AS LevelId FROM TA_Tbl_LeaveApplication LA
        INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = LA.Employee_Id
		INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
        INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
        WHERE LA.LeaveApplication_Id = @leaveApplicationId
	end
	end
	--Remove the temporary tables here  
	drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplication]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Proc_TA_GetCompOffDays 10860,2
Description		:	Insert into Leave Appliacation for Employee
Tables Included	:	Ta_Tbl_LeaveApplication, TA_Tbl_ProcessedData and TA_Tbl_YearSetting, TA_Tbl_OverTimeStatus
Created By		:	Prabakaran
Created On		:	18-Feb-07
Modified By		:	A.K.T.MOORTHI
Modified On		:	23-JULY-2013
Description		:	Update The CompOff Quota In "TA_Tbl_OverTimeStatus" Table
Modified By		:   A.K.T.MOORTHI
Modified On		:   06-Aug-2014
Description		:	Remove The Date Convertion In Expaire Date Calculation
Modifed by Gopinath for removing the lines added for Globalweekoff days due to V1.5 release
--Proc_TA_InsertLeaveApplication  ''337'',''04/16/2014'',''1'',''Leave'',''04/18/2014'',''04/21/2014'',''First Session'',''Second Session'',4.0,''TEst Reason'',0,1,1,'''',0,''Intervening''
--Proc_TA_InsertLeaveApplication  '''','''','''',''????'','''','''',''?er?ewr??'',''???ewr?rewr'',1.0,''??er??''
exec Proc_TA_InsertLeaveApplication @EmployeeID=7,@Leave_ApplicationDate=''2019-07-03 00:00:00.000'',@LeaveType_id=1,@Type=N''Leave'',
@Leave_FromDate=''2019-07-01 00:00:00.000'',@Leave_ToDate=''2019-07-01 00:00:00.000'',
@Leave_SessionFrom=N''First half'',@Leave_SessionTo=N''Second half'',@NumberOfDays=1.00,
@Reason=N''tr'',@IsBorrow=0,@auEmpId=N''1'',@YearSettings_Id=N''2'',@LeaveStatus=N''Approved'',@SuccessiveYear=0,@Intervening =''''
*/
CREATE PROCEDURE [dbo].[Proc_TA_InsertLeaveApplication](
	@EmployeeID INT,
	@Leave_ApplicationDate DATETIME=null,
	@LeaveType_id INT,
	@Type NVARCHAR(20),
	@Leave_FromDate DATETIME,
	@Leave_ToDate DATETIME,
	@Leave_SessionFrom NVARCHAR(20),
	@Leave_SessionTo NVARCHAR(20),
	@NumberOfDays DECIMAL(8,2),
	@Reason NVARCHAR(250),
	@IsBorrow INT,
	@auEmpId NVARCHAR(50),
	@YearSettings_Id NVARCHAR(20),
	@LeaveStatus NVARCHAR(30),
	@SuccessiveYear INT,
	@Intervening char(5)
) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @LevelId INT
	declare @CountRecord INT
	declare @LeaveApplicationId INT
	DECLARE @Isdeleted BIT 
	set @Isdeleted= 0
	declare @del BIT 
	set @del= 0
	DECLARE @SQLQuery NVARCHAR(MAX) 
	set @SQLQuery= ''''
	SELECT @LevelId = LevelId FROM TA_Tbl_EmployeeLevel WHERE EmployeeId = @EmployeeID
	WHILE((SELECT id FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> '''')
	BEGIN 	
		IF((SELECT levelId FROM Ta_Tbl_levelDetails WHERE id = @LevelId) <> 1)
		BEGIN
			SELECT @LevelId = parentId FROM Ta_Tbl_levelDetails WHERE id = @LevelId
		END
		ELSE
		BEGIN
			BREAK
		END
	END
	SET @LevelId = @LevelId
	SELECT @CountRecord = count(Employee_Id) FROM TA_Tbl_Employee 
		WHERE Leave_Sanc_Authority = Reporting_To AND Employee_Id = @EmployeeID  
	IF(@LeaveStatus = '''' AND @CountRecord > 0)
	BEGIN
		SET @LeaveStatus = ''Forwarded''
	END
	ELSE IF(@LeaveStatus = '''' AND @CountRecord = 0)
	BEGIN
		SET @LeaveStatus = ''Pending''
	END	
	INSERT INTO TA_Tbl_LeaveApplication(Employee_Id, Leave_ApplicationDate, LeaveType_id, Type, Leave_FromDate, Leave_ToDate, Leave_SessionFrom, Leave_SessionTo, NumberOfDays, Reason, Status, IsDeleted, IsBorrow, Emp_Id, YearSettings_Id, CompanyId, Successiveyear,Intervening)
	VALUES(CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
	CAST(@LeaveType_id AS NVARCHAR(20)), @Type,CAST(@Leave_FromDate AS NVARCHAR(20)),
	CAST(@Leave_ToDate AS NVARCHAR(20)), @Leave_SessionFrom,@Leave_SessionTo,
	CAST(@NumberOfDays AS NVARCHAR(20)), @Reason,@LeaveStatus,CAST(@Isdeleted AS NVARCHAR(10)),
	CAST(@IsBorrow AS NVARCHAR(10)),@auEmpId,@YearSettings_Id,CAST(@LevelId AS NVARCHAR(20)),
	CAST(@SuccessiveYear AS NVARCHAR(20)),@Intervening)
	
	SET @LeaveApplicationId = IDENT_CURRENT(''TA_Tbl_LeaveApplication'')
	Declare @diff int
	declare @i int
	declare @fromdate datetime
	declare @Todate datetime
	declare @fromsession varchar(20)
	declare @tosession varchar(20)
	set @i=0
	set @fromdate=@Leave_FromDate 
	set @Todate=@Leave_ToDate	
	set @diff=(select DATEDIFF(d,@Leave_FromDate,@Leave_ToDate))
	if(@diff=0)
		begin
			insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
			CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),@Leave_SessionFrom , @Leave_SessionTo,@LeaveStatus,@Isdeleted) 
		END
	ELSE
		BEGIN			 
			WHILE @i<=@diff 
				BEGIN
					IF @fromdate=@Todate
						BEGIN
							IF(@Leave_SessionTo=''Second half'')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),''First half'' , ''Second half'',@LeaveStatus,@Isdeleted) 		
								end
							if(@Leave_SessionTo=''First half'')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Todate AS NVARCHAR(20)),CAST(@Leave_ToDate AS NVARCHAR(20)),''First half'' , ''First half'',@LeaveStatus,@Isdeleted) 		
								end
						end
					else if @fromdate=@Leave_FromDate 
						begin
							if(@Leave_SessionFrom=''Second half'')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),''Second half'' , ''Second half'',@LeaveStatus,@Isdeleted) 		
								end
							if(@Leave_SessionFrom=''First half'')
								begin
									insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(getdate() AS NVARCHAR(20)),
									CAST(@Leave_FromDate AS NVARCHAR(20)),CAST(@Leave_FromDate AS NVARCHAR(20)),''First half'' , ''Second half'',@LeaveStatus,@Isdeleted) 		
								end
							--end								
						end	
					else
						begin
							insert into TA_Tbl_LeaveApplicationExists values(@LeaveApplicationId,CAST(@EmployeeID AS NVARCHAR(20)),CAST(GETDATE() AS NVARCHAR(20)),
							CAST(@fromdate AS NVARCHAR(20)),CAST(@fromdate AS NVARCHAR(20)),''First half'' , ''Second half'',@LeaveStatus,@Isdeleted)
						end				
					set @fromdate=DATEADD(d,1,@fromdate)					
					set @i=@i+1					
				end
		end
	IF(@Type= ''Comp Off'')
	BEGIN
		DECLARE @CompOffId BIGINT 
		set @CompOffId= 0
		Declare @RemainingDays NUMERIC(18,1) 
		set @RemainingDays= 0.0
		DECLARE @TblRecord TABLE(Id INT IDENTITY(1, 1), CompOffId INT, Process BIT)
		UPDATE TA_Tbl_OverTimeStatus SET CompOffSatus = ''Expired''
		WHERE DateToExpired < GETDATE() AND
			ISNULL(CompOffSatus, ''Not Taken'') = ''Not Taken'' AND
			OverTimeStatus = ''Approved'' AND
			CompOffEligible = 1 AND
			Employee_Id = @EmployeeId
		INSERT INTO @TblRecord
			SELECT ExtraTime_Id, 0 FROM TA_Tbl_OverTimeStatus
			WHERE DateToExpired >= GETDATE() AND
				ISNULL(CompOffSatus, ''Not Taken'') = ''Not Taken'' AND
				OverTimeStatus = ''Approved'' AND
				CompOffEligible = 1 AND
				Employee_Id = @EmployeeId
			ORDER BY Date
		WHILE ((EXISTS(SELECT Process FROM @TblRecord WHERE Process = 0)) AND @NumberOfDays > 0)
		BEGIN
			SET @CompOffId = (SELECT TOP 1 CompOffId FROM @TblRecord WHERE Process = 0 ORDER BY Id)
			UPDATE TA_Tbl_OverTimeStatus SET
				@RemainingDays = RemainingDays,
				RemainingDays = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN (@RemainingDays - @NumberOfDays)
					WHEN (@RemainingDays <= @NumberOfDays) THEN 0.0 END),
				CompOffSatus = (CASE 
					WHEN (@RemainingDays > @NumberOfDays) THEN ''Not Taken''
					WHEN (@RemainingDays <= @NumberOfDays) THEN ''Taken'' END),
				LeaveApplicationId = ISNULL(LeaveApplicationId, '''') + '':'' + CAST(@LeaveApplicationId AS VARCHAR(20))
			WHERE ExtraTime_Id = @CompOffId
			SET @NumberOfDays = (@NumberOfDays - @RemainingDays)
			UPDATE @TblRecord SET Process = 1 WHERE CompOffId = @CompOffId
		END
	END
	declare @LeaveID as int
	set @LeaveID=(select LevelId from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID and EffectiveDate in (select MAX(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeID))
	SELECT @LeaveApplicationId AS [LeaveApplicationId],@LeaveStatus as [LeaveApplicationStatus],@LeaveID as LevelID
	If ((@LeaveStatus=''Forwarded'' or @LeaveStatus=''Approved'') and @EmployeeID!=@auEmpId)
	begin
		Execute [Proc_TA_UpdateLeaveApplicationConversation] @LeaveApplicationId,@LeaveStatus,@auEmpId,''Ok'',@auEmpId
	End
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEncashmentDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEncashmentDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_InsertEncashmentDetails
Description	:	Insert Records in TA_Tbl_Encashment
Tables Included	:	TA_Tbl_Encashment
Created By	:	Prabakaran
Created On	:	28-Nov-07
Modified By	:
Modified On	:
*/
CREATE procedure [dbo].[Proc_TA_InsertEncashmentDetails]
@Employee_Id bigint,
@LeaveTypeId bigint,
@NumberOfDays decimal(18,1),
@Reason nvarchar(50)
as
declare @YearSettingId bigint
set @YearSettingId=(select YearSettings_Id from TA_Tbl_YearSetting Where Isactive=1)
begin
insert into TA_Tbl_Encashment(EmployeeId,LeaveTypeId,NumberOfDays,YearSettingId,Reason,Isdeleted) 
values(@Employee_Id,@LeaveTypeId,@NumberOfDays,@YearSettingId,@Reason,0)
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAllAuditColumnNames]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAllAuditColumnNames]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAllAuditColumnNames] 
	-- Add the parameters for the stored procedure here
	@tableId decimal
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT * FROM TA_Tbl_AuditField WHERE TableID = @tableId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectAdditionalWeekOffLevelRights] 
	@AdditionalWeekOffId int
AS
BEGIN
	SET NOCOUNT ON;
	select WL.LevelId,Addl_WeekOff_Day,Addl_WeekOff_Week from TA_Tbl_Additional_WeeklyOff_Levels WL 
	inner join TA_Tbl_Additional_WeeklyOff W
	on WL.Addl_WeeklyOff_Id=W.Addl_WeeklyOff_Id where WL.Addl_WeeklyOff_Id= @AdditionalWeekOffId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensationbyID]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompensationbyID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- select * from ta_tbl_compensation where Employee_id=''3232'' and FromDate=''09/18/2011'' 
-- Proc_TA_SelectCompensationbyID 358
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompensationbyID]   
	@CompOffID bigint
AS    
BEGIN    
	SET NOCOUNT ON;    
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat()	
	begin    
		select	C.ExtraTime_Id ''Compensation_Id'',
				E.Employee_Code_Id as ''Employee_Id'',C.Employee_Id as E_Employee_Id,
				isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as Employee_FirstName,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ApplicationDate,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.ApplicationDate, @dateFormat) 
				end AS ApplicationDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.Date,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.Date, @dateFormat) 
				end AS FromDate ,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.Date,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.Date, @dateFormat) 
				end AS ToDate,
				case C.NoOfDays when ''1.0'' then ''FullDay'' when ''0.5'' then ''HalfDay'' 
				end as Type,
				C.Reason,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.DateToExpired,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.DateToExpired, @dateFormat) 
				end AS ExpiryDate,
				C.NoOfDays as ''Quota'',
				case	when C.DateToExpired >= CONVERT(DATETIME,cast(getdate() as nvarchar(50)),102) then
						0  else 1 
				end as Expiredstatus,
				case	when C.InTime<>''00:00'' then	case	when (@TimeFormat) =''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.InTime,0)), 114) 
															else	InTime
													end 
						else ''''
				end	InTime,
				case	when C.OutTime<>''00:00'' then case	when (@TimeFormat) =''hh:mm'' then  CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.OutTime,0)), 114)
															else	OutTime
													 end 
						else '''' 
				end	OutTime,
				C.HrsExtra as ''WorkedHours'',
				C.DaysWorked as ''DayWorked'',
				C.OverTimeStatus as Comp_Status,
				C.Process_RecID
		from TA_Tbl_OverTimeStatus C
		inner join ta_tbl_Employee E on C.Employee_Id=E.Employee_Id 
		where	C.ExtraTime_Id=@CompOffID order by C.ExtraTime_Id desc
	end    
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompensation]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompensation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- select * from ta_tbl_compensation where Employee_id=''3232'' and FromDate=''09/18/2011'' 
-- Proc_TA_SelectCompensation '''',''788'',''05/01/2017'',73
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompensation]     
	@EmployeeName varchar(20),    
	@Employee_Id varchar(20),
	@FromDate varchar(20),
	@CompOffID bigint,
	@Remarks nvarchar(250)
AS    
BEGIN    
	SET NOCOUNT ON;    
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat()	
	-- Insert statements for procedure here    
	if(@EmployeeName ='''')    
	begin    
		select	C.Compensation_Id,
				C.Employee_Id,
				isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as Employee_FirstName,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ApplicationDate,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.ApplicationDate, @dateFormat) 
				end AS ApplicationDate,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.FromDate,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.FromDate, @dateFormat) 
				end AS FromDate ,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ToDate,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.ToDate, @dateFormat) 
				end AS ToDate,
				case C.Type when ''1.0'' then ''FullDay'' when ''0.5'' then ''HalfDay'' 
				end as Type,
				C.Remarks,
				case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, C.ExpiredDate,@dateFormat),'' '',''-'') 
						else CONVERT(VARCHAR, C.ExpiredDate, @dateFormat) 
				end AS ExpiryDate,
				C.Quota,
				case	when C.ExpiredDate >= CONVERT(DATETIME,cast(getdate() as nvarchar(50)),102) then
						0  else 1 
				end as Expiredstatus,
				case	when C.InTime<>''00:00'' then	case	when (@TimeFormat) =''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.InTime,0)), 114) 
															else	SUBSTRING(C.InTime,13,5)+'' '' + SUBSTRING(C.InTime,18,2)
													end 
						else ''''
				end	InTime,
				case	when C.OutTime<>''00:00'' then case	when (@TimeFormat) =''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,C.OutTime,0)), 114) 
															else	SUBSTRING(C.InTime,13,5)+'' '' + SUBSTRING(C.OutTime,18,2) 
													 end 
						else '''' 
				end	OutTime,
				C.WorkedHours,
				C.DayWorked,
				C.Status as Comp_Status,
				C.Comments 
		from TA_Tbl_Compensation C
		inner join ta_tbl_Employee E on C.Employee_Id=E.Employee_Code_Id 
		where	C.Compensation_Id=@CompOffID	order by Compensation_Id desc
	end    
	else    
	begin 
		if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1  and Compensation_Id=@CompOffID)
		begin
			if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1 and status <> ''Expired'' and Compensation_Id=@CompOffID)
			begin
				if exists(select * from TA_Tbl_Compensation where Employee_Id=@Employee_Id and Isdeleted <>1 and status <> ''Availed'' and Compensation_Id=@CompOffID)
				begin
					--delete from TA_Tbl_Compensation 
					UPDATE TA_Tbl_Compensation SET Isdeleted=1,status=''Cancelled'',Remarks=@Remarks
					WHERE Employee_Id=@Employee_Id and Isdeleted <>1 and Compensation_Id=@CompOffID
					select ''1''
				end
				else
				begin
					select ''Availed''
				end
			end
			else
			begin
				select ''Expired''
			end
		end
		else
		begin
			select''2''
		end
	end   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOrgSettings]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOrgSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptOrgSettings] 
AS
BEGIN
	select id,ParentID,Name from ta_tbl_leveldetails where isdeleted=0 order by parentid,Name
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGAttendance]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--
-- Proc_TA_RptGAttendance '''','''',''04/22/2005'',''04/22/2008'','''','''','''',''''
--Proc_TA_RptGAttendance '''','''',''01/01/2007'',''12/12/2009'','''',0,0,0,''SuperAdmin'',''1'',''''
--
CREATE PROCEDURE [dbo].[Proc_TA_RptGAttendance]
(
@EmployeeID VarChar(50), 
@LevelID VarChar(8000),
@FromDate VarChar(50), 
@ToDate VarChar(50), 
@EmployeeName varchar(50),
@shift int,
@EmployeeCategory int,
@EmployeeType int,
@UserGroupName varchar(250),
@GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @EmpAutoID int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	Declare @SelectSQL As Varchar(8000)
	Set @EmployeeName = @EmployeeName + ''%''
	Set @SelectSQL = '' ''  
	Set @SelectSQL = @SelectSQL + ''SELECT PD.Process_Rec_ID,ED.Employee_Code_Id AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''
    	Set @SelectSQL = @SelectSQL + ''replace(T.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''
	set @SelectSQL = @SelectSQL + ''replace(L.name,''''&amp;'''',''''&'''')  AS [Level Name],sh.Shift_StartTime,replace(sh.shift_shortName,''''&amp;'''',''''&'''') as shift_shortName, ''	 
	Set @SelectSQL = @SelectSQL + ''CONVERT(varchar,Date ,101) AS Date, InTime,LateIn as LateBy,LateInMins,PD.LateEntryReason,DATENAME(Month,[Date]) AS ''''Month'''' FROM TA_Tbl_Employee ED  ''
	Set @SelectSQL = @SelectSQL + ''INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + ''INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id ''
	Set @SelectSQL = @SelectSQL + ''INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + ''INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId ''
	SET @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''
	set @SelectSQL = @SelectSQL + '' inner join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
    set @SelectSQL = @SelectSQL + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
    set @SelectSQL = @SelectSQL + '' inner join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
    set @SelectSQL = @SelectSQL + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	--Set @SelectSQL = @SelectSQL + ''INNER JOIN Ta_Tbl_levelDetails L ON ED.LevelId = L.Id  ''	
	Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_ProcessedData PD ON ED.SwipeCardNo = PD.Employee_Code_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id ''
    Set @SelectSQL = @SelectSQL + '' Where ''
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @SelectSQL = @SelectSQL + '' TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' AND ''
	end
	if(@shift<>0)
	begin
		Set @SelectSQL = @SelectSQL + '' PD.shift_id= ''+  cast (@shift as nvarchar(50))  + '' AND ''
	end
	Set @SelectSQL = @SelectSQL + '' ( ED.Employee_Status = 1 or ( ED.Employee_Status = 0 and  convert(varchar(11), ED.InActiveDate,102) >= convert(varchar(11),getdate(),102))) AND (ED.Isdeleted = 0) AND (ED.report_exclude = 0)''
	Set @SelectSQL = @SelectSQL + '' and ED.Employee_FirstName + '''' '''' + isnull(ED.Employee_LastName,'''''''') like '''''' + @EmployeeName + '''''' ''
	Set @SelectSQL = @SelectSQL + '' AND Lev.EffectiveDate=(select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId=ED.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	Set @SelectSQL = @SelectSQL + '' AND EDesig.EffectiveDate=(select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=ED.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''	
	set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
    set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Employee_code_Id = '''''' + @EmployeeID + '''''' ''
	End
	if(@isReportingto > 0)
	BEGIN
		set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
		If Not (@EmpSwipeCard = '''')  
			 Begin  
			  Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			 End
	If (@EmployeeCategory <> 0)
		begin
			set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeCategory.CategoryId = '' +cast(@EmployeeCategory as nvarchar(8))
		end
	If (@EmployeeType <> 0)
		begin
			set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeType.TypeId = '' +cast(@EmployeeType as nvarchar(8))
		end
	If (@FromDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Date >= '''''' + @FromDate + '''''' ''
	End
	If (@ToDate <> '''')
	Begin
		Set @SelectSQL = @SelectSQL + ''And PD.Date <= '''''' + @ToDate + '''''' ''
	End
	if not(@LevelID='''' or @LevelID=''0'')
		Begin
			set @SelectSQL = @SelectSQL + '' and (Lev.LevelId IN ('' + @LevelID + '')) ''
		End
	set @SelectSQL = @SelectSQL + '' order by ED.Employee_Code_Id,pd.Date , pd.Intime''
	exec (@SelectSQL)
	End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGetEmailLog]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGetEmailLog]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 14-02-2013
-- Description:	Get the Email Log Details
-- [dbo].[Proc_TA_RptGetEmailLog] 34,1,''2013/01/01'',''2013/01/16'',''0''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptGetEmailLog]
	-- Add the parameters for the stored procedure here
	@Reportid INT,
	@Frequency INT,
	@Fromdate DATETIME,
	@Todate DATETIME,
	@CreatedBy BIGINT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	Create table #TempScheduleIDs(Scheduleid bigint,row int) 	
	CREATE TABLE #TempMailIds(Scheduleid BIGINT,Tomail NVARCHAR(max),CCmail NVARCHAR(max))		
	Insert into #TempScheduleIDs select ScheduleId,ROW_NUMBER()over(order by scheduleid) from TA_Tbl_EmailSchedule where IsDeleted=1
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	Declare @CountIds int
	Declare @i int
	DECLARE @ToEmailList VARCHAR(8000)	
	DECLARE @CCEmailList VARCHAR(8000)	
	Declare @ScheduleId bigint
	set @i=1
	set @CountIds=(select COUNT(scheduleid)from #TempScheduleIDs)
	while @CountIds>0
		begin		
			select @ScheduleId=scheduleid from #TempScheduleIDs where row=@i			
			SELECT @ToEmailList = COALESCE(@ToEmailList + ''; '', '''') + CAST(EmailID AS VARCHAR)
			FROM   TA_tbl_MailIdsForTriggeringEmail
			WHERE  ScheduleId = @ScheduleId and MailType = ''To''				
			SELECT @CCEmailList = COALESCE(@CCEmailList + ''; '', '''') + CAST(EmailID AS VARCHAR)
			FROM   TA_tbl_MailIdsForTriggeringEmail
			WHERE  ScheduleId = @ScheduleId and MailType = ''CC''	
			set @CCEmailList=SUBSTRING(@CCEmailList,1,LEN(@CCEmailList))
			set @ToEmailList=SUBSTRING(@ToEmailList,1,LEN(@ToEmailList))
			insert into #TempMailIds values(@ScheduleId,@ToEmailList,@CCEmailList)
			set @ToEmailList=Null
			set @CCEmailList=Null			
			set @i=@i+1			
			set @CountIds=@CountIds-1
		end	
	--select * from #TempMailIds 
    -- Insert statements for procedure here    
    DECLARE @SQLQUERY NVARCHAR(MAX)
    SET @SQLQUERY	=	''SELECT 
						case when ''+cast(@dateFormat as varchar(100))+''=106 then
											      REPLACE(CONVERT(VARCHAR, Sentdate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
											 else CONVERT(VARCHAR, Sentdate, ''+cast(@dateFormat as varchar(100))+'')
											end as ScheduleDate,
						ScheduleName,
						case when (ESS.Status<> 0 and ESS.Status is not null and ESS.Status<>'''''''') then 
										case when ''+cast(@dateFormat as varchar(100))+''=106 then
											      REPLACE(CONVERT(VARCHAR, Sentdate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
											 else CONVERT(VARCHAR, Sentdate, ''+cast(@dateFormat as varchar(100))+'')
											end 
							 else '''' '''' end as actual,
						Employee_FirstName +'''' ''''+ Employee_LastName AS CreatedBy,
						case when ''+cast(@dateFormat as varchar(100))+''=106 then
								  REPLACE(CONVERT(VARCHAR, DurationFrom,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
							 else CONVERT(VARCHAR, DurationFrom, ''+cast(@dateFormat as varchar(100))+'')							 
							 end as DurationFrom,
						case when ''+cast(@dateFormat as varchar(100))+''=106 then
								  REPLACE(CONVERT(VARCHAR, DurationTo,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
							 else CONVERT(VARCHAR, DurationTo, ''+cast(@dateFormat as varchar(100))+'')							 
							 end as DurationTo,
						Tomail,
						CCMail,
						case when ESS.Status=0 then ''''Pending'''' when ESS.Status=1 then ''''Send'''' end AS STATUS 
						FROM TA_Tbl_EmailSchedule ES inner join #TempMailIds MT ON Es.ScheduleId=MT.ScheduleId 
						LEFT OUTER JOIN TA_tbl_EmailScheduleStatus ESS ON ES.ScheduleId=ESS.ScheduleId 
						INNER JOIN TA_Tbl_Employee E ON ES.EmployeeId=E.Employee_Id 
						LEFT OUTER JOIN Ta_tbl_EmailReportNotSendedDetails ERNS on ES.ScheduleId=ERNS.Id and ERNS.AraisedFrom=''''Email''''''	
	SET @SQLQUERY	=	@SQLQUERY + '' WHERE 1=1 ''	
	IF @Reportid is not null and @Reportid<>'''' AND @Reportid<>0
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + '' AND ES.Reportid=''+cast (@Reportid as nvarchar(50))+''''
		END	
	IF @Frequency = 1
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + '' AND ES.Frequency=''''Daily''''''
		END	
	IF @Frequency = 2
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + '' AND ES.Frequency=''''Weekly''''''
		END	
	IF @Frequency = 3
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + '' AND ES.Frequency=''''Monthly''''''
		END	
	IF @CreatedBy IS NOT NULL AND @CreatedBy<>''''
		BEGIN
			SET @SQLQUERY	=	@SQLQUERY + '' AND E.Employee_id=''+@CreatedBy+'''' 
		END
	IF ((@Fromdate IS NOT NULL AND @Fromdate<>'''') AND (@Todate IS NOT NULL AND @Todate <>''''))
		BEGIN
			set @sqlQuery = @sqlQuery + '' and((sentDate >= CONVERT(DATETIME, '''''' + cast(@Fromdate as nvarchar(11)) + '''''', 102) and sentDate <= CONVERT(DATETIME, '''''' + cast(@toDate as nvarchar(11)) + '''''', 102)))''
		END
	EXECUTE(@SQLQUERY)
	DROP TABLE #TempMailIds 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAbsenteesDetail]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAbsenteesDetail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_RptAbsenteesDetail]
	(@EmployeeID VarChar(50), @CompanyID VarChar(50), @RegionID VarChar(50), @BranchID VarChar(50), @DeptID VarChar(50), 
@SectionID VarChar(50), @FromDate VarChar(50), @ToDate VarChar(50), @LeaveType VarChar(50), @EmployeeName varchar(50))
AS
BEGIN
	Create Table #TempReportTable
	(
	 ID int identity (1,1),
	 CardNo VarChar(255),	
	 EmployeeName Varchar(225),
	 Department Varchar(255),
	 Designation VarChar(255),
	 Section Varchar(225),
	 Company_Logo image,
	 Region Varchar(250),
	 AbsDate varchar(50)
	)
	Declare @AutoID as int
	Declare @totRec as int
	Declare @TestDate as Varchar(50)
	Set @TestDate = @FromDate
	Set @AutoID=0
	While (cast(@TestDate as datetime) <= cast(@ToDate as DateTime))
	Begin
	set @totRec = 0
	Select @totRec=Count(*)  from TA_Tbl_Holiday where Convert (varchar,Holiday_FromDate,101) >= @TestDate And Convert 
(varchar,Holiday_ToDate,101) <= @TestDate and Isdeleted = 1
	if @totRec = 0
	Begin
	Declare @SelectSQL As Varchar(4000)
	Set @SelectSQL = '' ''
	Set @SelectSQL = @SelectSQL + ''SELECT ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + ''case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName 
as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
    Set @SelectSQL = @SelectSQL + ''D.Department_Name AS Department, T.TitleName AS Designation, S.Section_Name AS Section, ''
    Set @SelectSQL = @SelectSQL + ''C.Company_Logo AS Logo, B.Branch_Name As Region,'''''' +  @TestDate + '''''' FROM 
TA_Tbl_Employee ED INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Department D ON ED.Dept_Id = D.Department_Id INNER JOIN TA_Tbl_Title T ON 
ED.Designation_Id = T.TitleId INNER JOIN ''
    Set @SelectSQL = @SelectSQL + ''TA_Tbl_Section S ON ED.Section_Id = S.Section_Id INNER JOIN TA_Tbl_CompanyDetails C ON 
ED.Company_Id = C.Company_Id  INNER JOIN TA_Tbl_Region R ON ED.Region_Id = R.Region_Id inner join TA_Tbl_Branch B on 
B.Branch_Id = ED.Branch_Id Where ''
	Set @SelectSQL = @SelectSQL + ''ED.IsDeleted = ''''1'''' ''
	If Not (@EmployeeId = '''' Or @EmployeeId = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmployeeId + '''''' ''
	End
	If Not (@CompanyID = '''' Or @CompanyID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Company_Id = '''''' + @CompanyID + '''''' ''
	End
	If Not (@RegionID = '''' Or @RegionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Region_Id = '''''' + @RegionID + '''''' ''
	End
	If Not (@BranchID = '''' Or @BranchID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Branch_Id = '''''' + @BranchID + '''''' ''
	End
	If Not (@DeptID = '''' Or @DeptID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Dept_Id = '''''' + @DeptID + '''''' ''
	End
	If Not (@SectionID = '''' Or @SectionID = ''0'')
	Begin
		Set @SelectSQL = @SelectSQL + ''And ED.Section_Id = '''''' + @SectionID + '''''' ''
	End
--	If Not (@LeaveType = '''' Or @LeaveType = ''0'')
--	Begin
--	Set @SelectSQL = @SelectSQL + ''And LA.LeaveType_id = '''''' + @LeaveType + '''''' ''	
--	end
	Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo Not In (SELECT Clk_EmpId FROM TA_Tbl_ClockDetails Where Convert 
(varchar,Clk_InDate,101) = '''''' + @TestDate + '''''') ''	
	Insert InTo #TempReportTable
	(CardNo, EmployeeName, Department, Designation, Section, Company_Logo, Region, AbsDate)		
	Exec (@SelectSQL)
	End	
	Set @TestDate = Convert (varchar,Dateadd(dd,1,@TestDate),101)
	End
	--Return
	Set @EmployeeName = @EmployeeName + ''%''
	Select * From #TempReportTable where EmployeeName like @EmployeeName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Test]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave_Test]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		senthil
-- ALTER  date: 03-Aug-07
-- Description:	Leave Report
-- Modified By : Sasireka.M
-- Modified On : 06.03.09
-- Description : For Monthly Leave Policy
--Modified By  : A.Amsaveni on 20.05.2013
--Description  : Display detail based on unplanned condition also. 
-- Proc_TA_RptLeave ''04/01/2009'',''01/31/2010'','''','''','''','''',''All'',''All'','''','''',''SuperAdmin'',1,'''',''0'',''1''
-- Proc_TA_RptLeave ''01/26/2010'',''01/26/2010'','''','''','''','''',''All'',''All'','''','''',''lll'',1,'''',''0'',''1''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptLeave_Test]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@Unplanned int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		declare @sqlResHoliday as varchar(8000)
		declare @sqlESIDays as varchar(8000)
		declare @sqlCompDays as varchar(8000)
		declare @sqlLOPDays as varchar(8000)
		declare @sqlMonthlyLOP as varchar(8000)
		set @sqlQuery = ''''		
		set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,''
		set @sqlQuery = @sqlQuery + '' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name ,dbo.TA_Tbl_LeaveApplication.IntimationType''
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' where dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		if (@LeaveStatus=''Canceled'')
		begin
		set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) ''
		end
		set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlQuery = @sqlQuery + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  --+ '' AND (TA_Tbl_Employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or TA_Tbl_Employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''')''
		end		
		if not(@EmployeeName='''')
		begin
			set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		If Not (@EmpSwipeCard = '''')  
		 Begin  
		  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		 End 
		if not (@empId='''')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
		if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
if not(@LeaveStatus=''All'' or @LeaveStatus=''Canceled'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
			set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
			end	
		END
		ELSE
			BEGIN
			   set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
if(@Unplanned!=0)
		begin
		set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
--Restricted Holiday
set @sqlResHoliday=''''
if (@LeaveType=''All'')
begin
set @sqlResHoliday='' UNION ''
end		
		set @sqlResHoliday = @sqlResHoliday + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,dbo.ta_tbl_Holiday.Holiday_Description as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, ''
		set @sqlResHoliday = @sqlResHoliday + '' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
		set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlResHoliday = @sqlResHoliday + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, dbo.TA_Tbl_LeaveApplication.IntimationType''
		set @sqlResHoliday = @sqlResHoliday + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlResHoliday = @sqlResHoliday + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlResHoliday = @sqlResHoliday + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlResHoliday = @sqlResHoliday + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlResHoliday = @sqlResHoliday + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlResHoliday = @sqlResHoliday + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlResHoliday = @sqlResHoliday + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlResHoliday = @sqlResHoliday + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlResHoliday = @sqlResHoliday + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		set @sqlResHoliday = @sqlResHoliday + '' And dbo.ta_tbl_Holiday.Holiday_Type=''''Y'''' ''
		set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.Type=''''Restricted Holiday'''')''
		if(@Unplanned!=0)
		begin
		set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
		if (@LeaveStatus=''Canceled'')
		begin
		set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) ''
		end
		set @sqlResHoliday = @sqlResHoliday + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlResHoliday = @sqlResHoliday + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlResHoliday = @sqlResHoliday + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
		if not(@EmployeeName='''')
		begin
			set @sqlResHoliday = @sqlResHoliday + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		If Not (@EmpSwipeCard = '''')  
		 Begin  
			Set @sqlResHoliday = @sqlResHoliday + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		 End 
		if not (@empId='''')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
		if(@employeeCategory<>0)
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_EmployeeCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_EmployeeType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
if (@LeaveType=''Restricted Holiday'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  ''
		end
if not(@LeaveStatus=''All'' or @LeaveStatus=''Canceled'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
			set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlResHoliday = @sqlResHoliday + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
			end	
		END
		ELSE
			BEGIN
			   set @sqlResHoliday = @sqlResHoliday + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
--exec(@sqlResHoliday)
-- ESI Leaves
set @sqlESIDays=''''
if (@LeaveType=''All'')
begin
set @sqlESIDays='' UNION ''
end			
		set @sqlESIDays = @sqlESIDays + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''''ESI'''' as leavetype, dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,''
		set @sqlESIDays = @sqlESIDays + '' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
		set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlESIDays = @sqlESIDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, dbo.TA_Tbl_LeaveApplication.IntimationType''
		set @sqlESIDays = @sqlESIDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlESIDays = @sqlESIDays + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlESIDays = @sqlESIDays + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlESIDays = @sqlESIDays + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlESIDays = @sqlESIDays + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlESIDays = @sqlESIDays + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlESIDays = @sqlESIDays + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlESIDays = @sqlESIDays + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlESIDays = @sqlESIDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		if (@LeaveStatus=''Canceled'')
		begin
		set @sqlESIDays = @sqlESIDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) ''
		end
		set @sqlESIDays = @sqlESIDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlESIDays = @sqlESIDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
		begin
			set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''ESI''''''
		end
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlESIDays = @sqlESIDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
		if not(@EmployeeName='''')
		begin
			set @sqlESIDays = @sqlESIDays + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlESIDays = @sqlESIDays + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End 
		if not (@empId='''')
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
		if(@employeeCategory<>0)
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_EmployeeCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_EmployeeType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveStatus=''All'' or @LeaveStatus=''Canceled'')
		begin
			set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
			set @sqlESIDays = @sqlESIDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		end
       if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlESIDays = @sqlESIDays + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
			end	
		END
		ELSE
			BEGIN
			   set @sqlESIDays = @sqlESIDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
if(@Unplanned!=0)
		begin
		set @sqlESIDays = @sqlESIDays + '' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
--exec(@sqlESIDays)
-- Comp Off Leaves
set @sqlCompDays=''''
if (@LeaveType=''All'')
begin
set @sqlCompDays='' UNION ''
end			
		set @sqlCompDays = @sqlCompDays + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''''Comp Off'''' as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,''
		set @sqlCompDays = @sqlCompDays + '' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
		set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlCompDays = @sqlCompDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, dbo.TA_Tbl_LeaveApplication.IntimationType''
		set @sqlCompDays = @sqlCompDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlCompDays = @sqlCompDays + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlCompDays = @sqlCompDays + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlCompDays = @sqlCompDays + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlCompDays = @sqlCompDays + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlCompDays = @sqlCompDays + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlCompDays = @sqlCompDays + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlCompDays = @sqlCompDays + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlCompDays = @sqlCompDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		if (@LeaveStatus=''Canceled'')
		begin
		set @sqlCompDays = @sqlCompDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) ''
		end
		set @sqlCompDays = @sqlCompDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlCompDays = @sqlCompDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
		begin
			set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''Comp Off''''''
		end
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlCompDays = @sqlCompDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
		if not(@EmployeeName='''')
		begin
			set @sqlCompDays = @sqlCompDays + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if not (@empId='''')
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlCompDays = @sqlCompDays + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End 
		if(@employeeCategory<>0)
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_EmployeeCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_EmployeeType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveStatus=''All'' or @LeaveStatus=''Canceled'')
		begin
			set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
			set @sqlCompDays = @sqlCompDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		end
      if(@EmpAutoId = 0)
	   BEGIN
			if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlCompDays = @sqlCompDays + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
			end	
		END
		ELSE
			BEGIN
			   set @sqlCompDays = @sqlCompDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
if(@Unplanned!=0)
		begin
		set @sqlCompDays = @sqlCompDays + '' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
--LOP Days
set @sqlLOPDays = ''''
if (@LeaveType=''All'')
begin
set @sqlLOPDays='' UNION ''
end				
		set @sqlLOPDays = @sqlLOPDays + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
		set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.ta_tbl_leavetype.leavetype + ''''-'''' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason,''
		set @sqlLOPDays = @sqlLOPDays + '' Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
		set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
		set @sqlLOPDays = @sqlLOPDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, dbo.TA_Tbl_LeaveApplication.IntimationType''
		set @sqlLOPDays = @sqlLOPDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
		set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
		set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlLOPDays = @sqlLOPDays + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @sqlLOPDays = @sqlLOPDays + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
		set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlLOPDays = @sqlLOPDays + '' where (dbo.TA_Tbl_LeaveApplication.Type=''''LOP'''' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
		if (@LeaveStatus=''Canceled'')
		begin
		set @sqlLOPDays = @sqlLOPDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=1) ''
		end
		set @sqlLOPDays = @sqlLOPDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
		set @sqlLOPDays = @sqlLOPDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlLOPDays = @sqlLOPDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
		if not(@EmployeeName='''')
		begin
			set @sqlLOPDays = @sqlLOPDays + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if not (@empId='''')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlLOPDays = @sqlLOPDays + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End 
		if(@employeeCategory<>0)
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_EmployeeCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
		if(@employeeType<>0)
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_EmployeeType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
if not(@LeaveStatus=''All'' or @LeaveStatus=''Canceled'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
			set @sqlLOPDays = @sqlLOPDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
		end
       if(@EmpAutoId = 0)
	   BEGIN
		if not(@LevelID='''' or @LevelID=''0'')
			begin
				set @sqlLOPDays = @sqlLOPDays + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''
			end	
		END
		ELSE
			BEGIN
			   set @sqlLOPDays = @sqlLOPDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
		if(@Unplanned!=0)
		begin
		set @sqlLOPDays = @sqlLOPDays + '' And (dbo.TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
create table #EmpLeave(Employee_Id varchar(15),
applicationDate datetime,
fromDate datetime,
todate datetime,
NumberOfDays decimal(18,1),
leavetype varchar(100),
Leave_SessionFrom varchar(100),
Leave_SessionTo varchar(100),
Reason varchar(1050),
status varchar(50),
Remarks varchar(1050),
TitleName varchar(500),
empname varchar(500),
[name] varchar(500),
IntimationType varchar(200),
)
if (@LeaveType=''All'')
	begin
insert into #EmpLeave exec(@sqlQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
	end
if (@LeaveType=''Restricted Holiday'')
	begin
	insert into #EmpLeave exec(@sqlResHoliday)
	end
if (@LeaveType=''Comp Off'')
	begin
	insert into #EmpLeave exec(@sqlCompDays)
	end
if (@LeaveType=''ESI'')
	begin
	insert into #EmpLeave exec(@sqlESIDays)
	end
if (@LeaveType=''LOP'')
	begin
	insert into #EmpLeave exec(@sqlLOPDays)
	end
else if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''Comp Off'' or @LeaveType=''ESI'' or @LeaveType=''LOP'')
	begin
	insert into #EmpLeave exec(@sqlQuery)
	end
	select * from #EmpLeave order by Employee_Id,fromDate asc
drop table #EmpLeave
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getLevels]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_getLevels]
 AS
Begin
	select *,1 as flag into #tempLevels from ta_tbl_level where isdeleted=0 order by parentLevelid
	update #tempLevels set flag=0 from #tempLevels
	inner join ta_tbl_leveldetails LD  on LD.levelId = #tempLevels.levelID and LD.isDeleted=0
	update #tempLevels set flag=0 from #tempLevels
	inner join ta_tbl_level L on L.parentLevelID = #tempLevels.levelID and L.isDeleted=0
	select * from #tempLevels
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelNameUpdate]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLevelNameUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLevelNameUpdate  
Description : check level name while update
Tables Included : Ta_Tbl_levelDetails  
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLevelNameUpdate]
(
@parentId int,
@LevelId int,
@Id int,
@LevelName varchar(50)
)
AS
SELECT COUNT(*) AS Expr1
FROM   Ta_Tbl_levelDetails
WHERE  parentId=@parentId and name = @LevelName and id!= @Id
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLevelName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLevelName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckLevelName  
Description : check level name
Tables Included : Ta_Tbl_levelDetails  
Created By : Senthil Kumar NP  
Created On : 28-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckLevelName]
(
@parentId int,
@LevelId int,
@LevelName varchar(50)
)
AS
Begin
	SELECT COUNT(*) AS Expr1
	FROM   Ta_Tbl_levelDetails
	WHERE  parentID=@parentId and levelId =@LevelId AND replace(name,'' '','''') = replace(@LevelName,'' '','''')
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLOPLeaveTypeDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLOPLeaveTypeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name     :    Proc_TA_GetLOPLeaveTypeDetails    
Description     :    LOP Details from TA_Tbl_LeavePolicyDetails
Tables Included :    TA_Tbl_LeavePolicyDetails and TA_Tbl_Emp_LeavePolicy  
Created By     :    Prabakaran    
Created On     :    20-Nov-07    
Modified By     :    
Modified On     :    
Proc_TA_GetLOPLeaveTypeDetails 56,'''',''''
*/    
CREATE   PROCEDURE [dbo].[Proc_TA_GetLOPLeaveTypeDetails]
@EmployeeId bigint ,
@LeaveFromDate nvarchar(50),
@LeaveToDate nvarchar(50)  
as    
begin
    SET NOCOUNT ON;
    select distinct lt.LeaveType_Id,lt.LeaveType from TA_Tbl_LeavePolicyDetails lpd
    inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
    inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lpd.LeaveType_Id  
    where elp.EmployeeId=@EmployeeId
    and lpd.LossOfPay=1
    and elp.Isdeleted=0
    --and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
    and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
    inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
    where
    --TA_Tbl_YearSetting.IsActive=1 and
    TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportDataCentena]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportDataCentena]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ExportDataCentena]
AS
BEGIN
	declare @StartDate as datetime
	declare @EndDate as datetime
	set @EndDate = convert(varchar(10),getdate(),101)
	set @StartDate = dateadd(day, -6, @EndDate)
	insert into TA_Tbl_ExportDataCentena
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id, 
	''AB'' as type ,count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,''Absent'') as remarks
	from ta_tbl_processedData 
	where attendance =''Absent'' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
	union all
--Sick Leave
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id, 
	''SL'' as type ,count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,''SL'') as remarks
	from ta_tbl_processedData 
	where LeaveCode =''SL'' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
	union all
-- Annual Leave
	select CONVERT(VARCHAR(11),getdate(),113) as ImportDate, employee_code_id,
	''AL'' as type , count(employee_code_id)as days,	
	dbo.Func_TA_GetRemarks(employee_code_id,@StartDate,@EndDate,''AL'') as remarks
	from ta_tbl_processedData 
	where LeaveCode =''AL'' and (date >= @StartDate and date <= @EndDate)
	group by employee_code_id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualODEntryById]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualODEntryById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_GetManualODEntryById] 121
--select CONVERT(varchar,getdate(),101)
-- Modified by Gopinath on 11 feb 2014 for Datetime conversion
CREATE PROCEDURE [dbo].[Proc_TA_GetManualODEntryById]
	(@MID as int)
AS
	DECLARE @Isdel int
	SET @Isdel=0
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	select M.ManualTimeEntry_Id,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_Date,106),'' '',''-'')
		 else 																
				convert(varchar, ManualTimeEntry_Date,@dateFormat)
	end as Mdate,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_InDate,106),'' '',''-'')
		 else 
			convert(varchar, ManualTimeEntry_InDate,@dateFormat) 
	end as InDate,
	case when (select TimeFormat from TA_Tbl_DateandTimeFormat)=''hh:mm'' then CONVERT(varchar(8), 
		   DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_InTime,0)), 114) else 
	M.ManualTimeEntry_InTime end ManualTimeEntry_InTime 
	,M.ManualTimeEntry_InReaderID,
	M.ManualTimeEntry_InPunchType,
	case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_OutDate,106),'' '',''-'')
		 else
			  convert(varchar, ManualTimeEntry_OutDate,@dateFormat) 
	end 
	as OutDate,
	case when (select TimeFormat from TA_Tbl_DateandTimeFormat)=''hh:mm'' then CONVERT(varchar(8), 
		   DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_OutTime,0)), 114) else 
	ManualTimeEntry_OutTime end ManualTimeEntry_OutTime
	,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Remarks,M.ManualTimeEntry_Status,
	E.Employee_FirstName + '''' + E.Employee_LastName AS ''Employee_Name'',E.Employee_Id,E.Emailid,
	E.Employee_Code_Id,M.IsOnduty,M.shift_id,S.Shift_ShortName,
	ld.name as LevelName, ld.id as levelid,ED.DesignationID 
	FROM TA_Tbl_ManualTimeEntry as M 
	INNER JOIN TA_Tbl_Employee as E ON E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	Inner join TA_Tbl_Shift S on M.shift_id=S.Shift_Id
	inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId 
	inner join TA_Tbl_EmployeeDesignation ED on e.Employee_Id = ED.EmployeeId   
	inner join Ta_Tbl_levelDetails ld on el.LevelId = ld.id  
	WHERE M.Isdeleted=@Isdel 
	and M.ManualTimeEntry_Id=@MID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[VerifyShift]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VerifyShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'create procedure [dbo].[VerifyShift] 
as
declare @Employee_Code varchar(20)
declare @Emp_year varchar(20)
declare @Emp_month varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @scount  int 
declare @Day1Shift int
declare @Day2Shift int
declare @Day3Shift int
declare @Day4Shift int
declare @Day5Shift int
declare @Day6Shift int
declare @Day7Shift int
declare @Day8Shift int
declare @Day9Shift int
declare @Day10Shift int
declare @Day11Shift int
declare @Day12Shift int
declare @Day13Shift int
declare @Day14Shift int
declare @Day15Shift int
declare @Day16Shift int
declare @Day17Shift int
declare @Day18Shift int
declare @Day19Shift int
declare @Day20Shift int
declare @Day21Shift int
declare @Day22Shift int
declare @Day23Shift int
declare @Day24Shift int
declare @Day25Shift int
declare @Day26Shift int
declare @Day27Shift int
declare @Day28Shift int
declare @Day29Shift int
declare @Day30Shift int
declare @Day31Shift int
declare @shiftIDS int
declare emp_ReProcess cursor for 
select EmployeeId,Year,Month,Day1Shift,Day2Shift,Day3Shift,Day4Shift,Day5Shift,Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
 from dbo.TA_Tbl_PermanentShiftAllocation where Month >6
open emp_ReProcess
fetch emp_ReProcess into @Employee_Code,@Emp_year,@Emp_month,@Day1Shift,@Day2Shift,@Day3Shift,@Day4Shift,@Day5Shift,@Day6Shift,@Day7Shift,@Day8Shift,@Day9Shift,@Day10Shift,@Day11Shift,@Day12Shift,@Day13Shift,@Day14Shift,@Day15Shift,@Day16Shift,@Day17Shift,@Day18Shift,@Day19Shift,@Day20Shift,@Day21Shift,@Day22Shift,@Day23Shift,@Day24Shift,@Day25Shift,@Day26Shift,@Day27Shift,@Day28Shift,@Day29Shift,@Day30Shift,@Day31Shift
while (@@fetch_status = 0 )
begin
set @shiftIDS=167
-- select * from dbo.TA_Tbl_ProcessedData where
-- Shift_Id not in ( select Shift_Id from dbo.TA_Tbl_Shift) and Shift_Id<>0 and  Shift_Id<>-1 order by date 
 if (@Day1Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day1Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day1Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day2Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day2Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day2Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day3Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day3Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day3Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day4Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day4Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day4Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day5Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day5Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day5Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day6Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day6Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day6Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day7Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day7Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day7Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day8Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day8Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day8Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day9Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day9Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day9Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day10Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day10Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day10Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day11Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day11Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day11Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day12Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day12Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day12Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day13Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day13Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day13Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day14Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day14Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day14Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day15Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day15Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day15Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day16Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day16Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day16Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day17Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day17Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day17Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day18Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day18Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day18Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day19Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day19Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day19Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day20Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day20Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day20Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day21Shift>0 )
begin
set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day21Shift)
		 if (@eCount=0 )
		begin
update TA_Tbl_PermanentShiftAllocation set Day21Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
		 end
end
if (@Day22Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day22Shift)
	 if (@eCount=0  )
	begin
update TA_Tbl_PermanentShiftAllocation set Day22Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day23Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day23Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day23Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day24Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day24Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day24Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day25Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day25Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day25Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day26Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day26Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day26Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day27Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day27Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day27Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day28Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day28Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day28Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day29Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day29Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day29Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day30Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day30Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day30Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
if (@Day31Shift>0 )
begin
	set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =@Day31Shift)
	 if (@eCount=0 )
	begin
update TA_Tbl_PermanentShiftAllocation set Day31Shift =@shiftIDS where EmployeeId= @Employee_Code and Year=@Emp_year and Month=@Emp_month
	 end
end
--select @scount=2
--While @scount <= 30
--begin
--set @eCount=(select  count(* ) from dbo.TA_Tbl_Shift WHERE Shift_Id =''@Day''+ltrim(str(@scount))+''Shift'')
-- if (@eCount=0)
--begin
-- end
--select @scount=2+1
--end
  fetch emp_ReProcess into @Employee_Code,@Emp_year,@Emp_month,@Day1Shift,@Day2Shift,@Day3Shift,@Day4Shift,@Day5Shift,@Day6Shift,@Day7Shift,@Day8Shift,@Day9Shift,@Day10Shift,@Day11Shift,@Day12Shift,@Day13Shift,@Day14Shift,@Day15Shift,@Day16Shift,@Day17Shift,@Day18Shift,@Day19Shift,@Day20Shift,@Day21Shift,@Day22Shift,@Day23Shift,@Day24Shift,@Day25Shift,@Day26Shift,@Day27Shift,@Day28Shift,@Day29Shift,@Day30Shift,@Day31Shift
end   
deallocate emp_ReProcess' 
END
GO
/****** Object:  View [dbo].[TA_VW_ShiftInPunches]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_ShiftInPunches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_ShiftInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], ''Shift In'' PunchType
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = ''N'') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE ''In'')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_ShiftInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_ShiftInPunches'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_ShiftInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_ShiftInPunches'
GO
/****** Object:  View [dbo].[TA_VW_LunchInPunches]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_LunchInPunches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_LunchInPunches]
AS
SELECT     TOP (100) PERCENT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], CD.Clk_InPunchType [PunchType]
FROM         dbo.TA_Tbl_ClockDetails AS CD RIGHT OUTER JOIN
                      dbo.TA_Tbl_Terminal AS T ON T.Terminal_ReaderID = CD.Clk_InDeviceId RIGHT OUTER JOIN
                      dbo.TA_Tbl_Entrance_INOUTDetails AS E ON E.Reader_Id = T.Terminal_Id
WHERE     (CD.Clk_Process = ''N'') AND (E.Entrance_Id IN (33, 34)) AND (CD.Clk_InPunchType LIKE ''Lunch In'')
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType
ORDER BY CD.Clk_EmpId, CD.Clk_Date
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_LunchInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[41] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "CD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 218
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "T"
            Begin Extent = 
               Top = 6
               Left = 256
               Bottom = 125
               Right = 447
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "E"
            Begin Extent = 
               Top = 6
               Left = 485
               Bottom = 125
               Right = 661
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 12
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_LunchInPunches'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_LunchInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_LunchInPunches'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntryById]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualEntryById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_GetManualEntryById 157
CREATE   PROCEDURE [dbo].[Proc_TA_GetManualEntryById]
(@MID as int)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as varchar(10)
	select @dateFormat=DateFormat,@TimeFormat=TimeFormat from dbo.Func_TA_GetDateTimeFormat()
	
	select M.ManualTimeEntry_Id,Replace(Convert(varchar,M.ManualTimeEntry_Date,@dateFormat),'' '',''-'') as Mdate,
	Replace(Convert(varchar, M.ManualTimeEntry_InDate,@dateFormat),'' '',''-'') as InDate,
	case	when @TimeFormat=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_InTime,0)), 114)
			else substring(M.ManualTimeEntry_InTime,0,6)+'' '' + substring(M.ManualTimeEntry_InTime,10,12) end ManualTimeEntry_InTime,
	M.ManualTimeEntry_InReaderID,
	M.ManualTimeEntry_InPunchType,Replace(Convert(varchar, M.ManualTimeEntry_OutDate,@dateFormat),'' '',''-'') as OutDate,
	case	when @TimeFormat=''hh:mm'' then 
				CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,M.ManualTimeEntry_OutTime,0)), 114)
			else substring(ManualTimeEntry_OutTime,0,6)+'' ''+substring(ManualTimeEntry_OutTime,10,12) end ManualTimeEntry_OutTime
	,M.ManualTimeEntry_OutReaderID,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Remarks,M.ManualTimeEntry_Status,
	E.Employee_FirstName + '' '' + E.Employee_LastName AS ''Employee_Name'',
	E.Employee_Code_Id,En.Entrance_Id,En.Entrance_Name,M.IsOnduty  
	FROM TA_Tbl_ManualTimeEntry as M INNER JOIN TA_Tbl_Employee as E ON (E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id)
	INNER JOIN TA_Tbl_Entrance_INOUTDetails eio ON (eio.Reader_Id=M.ManualTimeEntry_InReaderID or eio.Reader_Id=M.ManualTimeEntry_OutReaderID)
	INNER JOIN TA_Tbl_Entrance as En ON (EN.Entrance_Id=eio.Entrance_Id)
	WHERE M.Isdeleted=0 and M.ManualTimeEntry_Id=@MID and En.Isdeleted=0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetMaxDaysApplicableByLeavePolicy
Description		:	Get Maximum No. of Leaves applicable for a Particular employee based on Leave Policy Details
Tables Included	:	TA_Tbl_LeavePolicyDetails,TA_Tbl_LeaveType,TA_Tbl_Emp_LeavePolicy and TA_Tbl_Employee
Created By		:	Prabakaran
Created On		:	18-Jul-07
Modified By		:
Modified On		:
*/
CREATE Procedure [dbo].[Proc_TA_GetMaxDaysApplicableByLeavePolicy]
@Employee_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select lp.LeaveType_Id,lp.MaxDays_applicable as MaxDays_applicable,lt.LeaveType  
	from TA_Tbl_LeavePolicyDetails lp 
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id
	inner join TA_Tbl_Emp_LeavePolicy e on e.LeavePolicy_Id=lp.Policy_Id
	where e.EmployeeId= @Employee_Id  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftRoaster]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_ShiftRoaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Temp_ShiftRoaster] AS
select * from TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Temp_ShiftPatternId]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Temp_ShiftPatternId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Temp_ShiftPatternId](@ShiftPatternid int)
 AS
SELECT *  FROM TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternid
' 
END
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches_Test]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunches_Test]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_FirstInPunches_Test]
AS
--Get All Employee Appropriate Device First In Data After Shift In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime],  ''Work Place In'' PunchType, ''Shift FIn'' [FirstInPunch], NULL Id FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_ShiftInPunches IP ON IP.EmployeeCodeId = CD.Clk_EmpId AND IP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= IP.[DateTime]
WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Break In
SELECT [EmployeeCodeId],[DeviceId], [Date], [DateTime], PunchType, [FirstInPunch], ROW_NUMBER() OVER(PARTITION BY [EmployeeCodeId], CAST([Date] AS DATETIME) ORDER BY [DateTime] ASC) Id FROM (
	SELECT DISTINCT
		CD.Clk_EmpId [EmployeeCodeId], 
		CD.Clk_InDeviceId [DeviceId],
		CD.Clk_Date [Date],
		--(SELECT TOP 1(TCD.Clk_InDate + TCD.Clk_InTime) FROM TA_Tbl_ClockDetails TCD WHERE TCD.Clk_Process = ''N'' AND TCD.Clk_InPunchType LIKE ''In'' AND TCD.Clk_EmpId = CD.Clk_EmpId AND (TCD.Clk_InDate + TCD.Clk_InTime) >= BP.[DateTime]) [DateTime],
		(CD.Clk_InDate + CD.Clk_InTime)[DateTime],
		''Work Place In'' PunchType,
		''Break FIn'' [FirstInPunch]
	FROM TA_Tbl_ClockDetails CD
	RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
	RIGHT OUTER JOIN TA_VW_BreakInPunches_Test BP ON BP.EmployeeCodeId = CD.Clk_EmpId AND BP.[Date] = CD.Clk_Date --AND (Clk_InDate + Clk_InTime) >= BP.[DateTime]
	WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
	GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id, (CD.Clk_InDate + CD.Clk_InTime), BP.[DateTime]
) Tbl
UNION ALL
--Get All Employee Appropriate Device First In Data After Lunch In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], ''Work Place In'' PunchType, ''Lunch FIn'' [FirstInPunch], NULL Id FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_LunchInPunches LP ON LP.EmployeeCodeId = CD.Clk_EmpId AND LP.[Date] = CD.Clk_Date AND (CD.Clk_InDate + CD.Clk_InTime) >= LP.[DateTime]
WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
'
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunches]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunches]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_FirstInPunches]
AS
--Get All Employee Appropriate Device First In Data After Shift In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime],  ''Work Place In'' PunchType, ''Shift FIn'' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_ShiftInPunches IP ON IP.EmployeeCodeId = CD.Clk_EmpId AND IP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= IP.[DateTime]
WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Break In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], ''Work Place In'' PunchType, ''Break FIn'' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_BreakInPunches BP ON BP.EmployeeCodeId = CD.Clk_EmpId AND BP.[Date] = CD.Clk_Date AND (Clk_InDate + Clk_InTime) >= BP.[DateTime]
WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
UNION ALL
--Get All Employee Appropriate Device First In Data After Lunch In
SELECT CD.Clk_EmpId [EmployeeCodeId], CD.Clk_InDeviceId [DeviceId], CD.Clk_Date [Date], MIN((CD.Clk_InDate + CD.Clk_InTime)) [DateTime], ''Work Place In'' PunchType, ''Lunch FIn'' [FirstInPunch] FROM TA_Tbl_ClockDetails CD
RIGHT OUTER JOIN TA_Tbl_EmployeeEntrance EE ON EE.Employee_Code_Id = CD.Clk_EmpId AND EE.Device_Id = CD.Clk_InDeviceId
RIGHT OUTER JOIN TA_VW_LunchInPunches LP ON LP.EmployeeCodeId = CD.Clk_EmpId AND LP.[Date] = CD.Clk_Date AND (CD.Clk_InDate + CD.Clk_InTime) >= LP.[DateTime]
WHERE CD.Clk_Process = ''N'' AND CD.Clk_InPunchType LIKE ''In''
GROUP BY CD.Clk_EmpId, CD.Clk_InDeviceId, CD.Clk_Date, CD.Clk_InPunchType, EE.Employee_Code_Id
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_FirstInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunches'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_FirstInPunches', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunches'
GO
/****** Object:  StoredProcedure [dbo].[UpdateDefaultGradeForSEFromDemo]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateDefaultGradeForSEFromDemo]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[UpdateDefaultGradeForSEFromDemo]
	-- Add the parameters for the stored procedure here
	@gradeName nvarchar(50),
    @gradeLevel int,
	@empAutoId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	declare @RecordCount as int
	set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name=''SEGrade'')
	/**********/
	delete from TempEmployee 
	delete from temptitle
	delete from TempApprovalSettings
	Insert into temptitle	
	select TitleName, TitleDescription, LevelID, LeavePolicyID, GradeID, Emp_Id, IsDeleted, Time_Stamp,
	TitleId from TA_Tbl_Title 
	Insert into TempEmployee 
		select Employee_Id,Leave_Sanc_Authority,Reporting_To from TA_Tbl_Employee WHERE Employee_Code_Id <> ''18000000''
	Insert into TempApprovalSettings
	select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry , Approval
	from TA_Tbl_ApprovalSettings
	/**********/
	if(@RecordCount=0)
		begin	
			INSERT INTO TA_Tbl_Grade(Grade_Name,Grade_Level,Emp_ID,Time_Stamp,Isdeleted) VALUES(@gradeName,@gradeLevel,@empAutoId,getdate(),0)
			select @@identity
			UPDATE TA_Tbl_Title SET GradeID = @@identity
			UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> ''18000000''
			update TA_Tbl_Grade set Isdeleted=1 where Grade_ID <> @@identity
			--DELETE TA_Tbl_Grade WHERE Grade_ID <> @@identity
			DELETE FROM TA_Tbl_ApprovalSettings
		end
	else
		begin
			UPDATE TA_Tbl_Grade SET Isdeleted =0 where Grade_ID=(select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=1)
			UPDATE TA_Tbl_Title SET GradeID = (select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1)
			UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> ''18000000''
			update TA_Tbl_Grade set Isdeleted=1 WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=0)
			--DELETE TA_Tbl_Grade WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=0)
			DELETE FROM TA_Tbl_ApprovalSettings
		end		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosure_Insert]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMonthClosure_Insert]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*      
Procedure Name : Proc_TA_CheckMonthClosure_Insert   1,''01/01/2009 00:00:00.000'',''01/31/2009 00:00:00.000''   
Description : check month closure before insert, is alredy there or not       
Tables Included : TA_Tbl_MonthClosure      
Created By : Kumuthini.L      
Created On : 05-Aug-2007     
Modified By :      
Modified On :      
*/      
CREATE  PROCEDURE [dbo].[Proc_TA_CheckMonthClosure_Insert]     
(    
@Org_LevelId INT,    
@StartDate varchar(30),    
@EndDate varchar(30)     
)    
AS    
BEGIN    
SELECT COUNT(MonthClosure_Id) AS MID FROM TA_Tbl_MonthClosure     
WHERE OrgLevel_Id=@Org_LevelId  AND      
MonthClosure_StartDate=@StartDate AND  
MonthClosure_EndDate=@EndDate  
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetManualTimeEntrySanctionDetails ''3'','''','''','''','''',''2'','''',''08/01/2008'',''05/31/2009'',0
Description		:	Get Manual Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included		:	TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee
Created By		:	Kumuthini.L
Created On		:	09-Jan-09
Modified By		:	Sasireka
Modified On		:	18.05.09
Modified By     :A.Amsaveni on 25/09/2013 to orderby MT.ManualTimeEntry_Date
Modified By		:K.Gopinath
Modified On		:	01-Feb-2014
Descriptions	: For filter the OD entry.
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetManualTimeEntrySanctionDetails]
	@Employee_Id int,
	@LevelId varchar(2000),
	@Status varchar(20) =null,
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate datetime =null,
	@ManualEntry_ToDate datetime =null,
	@Isdeleted bit =0,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int    
as
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	set @sqlQuery=''''
	set @sqlQuery = ''select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,CONVERT(VARCHAR, MT.ManualTimeEntry_Date, 101) AS ManualTimeEntry_Date,CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,101) + ''''  '''' + MT.ManualTimeEntry_InTime AS ''''InDateTime'''', CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,101) + ''''  '''' + MT.ManualTimeEntry_OutTime AS ''''OutDateTime'''',MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''''0'''' as SelectedRecords from TA_TBL_Employee E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on E.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on E.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''
	set @sqlQuery = @sqlQuery + '' where  (Reporting_to in(Select Reporting_To from ta_Tbl_employee where Reporting_To='''''' + cast(@Employee_Id as nvarchar(20)) + '''''') ''
	set @sqlQuery = @sqlQuery + '' or Leave_Sanc_Authority in (Select Leave_Sanc_Authority from ta_Tbl_employee where Leave_Sanc_Authority='''''' + cast(@Employee_Id as nvarchar(20)) + ''''''))  and ''
	set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and MT.IsDeleted=0 and ys.IsActive=1 and MT.IsOnDuty=0''
	set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  MT.ManualTimeEntry_Date order by EffectiveDate desc) ''
	if not(@EmployeeName='''')
	begin
		set @sqlQuery = @sqlQuery + ''and E.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
	end
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='''')
	begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
	end		
 If Not (@EmpSwipeCard = '''')  
    Begin  
		  Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End 
		if not(@Status is null or @Status='''' or @Status=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Status IN ('''''' + @Status  + ''''''))''
		End
		if not(cast(@ManualEntry_FromDate as nvarchar(11))='''' or cast(@ManualEntry_FromDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Date>=CONVERT(DATETIME, '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) + '''''', 102))''
		End
		if not(cast(@ManualEntry_ToDate as nvarchar(11))='''' or cast(@ManualEntry_ToDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Date<=CONVERT(DATETIME, '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) + '''''', 102))''
		End
		set @sqlQuery = @sqlQuery + ''order by MT.ManualTimeEntry_Date desc ''
		exec(@sqlQuery)
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name  : Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin ''3'',''Approved'',''804'','''',0,0,''2013/01/01'',''2013/10/28'',0,'''',''SuperAdmin'',3
Description		: Get Manual Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: Kumuthini.L    
Created On		: 08-Jan-08    
Modified By		: Sasireka.M 
Modified On		: 16-May-2009
Modified By     :A.Amsaveni on 25/09/2013 to orderby MT.ManualTimeEntry_Date
Modified By		:	Manjula.P
Modified On		:	03-Jan-2014
Descriptions	:	Changing condition ManualTimeEntry_InDate and ManualTimeEntry_OutDate in where condition instead of ManualTimeEntry_Date
Issue			:	When we putting manual time entry for past date the records is not displaying in manual time entry sanction screen : Code :0021124
Modified By		:K.Gopinath
Modified On		:	01-Feb-2014
Descriptions	: For filter the OD entry.
*/    
CREATE PROCEDURE [dbo].[Proc_TA_GetManualEntrySanctionDetailsForSuperAdmin]    
	@Employee_ID int,
	@LevelId varchar(2000),    
	@Status varchar(20) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''''
		set @sqlQuery = ''select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,CONVERT(VARCHAR, MT.ManualTimeEntry_Date, 101) AS ManualTimeEntry_Date,CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,101) + ''''  '''' + MT.ManualTimeEntry_InTime AS ''''InDateTime'''', CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,101) + ''''  '''' + MT.ManualTimeEntry_OutTime AS ''''OutDateTime'''',MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''''0'''' as SelectedRecords  from TA_TBL_Employee E ''
		set @sqlQuery = @sqlQuery + '' inner join TA_TBL_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
		set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id ''
		set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and MT.IsDeleted=0 and ys.IsActive=1 and MT.IsOnDuty=0''   
		if not(@EmployeeName='''')
		begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
		if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
		end
		if not (@EmployeeId='''')
		begin
				set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
		end		
		if not(@Status is null or @Status='''' or @Status=''0'' or @Status=''All'')
		begin
			set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Status IN ('''''' + @Status  + ''''''))''
		End
		if not(cast(@ManualEntry_FromDate as nvarchar(11))='''' or cast(@ManualEntry_FromDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (( isnull(MT.ManualTimeEntry_InDate,''''''+cast(''1990/01/01'' as nvarchar(11))+'''''') between '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) +'''''' and '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) +'''''') ''
		End
		if not(cast(@ManualEntry_ToDate as nvarchar(11))='''' or cast(@ManualEntry_ToDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' or ( isnull(MT.ManualTimeEntry_OutDate,''''''+cast(''1990/01/01'' as nvarchar(11))+'''''') between  '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) +'''''' and '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) +'''''')) ''
		End
           set @sqlQuery = @sqlQuery + '' order by MT.ManualTimeEntry_Date desc ''
	exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffSanction]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <22-Jan-2012>
-- Description:	<Comp off Sanction>
-- exec [Proc_TA_EmployeeCompOffSanction] ''2012/01/01'',''2013/01/22'','''','''',''1'',''0'',''0'',''SuperAdmin'',''0'',''All'','''',1,''compoff''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffSanction] 
	-- Add the parameters for the stored procedure here
	(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(50),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @SanctionType varchar(25)   
    )
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  --Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
--/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
--(
--	[EffectiveDate] ASC
--) ON [PRIMARY]
--/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
--CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
--(
--	[PayId] ASC
--) ON [PRIMARY]
--/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
--CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
--(
--	[EmployeeId] ASC
--)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EPay.PayId is not null
/*
	declare @shfTime as dateTime
	set @shfTime = (select Shift_EndTime from ta_tbl_shift where shift_id = @shift)	
*/
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15),
			[CompoffMins] nvarchar(15),
			[HrsCompOff] nvarchar(15)
	  )
	 -- /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessDate] ON [dbo].[#TempProcessedData] 
		--(
		--	[Date] ASC
		--) ON [PRIMARY]
		--/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessCode] ON [dbo].[#TempProcessedData] 
		--(
		--	[Employee_Code_Id] ASC
		--) ON [PRIMARY]
		--/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		--CREATE NONCLUSTERED INDEX [IDX_TempProcessOtMins] ON [dbo].[#TempProcessedData] 
		--(
		--	[OtMins] ASC
		--) ON [PRIMARY]
	  insert into #TempProcessedData 
	  select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
	  [EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
	  [OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[CompoffMins],[Hrscompoff]
	   from TA_Tbl_ProcessedData PD
	  where Employee_Code_Id in (
	  select SwipeCardNo from TA_Tbl_Employee inner join
	  #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id)
	  and CompoffMins<>0 and CompoffMins is not null and 
	  [Date] between @fromDat and @ToDat 
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''select * from (''
	set @sqlQuery = @sqlQuery + ''select #TempProcessedData.Process_Rec_ID,TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,''
	--set @sqlQuery = @sqlQuery + ''ISNULL(ta_tbl_shift.Shift_ShortName,''''Off'''') as ShiftName,''
	--set @sqlQuery = @sqlQuery +  '' #TempProcessedData.HrsWork, #TempProcessedData.HrsOt,#TempProcessedData.OffOT,#TempProcessedData.HolOT, ta_tbl_Employee.Employee_FirstName from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.Employee_Code_Id''
	--set @sqlQuery = @sqlQuery +  '' where #TempProcessedData.HrsOT is not NULL and #TempProcessedData.HrsOt <>''''0''''''
	set @sqlQuery = @sqlQuery + '' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT,#TempProcessedData.OffOT,#TempProcessedData.HolOT,ISNULL(#TempProcessedData.OverTimeStatus,''''Pending'''') as OverTimeStatus, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''''''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],ta_tbl_Employee.Employee_Id,#TempProcessedData.OTMins,''''0'''' as SelectedRecords,HrsCompoff from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
	--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''	 
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' where #TempProcessedData.CompoffMins <> 0 ''
	if(@SanctionType = ''OverTime'')
		begin
			set @sqlQuery = @sqlQuery + '' AND Ta_Tbl_Employee.OT_Eligible=1 ''
		end
	ELSE IF(@SanctionType = ''compoff'')
		BEGIN
			set @sqlQuery = @sqlQuery + '' AND Ta_Tbl_Employee.CompOff_Eligible=1 ''
		END	
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end
--	if(@shift<>0) 
--	begin
--		set @sqlQuery = @sqlQuery + '' And #TempProcessedData.Shift_Id='' + cast (@shift as nvarchar(50))  
--	end 
	set @sqlQuery = @sqlQuery + '' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1''
	--set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	--set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	--set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	--set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	--set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeePay.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeePay where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	if not(@EmployeeName='''')
	begin
			set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		-- set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@empId='''')
	begin
		--set @sqlQuery = @sqlQuery + '' and #TempProcessedData.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
	end
 If Not (@EmpSwipeCard = '''')  
    Begin  
		  Set @sqlQuery = @sqlQuery + '' And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End
	--if not(@LevelID='''' or @LevelID=''0'')
	--begin
		--set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '') '' 
	--end
	if not(@status='''' or @status=''All'')
	begin
	 	IF(@status = ''Pending'')
			BEGIN
				set @sqlQuery = @sqlQuery + '' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = '''''' + @status + '''''')''
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + '' AND #TempProcessedData.OvertimeStatus = '''''' + @status + ''''''''
			END
             end 
	set @sqlQuery = @sqlQuery + '' ) OTRecords order by OTRecords.Employee_Code_Id , OTRecords.Date''
	exec (@sqlQuery)
--Remove the temporary tables here
drop table #TempProcessedData
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffRequestionCount]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffRequestionCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_EmployeeOTSanction  
Description : To get the OT Employee with Approval Status
*/  
-- [Proc_TA_EmployeeCompOffRequestionCount] 2,''IndividualUsers''
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffRequestionCount]
(
	@Employee_ID int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
	--select * from #EmpDesignation
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
		;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	--inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	--select @TopLevelId
	--update TA_Tbl_ShiftSettings set isRequestingforCompOff=1
	
	CREATE TABLE #TempProcessedData
	(
		[Process_Rec_ID] bigint,
		[Employee_Code_Id] nvarchar(20),
		[Date] datetime,
		[Shift_Id] int,
		[InTime] nvarchar(25),
		[OutTime] nvarchar(25),
		[HrsWork] nvarchar(10),
		[HrsOT] nvarchar(10),
		[NormOT] nvarchar(10),
		[OffOT] nvarchar(10),
		[HolOT] nvarchar(10),
		[EarlyOut] nvarchar(10),
		[LateIn] nvarchar(10),
		[Attendance] nvarchar(20),
		[WorkHrs] nvarchar(10),
		[HrsLess] nvarchar(10),
		[HrsExtra] nvarchar(10),
		[LateInMins] float,
		[EarlyOutMins] float,
		[ExtraMins] float,
		[OtMins] float,
		[OvertimeStatus] nvarchar(50),
		[TotalDays] numeric(18, 1),
		[LeaveCode] nvarchar(20),
		[LateEntryReason] nvarchar(260),
		[EarlyOutReason] nvarchar(260),
		[ProcessFlag] bit,
		[Status] nvarchar(50),
		[FNAttendanceCode] nvarchar(15),
		[ANAttendanceCode] nvarchar(15),
		[ActHrsOT] nvarchar(10),
		[ActNormOT] nvarchar(10),
		[ActOffOT] nvarchar(10),
		[ActHolOT] nvarchar(10),
		[ActOtMins] float,
		[AvailOtMins] float,
		[ExtraTime_Id] bigint
	)
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate,@ToDate=TODATE  from TA_Tbl_YearSetting where IsActive=1
	
	insert into #TempProcessedData 
	select OT.Process_RecID as ''Process_Rec_ID'',E.Employee_Code_Id,OT.Date,p.Shift_Id,
	P.InTime,P.OutTime,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,
	p.EarlyOut,p.LateIn,p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,
	p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
	p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,
	p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id				
	from TA_Tbl_OverTimeStatus OT 
	inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
	inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id  
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
	where P.[Date] between @Fromdate and @ToDate and OT.isDelete=0 and OT.isRequest=1
	and OT.isdelete=0 and DateToExpired>=GETDATE()
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''	
	set @sqlQuery = @sqlQuery + ''select 
	count(case  when OverTimeStatus=''''Approved'''' and E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1  end)Approved,
	count(case  when OverTimeStatus=''''Forwarded'''' and E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1 end)Forwarded,
    count(case  when OverTimeStatus=''''Pending'''' and (E.Reporting_To='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' or E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''') then 1  end)Pending 
    from #TempProcessedData TPD 
	INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.SwipeCardNo''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''	 
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' where TPD.AvailOtMins <> 0 AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 ''
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	set @sqlQuery = @sqlQuery + '' And E.isdeleted=0 and E.report_exclude=0 and E.employee_status=1''
	exec (@sqlQuery)
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeCompOffOTSanction]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeCompOffOTSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*   
Procedure Name    :     Proc_TA_EmployeeCompOffOTSanction
Tables Included :      TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
                              TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
                              TA_Tbl_Grade,ta_tbl_shift
Created By        :     A.K.T.MOORTHI
Created On        :     20-July-2013
Description       :     To get the OT and CompOff Employee.
Modified By       :   A.K.T.MOORTHI
Modified On       :   06-Aug-2014
Description       :     Remove The Date Convertion In Expaire Date Calculation
UPDATE TA_Tbl_ProcessedData SET OverTimeStatus = ''Pending'' WHERE Process_Rec_ID IN(1944, 1945, 2065)
EXEC [Proc_TA_EmployeeCompOffOTSanction] ''2019/02/01'',''2019/02/28'',''14230'','''',''1'',''0'',''0'',''SuperAdmin'',''0'',''All'','''',1, 97
exec Proc_TA_EmployeeCompOffOTSanction @FromDate=''2015-04-01 00:00:00'',@ToDate=''2016-04-30 00:00:00'',@EmpId='''',@EmployeeName='''',@LevelID=''1'',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=''SuperAdmin'',@GradeLevel=''5'',@Status=''All'',@EmpSwipeCard='''',@ParentId=1,@ApprovalEmpId=''2''
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeCompOffOTSanction](
      @FromDate DATETIME,
      @ToDate DATETIME,
      @EmpId VARCHAR(100),
      @EmployeeName VARCHAR(50),
      @LevelID VARCHAR(8000),
      @EmployeeCategory INT,
      @EmployeeType INT,
      @UserGroupName VARCHAR(250),
      @GradeLevel VARCHAR(20),
      @Status VARCHAR(50),
      @EmpSwipeCard VARCHAR(20),
      @ParentId INT,
      @ApprovalEmpId VARCHAR(20)
)
AS
BEGIN
	set nocount on
   DECLARE @SQLQuery VARCHAR(MAX) 
   set @SQLQuery= ''''
   declare @AUserGroup VARCHAR(100) 
   declare @AUserGroupType VARCHAR(100) 
   set @AUserGroup= ''''
   set @AUserGroupType= ''''
   DECLARE @Id INT
   DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
   set @Id = ISNULL(@ParentId, 0)
      SELECT @AUserGroup = ISNULL(UG.groupName, ''''),@AUserGroupType=ISNULL(ReportsBasedOn,2) FROM TA_Tbl_Employee Emp
            INNER JOIN TA_Tbl_Usergroup UG ON UG.groupId = Emp.UserGroup_Id
      WHERE Employee_Id = @ApprovalEmpId
      if(@AUserGroupType='''')
      begin
		set @AUserGroupType=2
	  end
      WHILE (NOT EXISTS(SELECT Id FROM Ta_Tbl_levelDetails WHERE id = @Id AND parentId = 0) AND @Id !=0)
      BEGIN
            SELECT @Id = parentId FROM Ta_Tbl_levelDetails WHERE id = @Id
      END
      declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](CAST(@ApprovalEmpId as int)) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](CAST(@ApprovalEmpId as int)) as EmpAutoId
--Temporary table''s creation
      CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME)
      CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
      CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
      CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
      CREATE TABLE #LevelRights(LevelId INT)
      Create table #OTHours (Process_Rec_ID int,Employee_ID int,Employee_Code_ID nvarchar(20),Date varchar(20),Employee_FirstName nvarchar(Max),[Level Name] nvarchar(Max),HrsExtra nvarchar(20),ActHrsExtra nvarchar(20),ActExtraMins int,HrsExtraIn nvarchar(20),ExtraMins int,OverTimeStatus nvarchar(10),CompOffEligible int,OTEligible int,CompOffChecked int,OTChecked int,Status nvarchar(10),TopLevelID int)
      INSERT INTO #LevelRights 
            SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
      (
            [LevelId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
      (
            [EffectiveDate] ASC
      )ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
      (
            [DesignationId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
      (
            [EmployeeId] ASC
      ) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
      (
            [TypeId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
      (
            [EffectiveDate] ASC
      )ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
      (
            [CategoryId] ASC
      ) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
      (
            [EmployeeId] ASC
      ) ON [PRIMARY]
--Employee Level insert in Temporary table
      INSERT INTO #EmpLevel 
            SELECT EL.EmployeeId, EL.LevelId, MAX(EL.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeLevel EL
                  INNER JOIN TA_Tbl_Employee Emp ON EL.EmployeeId = Emp.Employee_Id       
            WHERE Emp.Isdeleted = 0 AND EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
            GROUP BY EL.EmployeeId, EL.LevelId
      INSERT INTO #EmpDesignation 
            SELECT ED.EmployeeId, ED.DesignationID, MAX(ED.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeDesignation ED
                  INNER JOIN TA_Tbl_Employee Emp ON ED.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
            GROUP BY ED.EmployeeID, ED.DesignationID
      INSERT INTO #EmpType 
            SELECT ET.EmployeeId, ET.TypeId, MAX(ET.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeType ET
                  INNER JOIN TA_Tbl_Employee Emp ON ET.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND ET.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ET.TypeId IS NOT NULL
            GROUP BY ET.EmployeeId, ET.TypeId
      INSERT INTO #EmpCategory
            SELECT EC.EmployeeId, EC.CategoryId, MAX(EC.EffectiveDate) EffectiveDate FROM TA_Tbl_EmployeeCategory EC
                  INNER JOIN TA_Tbl_Employee Emp ON EC.EmployeeId = Emp.Employee_Id 
            WHERE Emp.Isdeleted = 0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EC.CategoryId IS NOT NULL
            GROUP BY EC.EmployeeId, EC.CategoryId
      --CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''''00:00''''), 108)
      SET @SQLQuery = ''SELECT PD.Process_Rec_ID, Emp.Employee_Id, Emp.Employee_Code_Id, case when ''+cast(@dateFormat as varchar(100))+''=106 then
					REPLACE(CONVERT(VARCHAR, PD.[Date],''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
					else CONVERT(VARCHAR, PD.[Date], ''+cast(@dateFormat as varchar(100))+'') end  AS [Date],''
      SET @SQLQuery = @SQLQuery + '' Emp.Employee_FirstName + SPACE(1) + ISNULL(Emp.Employee_LastName, '''''''') Employee_FirstName, REPLACE(LD.Name, ''''&amp;'''', ''''&'''') [Level Name],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN PD.HrsOT != ''''00:00'''' THEN PD.HrsOT WHEN PD.NormOT != ''''00:00'''' THEN PD.NormOT WHEN PD.OffOT != ''''00:00'''' THEN PD.OffOT WHEN PD.HolOT != ''''00:00'''' THEN PD.HolOT END) [HrsExtra],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN isnull(PD.ActHrsOT,PD.HrsOT) != ''''00:00'''' THEN isnull(PD.ActHrsOT,PD.HrsOT) WHEN isnull(PD.ActNormOT,PD.NormOT) != ''''00:00'''' THEN isnull(PD.ActNormOT,PD.NormOT) WHEN isnull(PD.ActOffOT,PD.OffOT) != ''''00:00'''' THEN isnull(PD.ActOffOT,PD.OffOT) WHEN isnull(PD.ActHolOT,PD.HolOT) != ''''00:00'''' THEN isnull(PD.ActHolOT,PD.HolOT) END) [ActHrsExtra],isnull(PD.ActOtMins,PD.OtMins) [ActExtraMins],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN PD.HrsOT != ''''00:00'''' THEN PD.HrsOT WHEN PD.NormOT != ''''00:00'''' THEN ''''NormOTHrs'''' WHEN PD.OffOT != ''''00:00'''' THEN ''''WeekOffOT'''' WHEN PD.HolOT != ''''00:00'''' THEN ''''HolOT'''' END) [HrsExtraIn],''
      SET @SQLQuery = @SQLQuery + '' PD.OtMins [ExtraMins], 
      (CASE WHEN (('''''' + @AUserGroup + '''''' = ''''SuperAdmin'''' OR '' + @ApprovalEmpId + '' = ISNULL(Emp.Reporting_To, 0) OR '' + @AUserGroupType + '' = 0) 
      AND (ISNULL(PD.OverTimeStatus, ''''Pending'''') = ''''Pending'''') AND ('''''' + @AUserGroup + '''''' = ''''SuperAdmin'''' OR '' + @ApprovalEmpId + '' = ISNULL(Emp.Leave_Sanc_Authority, 0) OR '' + @AUserGroupType + '' = 0)) 
      THEN ''''Forwarded'''' ELSE ISNULL(PD.OverTimeStatus, ''''Pending'''') END) [OverTimeStatus],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN ((DATEADD(D, ISNULL(SS.VaildityCompOffDays, 0), PD.[Date]) < GETDATE()) OR (ISNULL(PD.OverTimeStatus, ''''Pending'''') = ''''Approved'''')) THEN 0 WHEN ((DATEDIFF(MI,''''00:00'''', ISNULL(SS.HalfDayCompOff, ''''00:00'''')) > ISNULL(PD.OtMins, 0)) OR ISNULL(PD.OtMins, 0) = 0) THEN 0 ELSE 1 END) [CompOffEligible],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN ((ISNULL(PD.OtMins, 0) = 0) OR (ISNULL(PD.OverTimeStatus, ''''Pending'''') = ''''Approved'''')) THEN 0 ELSE 1 END) [OTEligible],''
      SET @SQLQuery = @SQLQuery + '' ISNULL(OTS.CompOffEligible, 0) [CompOffChecked], ISNULL(OTS.OTEligible, 0) [OTChecked],''
      SET @SQLQuery = @SQLQuery + '' (CASE WHEN '''''' + @AUserGroup + '''''' = ''''SuperAdmin'''' OR '' + @ApprovalEmpId + '' = ISNULL(Emp.Leave_Sanc_Authority, 0) OR '' + @AUserGroupType + '' = 0 THEN ''''Approved'''' WHEN (('' + @ApprovalEmpId + '' = ISNULL(Emp.Reporting_To, 0)) AND ('' + @ApprovalEmpId + '' = ISNULL(Emp.Leave_Sanc_Authority, 0))) THEN ''''Approved'''' WHEN '' + @ApprovalEmpId + '' = ISNULL(Emp.Reporting_To, 0) THEN ''''Forwarded'''' ELSE ''''Pending'''' END) [Status],''     
      SET @SQLQuery = @SQLQuery + CAST(@Id AS VARCHAR(15)) + '' [TopLevelId]''  
      SET @SQLQuery = @SQLQuery + '' FROM TA_Tbl_ProcessedData PD''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo''
      SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.EmployeeId = Emp.Employee_Id''
      SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id = ELP.LeavePolicy_Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId''
      --SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id''
      SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON SS.CompanyId = '' + CAST(@Id AS VARCHAR(15))
      SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_OverTimeStatus OTS ON OTS.Process_RecID = PD.Process_Rec_ID''    
      SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel EL ON EL.EmployeeId = Emp.Employee_Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation ED ON ED.EmployeeId = Emp.Employee_Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType ET ON ET.EmployeeId = Emp.Employee_Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory EC ON EC.EmployeeId = Emp.Employee_Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = EL.LevelId''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
      SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''      
      SET @SQLQuery = @SQLQuery + '' WHERE PD.OtMins != 0 AND Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1''
      SET @SQLQuery = @SQLQuery + '' AND Emp.IsDeleted = 0 AND Emp.Employee_Status = 1 AND PD.[Date] BETWEEN '''''' + CONVERT(VARCHAR(11), @FromDate, 101) + '''''' AND '''''' + CONVERT(VARCHAR(11), @ToDate, 101) + ''''''''
      SET @SQLQuery = @SQLQuery + '' AND YS.IsActive = 1''-- AND LP.OtDayWise = 1'' AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''''00:00''''), 108) != ''''00:00'''' 
      IF(@UserGroupName <> ''SuperAdmin'')
      BEGIN
            SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel  
      END
		if(@isReportingto > 0)
            BEGIN
               set @SQLQuery = @SQLQuery + '' and (Emp.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
      IF NOT(@EmployeeName = '''')
      BEGIN
            SET @SQLQuery = @SQLQuery + '' AND (Emp.Employee_FirstName + '''' '''' + ISNULL(Emp.Employee_LastName, '''''''') LIKE '''''' + @EmployeeName + ''%'''')''
      END
      IF(@EmployeeCategory <> 0)
      BEGIN
            SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@EmployeeCategory AS VARCHAR(10))
      END
      IF(@EmployeeType<>0)
      BEGIN
            SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@EmployeeType AS VARCHAR(10))
      END
      IF NOT(@EmpId='''')
      BEGIN
            SET @SQLQuery = @SQLQuery + '' AND Emp.Employee_Code_Id = '''''' + CAST(@EmpId AS VARCHAR(50)) + ''''''''
      END
      IF NOT(@EmpSwipeCard = '''')  
    BEGIN
            SET @SQLQuery = @SQLQuery + '' AND Emp.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
      END
      SET @SQLQuery = @SQLQuery + '' ORDER BY PD.Employee_Code_Id, PD.[Date]''
      --print(@SQLQuery)
      insert into #OTHours EXEC(@SQLQuery)
      DECLARE @SQL nvarchar(max)
      set @SQL=''''
      set @SQL=''select * from #OTHours ''
      IF NOT(@Status = '''' OR @Status = ''All'')
      BEGIN
            IF(@Status = ''Pending'')
            BEGIN
                  SET @SQL = @SQL + '' where (OvertimeStatus IS NULL OR OvertimeStatus = '''''' + @Status + '''''')''
            END
            ELSE
            BEGIN
                SET @SQL = @SQL + '' where OvertimeStatus = '''''' + @status + ''''''''
            END
    END
      EXEC(@SQL)
      DROP TABLE #EmpLevel
      DROP TABLE #EmpDesignation
      DROP TABLE #EmpType
      DROP TABLE #EmpCategory
      DROP TABLE #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpDesignation_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpDesignation_MusterRoll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]''2014-09-11'','''',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpDesignation_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@DesignationId varchar(50),
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here	
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql=''	select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeDesignation ed
					inner join ta_tbl_employee		emp	on ed.EmployeeId = emp.Employee_Id 
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 group by ed.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)EDesig
				inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
				AND ED.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and ED.DesignationId is not null ''
	if (@Employee_Code_Id<>'''')
		if(@DesignationId<>0 and @DesignationId!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and ED.DesignationId=''+convert(varchar(20),@DesignationId)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	else 
		if(@DesignationId<>0 and @DesignationId!='''')
			BEGIN					
				Set @sql=@sql+'' and ED.DesignationId=''+convert(varchar(20),@DesignationId)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	execute(@sql)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxUserLevel]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxUserLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Proc_TA_GetMaxUserLevel 1,''SuperAdmin'',0
--	Modified by		:	Manjula.P
--	Modified On		:	13-May-2014
--	Descriptions	:	Adding if condition and else for staying selected organization levels : Ex Discrepancy entry : Bug code :0023939
CREATE  PROCEDURE [dbo].[Proc_TA_GetMaxUserLevel]
(  
  @TotLevels varchar(4000),
  @UserGroupName varchar(250), 
  @ParentId int 
)  
AS  
BEGIN  
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--declare @qry as varchar(8000)  
	--set @qry =''''
	if(isnull(@ParentId,0)=0)
	begin		
		--Added this condition newly to handled one company is having, need to select automatically.
		--on 02-Mar-2020 12:08 PM by Manikanan.rr
		if((select count(*) from ta_tbl_leveldetails where parentId=0 and isDeleted=0)=1)
		begin
			select min(id) as MaxLevel from ta_tbl_leveldetails 
			inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
			where isdeleted=0 and parentID = (select min(parentid) from Ta_Tbl_levelDetails where isdeleted=0)
		end
		else
		begin
			select min(id) as MaxLevel from ta_tbl_leveldetails 
			inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
			where isdeleted=0 and parentID = (select min(parentid) from Ta_Tbl_levelDetails where levelId=3 and isdeleted=0)
		end
	end
	else   
	begin
	  select max(id) as MaxLevel from ta_tbl_leveldetails 
	  inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id  
	  where isdeleted=0 and parentID = (select min(ParentID) from ta_tbl_leveldetails 
	  inner join #LevelRights on #LevelRights.LevelId=ta_tbl_leveldetails.id where isdeleted=0)
	end
	--exec (@qry)
	drop table #LevelRights 
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetMaxPermissionHoursByLeavePolicy 151
Description		:	Get Permisssion Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeavePolicy
Created By		:	Prabakaran
Created On		:	19-Jul-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_GetMaxPermissionHoursByLeavePolicy]
	@Employee_Id bigint
as
BEGIN
	SET NOCOUNT ON;
	select * from TA_Tbl_LeavePolicy l 
	inner join ta_tbl_Emp_leavepolicyDetails elpd on l.Policy_Id= elpd.Policy_ID
	inner join ta_tbl_emp_leavepolicy elp on elp.Emp_LeavePolicyId=elpd.Emp_LeavePolicyId
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId
	where ys.IsActive=1 and elpd.empid=@Employee_Id and  l.IsDeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ProjectReport_Mesmack]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ProjectReport_Mesmack]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <06Jan2020>
-- Description:	<Project Summary Report>
-- =============================================
--Proc_TA_ProjectReport_Mesmack ''v124'',''0,1'',''01/jan/2019'',''30/Dec/2019'','''',0,0,0,''SuperAdmin'',''0'',0,0,''Both'',0,0,0
--v124	477	11124 SANTHOSAM M
CREATE PROCEDURE [dbo].[Proc_TA_ProjectReport_Mesmack]

	@EmployeeID varchar(50), 
	@LevelID varchar(8000),  
	@FromDate varchar(50), 
	@ToDate varchar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int,
	@ProjectId bigint

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @local_EmployeeID varchar(50)
	DECLARE @local_LevelID varchar(8000)
	DECLARE @local_FromDate varchar(50) 
	DECLARE @local_ToDate varchar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	DECLARE @local_ProjectId int

	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	set @local_ProjectId=@ProjectId

	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	DECLARE @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	create table #Project(projectId bigint)
    create table #EmpOvertime(SwipecardNo varchar(50),overtimeduration varchar(10));
	create table #EmpAbsent(SwipecardNo varchar(50), Absentdays float);
	create table #EmpSickeLeave(SwipecardNo varchar(50),EmployeeName varchar(200), SickeLeaves float);
	create table #EmpUmrahLeave(SwipecardNo varchar(50),EmployeeName varchar(200), UmrahLeave float);
	create table #EmpOtherLeave(SwipecardNo varchar(50),EmployeeName varchar(200), OtherLeave float);
	create table #tempProjectSummary (EmployeeName varchar(200),Employee_Code_Id varchar(50), overtimeduration varchar(10),Absentdays float,SickeLeaves float,UmrahLeave float,OtherLeave float)

	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	create table #EmployeeNames(SwipecardNo varchar(50), EmployeeName varchar(200), EmployeeCodeId varchar(50))

	--insert into #Project
	--select Project_Id from ta_tbl_project
	--where (Project_StartTime >= CONVERT(DATETIME,''''+cast(@local_FromDate as nvarchar(20))+'''', 102)
	--and Project_EndTime <=  CONVERT(DATETIME,''''+cast(@local_ToDate as nvarchar(20))+'''', 102) )
	--and (Project_Status != ''Rejected'') and (IsDeleted = 0)

    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 


	--insert into level table
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End	
	Execute(@sqlEmpLevel);

	--Overtime for the duration coding

	WITH cte AS (
    SELECT a.Employee_Code_Id,SUM(DATEDIFF(MINUTE, ''00:00'', CAST(NormOT AS TIME))) t
    FROM TA_Tbl_ProcessedData a
	inner join #EmpLevel b on b.SwipeCard = a.Employee_Code_Id
	inner join #EmpDesignation c on c.SwipeCard = a.Employee_Code_Id
	inner join #EmpType d on d.SwipeCard = a.Employee_Code_Id
	inner join #EmpCategory e on e.SwipeCard = a.Employee_Code_Id
	where a.date >= CONVERT(DATETIME,''''+cast(@local_FromDate as nvarchar(50))+'''', 102) 
	and a.date <= CONVERT(DATETIME,''''+cast(@local_ToDate as nvarchar(50))+'''', 102) 
	GROUP BY a.Employee_Code_Id
	)

   	insert into #EmpOvertime SELECT Employee_Code_Id,
	RTRIM(t/60) + '':'' + RIGHT(''0'' + RTRIM(t%60), 2) FROM cte

	--Absent days for the duration coding

	insert into #EmpAbsent	
	select a.Employee_Code_Id,
	sum(case when a.FNAttendanceCode = ''Absent'' and a.ANAttendanceCode = ''Absent'' then 1
	else 0
	end)
	FROM TA_Tbl_ProcessedData a
	inner join #EmpLevel b on b.SwipeCard = a.Employee_Code_Id
	inner join #EmpDesignation c on c.SwipeCard = a.Employee_Code_Id
	inner join #EmpType d on d.SwipeCard = a.Employee_Code_Id
	inner join #EmpCategory e on e.SwipeCard = a.Employee_Code_Id
	where a.date >= CONVERT(DATETIME,''''+cast(@local_FromDate as nvarchar(50))+'''', 102) 
	and a.date <= CONVERT(DATETIME,''''+cast(@local_ToDate as nvarchar(50))+'''', 102) 
	GROUP BY a.Employee_Code_Id


	--Leave count according to type coding

	declare @DynamicSQL varchar(max)
	set @DynamicSQL = ''''

	set @DynamicSQL = @DynamicSQL + ''select b.SwipeCardNo, b.Employee_FirstName, isnull(sum(isnull(a.NumberOfDays,0)),0)
	from TA_Tbl_LeaveApplication a
	inner join TA_Tbl_LeaveType d on d.LeaveType_Id = a.LeaveType_id
	inner join ta_tbl_employee b on b.Employee_Id = a.Employee_Id
	inner join #EmpLevel c on c.SwipeCard = b.SwipeCardNo
	where a.Leave_FromDate >= CONVERT(DATETIME,''''''+cast(@local_FromDate as nvarchar(50))+'''''', 102) 
	and a.Leave_ToDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) 
	and (d.LeaveType_Id = a.LeaveType_id)	''

	insert into #EmpSickeLeave exec(@DynamicSQL + '' and d.LeaveType = ''''SL'''' group by b.SwipeCardNo,b.Employee_FirstName '' ) 
	insert into #EmpUmrahLeave exec(@DynamicSQL + '' and d.LeaveType = ''''EL'''' group by b.SwipeCardNo, b.Employee_FirstName'' ) 
	insert into #EmpOtherLeave exec(@DynamicSQL + '' and d.LeaveType not in (''''SL'''',''''EL'''') group by b.SwipeCardNo,b.Employee_FirstName'' ) 
	
	--insert into employee names table	
	insert into #EmployeeNames
	select a.SwipecardNo, b.Employee_FirstName, b.Employee_Code_Id
	from #EmpOvertime a
	inner join ta_tbl_employee b on b.SwipeCardNo = a.SwipecardNo

	-- the final table for rpt binding

	insert into #tempProjectSummary (
	EmployeeName,
	Employee_Code_Id,
	overtimeduration,
	Absentdays,
	SickeLeaves,
	UmrahLeave,
	OtherLeave)
	select 
	isnull(f.EmployeeName,''''),
	isnull(f.EmployeeCodeId,''''),
    isnull(a.overtimeduration,0),
	isnull(b.Absentdays,0),
	isnull(c.SickeLeaves,0),
	isnull(d.UmrahLeave,0),
	isnull(e.OtherLeave,0)
	from #EmpOvertime a
	left outer join #EmpAbsent b on b.SwipecardNo = a.SwipecardNo
	left outer join #EmpSickeLeave c on c.SwipecardNo = a.SwipecardNo
	left outer join #EmpUmrahLeave d on d.SwipecardNo = a.SwipecardNo
	left outer join #EmpOtherLeave e on e.SwipecardNo = a.SwipecardNo
	inner join #EmployeeNames f on f.SwipecardNo = a.SwipecardNo


	select 
	isnull(EmployeeName,'''') as EmployeeName,
	isnull(Employee_Code_Id,'''')as Employee_Code_Id,
	isnull(overtimeduration,'''') as overtimeduration,
	isnull(Absentdays,0) as Absentdays,
	isnull(SickeLeaves,0) as SickeLeaves,
	isnull(UmrahLeave,0) as UmrahLeave,
	isnull(OtherLeave,0) as OtherLeave
	from #tempProjectSummary

END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByOverTime]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PayrollByOverTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_PayrollByOverTime ''ppd.Employee_Id,ppd.HrsOT'' , ''March'',''2009'',''40'',''40,182,187,185,183,204,202,206,200,191,195,218,220,222,197,189,228,214,193,216,224,226,184,199,186,188,190,192,194,196,198,201,203,205,207,215,217,219,221,223,225,227,229'',''03''
--Proc_TA_PayrollByOverTime '''' , ''April'',''2009'',''1'',''1,2,3'',''03'',5,''SuperAdmin'',0
CREATE   PROCEDURE [dbo].[Proc_TA_PayrollByOverTime] 
(
   @SelectedFieldNames NVARCHAR(2000),
   @Month VARCHAR(20),  
   @Year INT,
   @CompanyID as int,  
   @Level as varchar(8000),
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int	
)
AS
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
declare @ToDate as nvarchar(15)
if (@mon=12)
	Begin
		set @ToDate =  ''01/'' + ''01/'' + cast(@Year+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@mon+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@Year as nvarchar(20))
	End
  set @SelectedFieldNames = replace(@SelectedFieldNames,''ppd.HrsOT'',''round (cast(replace(ppd.NormOT,'''':'''',''''.'''') as decimal) +   (round(cast(replace(ppd.NormOT,'''':'''',''''.'''') as float)- cast(replace(ppd.NormOT,'''':'''',''''.'''') as decimal),2)*100)/60,2) as HrsOT'')
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
Begin
	DECLARE @Query AS VARCHAR(8000)
--SET @Query = ''SELECT  '' + cast (@Mon as varchar(3)) + '','' + cast(@year as varchar(4)) +'','' +  @SelectedFieldNames 
--SET @Query = @Query + '' ,TA_Tbl_OtType.OTType''
--ppd.Employee_Id
--select * from TA_Tbl_OtType
SET @Query = ''SELECT  ta_tbl_employee.employee_code_id as employee_code, ''
SET @Query = @Query +  cast (@Mon as varchar(3)) + '' as pay_month ,'' + cast(@year as varchar(4)) + '' as pay_year,''
SET @Query = @Query + '' TA_Tbl_OtType.OTType as ot_type,''
--round (cast(replace(ppd.NormOT,'''':'''',''''.'''') as decimal) +   (round(cast(replace(ppd.NormOT,'''':'''',''''.'''') as float)- cast(replace(ppd.NormOT,'''':'''',''''.'''') as decimal),2)*100)/60,2) as ot_hours''
SET @Query = @Query + '' ''''overtime '' + substring(@Month,1,3) + '''''' as remarks, ''
SET @Query = @Query + '' ppd.NormOT,ppd.OffOT,ppd.HolOT''
SET @Query = @Query + '' FROM TA_Tbl_PayrollProcessDetails ppd''
SET @Query = @Query + '' inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id''
SET @Query = @Query + '' left join TA_Tbl_OtType on 1=1  ''
SET @Query = @Query + '' inner join ta_tbl_employee on ta_tbl_employee.swipecardno = ppd.Employee_Id''
SET @Query = @Query + '' inner join ta_tbl_employeelevel on ta_tbl_employee.employee_id=ta_tbl_employeelevel.employeeid''
set @Query = @Query + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
set @Query = @Query + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid ''
SET @Query = @Query + '' WHERE mc.MonthClosure_Month = '''''' + @Month  + '''''' AND ''
SET @Query = @Query + '' mc.MonthClosure_Year = '' + CAST(@Year AS NVARCHAR) +'' and ''
SET @Query = @Query + '' mc.MonthClosure_Id = '' + CAST(@intMonthClosureId AS NVARCHAR(25)) +'' and ''
SET @Query = @Query + '' TA_Tbl_OtType.OtValue = case when ppd.NormOT<>''''00:00'''' then ''''WorkingDay'''' when ppd.OffOT<>''''00:00'''' then ''''WeeklyOff'''' when ppd.HolOT<>''''00:00'''' then ''''Holiday '''' end  and  ''
SET @Query = @Query + '' TA_Tbl_OtType.isdeleted=0 and (ppd.NormOT<>''''00:00'''' or ppd.HolOT<>''''00:00'''' or ppd.OffOT<>''''00:00'''') And''
SET @Query = @Query + '' TA_Tbl_OtType.CompanyID='' + CAST(@CompanyID AS NVARCHAR) + ''''
--SET @Query = @Query + '' TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''''''+ @ToDate + '''''', 102) order by EffectiveDate desc)''
--SET @Query = @Query + '' #EmpLevel.levelid in ('' + @Level + '')''
create table #EmpOTExport
(TempId int identity(1,1),employee_code nvarchar(15),pay_month varchar(3),pay_year varchar(4),ot_type varchar(50),ot_hours nvarchar(25) default null,remarks nvarchar(200),
NormOTMins nvarchar(25),WeekOffOTMins nvarchar(25),
HolidayOTMins nvarchar(25))
insert into #EmpOTExport(employee_code,pay_month,pay_year,ot_type,remarks,NormOTMins,WeekOffOTMins,HolidayOTMins)
  EXEC(@Query) 
--select * from #EmpOTExport
declare @incr as int
declare @maxrec as int
set @incr=1
set @maxrec = (select max(TempId) from #EmpOTExport)
while(@incr<=@maxrec)
begin
	declare @hrsNormOTnv as nvarchar(25)
	declare @hrsWkOffOTnv as nvarchar(25)
	declare @hrsHOLOTnv as nvarchar(25)
	declare @dotposition as varchar(25)
	declare @length as int
	declare @hrsNormOTint as int
	declare @hrsWkOffOTint as int
	declare @hrsHOLOTint as int
	declare @minNormOTint as int
	declare @minWkOffOTint as int
	declare @minHOLOTint as int
	set @hrsNormOTnv = (select ISNULL(NormOTMins,''00:00'') from #EmpOTExport where TempId=@incr)
	set @hrsWkOffOTnv = (select ISNULL(WeekOffOTMins,''00:00'') from #EmpOTExport where TempId=@incr)
	set @hrsHOLOTnv = (select ISNULL(HolidayOTMins,''00:00'') from #EmpOTExport where TempId=@incr)
	set @dotposition = CHARINDEX('':'',@hrsNormOTnv)
	set @length = len(@hrsNormOTnv)
	set @hrsNormOTint = SUBSTRING(@hrsNormOTnv,1,@dotposition-1)
	set @minNormOTint = SUBSTRING(@hrsNormOTnv,cast(@dotposition+1 as int),@length)
	set @dotposition = CHARINDEX('':'',@hrsWkOffOTnv)
	set @length = len(@hrsWkOffOTnv)
	set @hrsWkOffOTint = SUBSTRING(@hrsWkOffOTnv,1,@dotposition-1)
	set @minWkOffOTint = SUBSTRING(@hrsWkOffOTnv,cast(@dotposition+1 as int),@length)
	set @dotposition = CHARINDEX('':'',@hrsHOLOTnv)
	set @length = len(@hrsHOLOTnv)
	set @hrsHOLOTint = SUBSTRING(@hrsHOLOTnv,1,@dotposition-1)
	set @minHOLOTint = SUBSTRING(@hrsHOLOTnv,cast(@dotposition+1 as int),@length)
	declare @otHrs as nvarchar(25)
	declare @otMins as nvarchar(25)
	declare @exportOTHrs as float
	set @otHrs = @hrsNormOTint + @hrsWkOffOTint + @hrsHOLOTint
	set @otMins = @minNormOTint + @minWkOffOTint + @minHOLOTint
	if(@otMins>=60)
		begin
			declare @minToHr as int 
			set @minToHr = @otMins / 60
			set @otHrs = @otHrs + @minToHr
			set @otMins = @otMins % 60
		end
	declare @result as nvarchar(25)
	set @result = @otHrs +'':''+@otMins
	set @exportOTHrs = @otHrs * 60
	set @exportOTHrs = @exportOTHrs + @otMins
    declare @othours as nvarchar(25)
	set @othours = (select round (cast(replace(@result,'':'',''.'') as decimal) +   (round(cast(replace(@result,'':'',''.'') as float)- cast(replace(@result,'':'',''.'') as decimal),2)*100)/60,2))
    update  #EmpOTExport set ot_hours = @othours where TempId=@incr
	--select round( cast( ((@exportOTHrs) / 60) as float) ,2) as ''hours'' 
    -- wrong result as 100%
	set @incr=@incr+1
end
select employee_code,pay_month,pay_year,ot_type,ot_hours,remarks from #EmpOTExport
drop table #EmpOTExport
  --Remove the temporary tables here
drop table #EmpLevel
drop table #LevelRights
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_PayrollByAttandance]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_PayrollByAttandance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_PayrollByAttandance ''ppd.Employee_Id,ppd.AbsentDays'' , ''March'',''2009'',''40'',''40,182,187,185,183,204,202,206,200,191,195,218,220,222,197,189,228,214,193,216,224,226,184,199,186,188,190,192,194,196,198,201,203,205,207,215,217,219,221,223,225,227,229'',''03''
CREATE   PROCEDURE [dbo].[Proc_TA_PayrollByAttandance] 
(
   @SelectedFieldNames NVARCHAR(2000),
   @Month VARCHAR(20),  
   @Year INT,
   @CompanyID as int,  
   @Level as varchar(8000),
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int 
)
AS
Begin
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
declare @ToDate as nvarchar(15)
--set @FromDate = cast(@SelectedMonth as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
if (@mon=12)
	Begin
		set @ToDate =  ''01/'' + ''01/'' + cast(@Year+1 as nvarchar(20))
	End
Else
	Begin
		set @ToDate = cast(@mon+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@Year as nvarchar(20))
	End
	DECLARE @Query AS VARCHAR(8000)
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
--SET @Query =  ''SELECT  '' +  @SelectedFieldNames + '',TA_Tbl_AttandanceCode.AttandanceCode''
--ppd.Employee_Id
SET @Query =  ''SELECT  ta_tbl_employee.employee_code_id as employee_code,''
SET @Query = @Query +  cast (@Mon as varchar(3)) + '' as pay_month ,'' + cast(@year as varchar(4)) + '' as pay_year,''
SET @Query = @Query + '' TA_Tbl_AttandanceCode.AttandanceCode as attn_code, ppd.AbsentDays as no_of_days''
SET @Query = @Query + '' ,''''auto upload'''' as remarks  FROM TA_Tbl_PayrollProcessDetails ppd inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id''
SET @Query = @Query + '' left join TA_Tbl_AttandanceCode on 1=1''  
SET @Query = @Query + '' inner join ta_tbl_employee on ta_tbl_employee.swipecardno = ppd.Employee_Id''
SET @Query = @Query + '' inner join ta_tbl_employeelevel on ta_tbl_employee.employee_id=ta_tbl_employeelevel.employeeid''
set @Query = @Query + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
set @Query = @Query + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid ''
SET @Query = @Query + '' WHERE ''
SET @Query = @Query + '' mc.MonthClosure_Month ='''''' + @Month  + '''''' AND ''
SET @Query = @Query + '' mc.MonthClosure_Year = '' + CAST(@Year AS NVARCHAR) +''  and ''
SET @Query = @Query + '' mc.MonthClosure_Id = '' + CAST(@intMonthClosureId AS NVARCHAR(25)) +'' and ''
SET @Query = @Query + '' TA_Tbl_AttandanceCode.AttandanceValue=''''Absent'''' and ''
SET @Query = @Query + '' TA_Tbl_AttandanceCode.CompanyID='' + CAST(@CompanyID AS NVARCHAR) + '' and ''
SET @Query = @Query + '' TA_Tbl_AttandanceCode.isdeleted=0 and  ppd.AbsentDays<>0.0 ''
--SET @Query = @Query + '' TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,''''''+ @ToDate + '''''', 102) order by EffectiveDate desc)''
--SET @Query = @Query + '' #EmpLevel.levelid in ('' + @Level + '')''
	EXEC(@Query)
  --Remove the temporary tables here
drop table #EmpLevel
drop table #LevelRights
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Payroll]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Payroll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_Payroll] ''convert(varchar(100),ppd.Employee_Id) as Employee_Id,convert(varchar(100),ppd.EarlyOut) as EarlyOut,convert(varchar(100),ppd.LateIn) as LateIn,convert(varchar(100),ppd.HrsLess) as HrsLess,convert(varchar(100),ppd.HrsExtra) as HrsExtra,convert(varchar(100),ppd.LeaveDays) as LeaveDays,convert(varchar(100),ppd.AbsentDays) as AbsentDays,convert(varchar(100),ppd.PresentDays) as PresentDays,convert(varchar(100),ppd.Holidays) as Holidays,convert(varchar(100),ppd.LOPDays) as LOPDays,convert(varchar(100),ppd.TotalPermissionHours) as TotalPermissionHours,convert(varchar(100),ppd.WeekOffDays) as WeekOffDays,convert(varchar(100),ppd.HrsWork) as Hours_Worked,convert(varchar(100),ppd.HrsOt) as Total_OT,convert(varchar(100),ppd.NormOt) as WeekDay_OT,convert(varchar(100),ppd.OffOT) as WeekOff_OT,convert(varchar(100),ppd.HolOT) as Holiday_OT,convert(varchar(100),ppd.WorkHrs) as Defined_WorkHours,convert(varchar(250),LD.description) as LevelCode'' , ''January'',''2019'',''1'',''1'',''1'',2,''SuperAdmin'',1,''SummarizedData''  
--[Proc_TA_Payroll] ''   Date, InTime, OutTime, EarlyOut, LateIn, HrsLess, HrsExtra, FNAttendanceCode, ANAttendanceCode, Hours_Worked, Total_OT, WeekDay_OT, WeekOff_OT, Holiday_OT, Defined_WorkHours, Employee_Id, EmployeeName, CardNo, ShiftCode, ShiftName, DateIn, DateOut, InReaderId, OutReaderId, InReaderName, OutReaderName, Remarks, LevelCode, LevelName, OverTimeType'' , ''March'',''2011'',''323'',''323'',''3'',45,''SuperAdmin'',323,''DailyData''  
CREATE   PROCEDURE [dbo].[Proc_TA_Payroll]  
(  
   @SelectedFieldNames NVARCHAR(4000),  
   @Month VARCHAR(20),  
   @Year INT,  
   @CompanyID as int,    
   @Level as varchar(1000),  
   @mon as int,
   @intMonthClosureId int,
   @UserGroupName varchar(250), 
   @ParentId int,
   @DataType varchar(50) 
)  
AS  
Begin 
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	create table #LevelRights_Company(LevelId int)
	insert into  #LevelRights_Company select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@CompanyID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	DECLARE @Query AS VARCHAR(8000)  
	declare @ToDate as nvarchar(15)  
	if (@mon=12)  
	Begin  
		set @ToDate =  ''01/'' + ''01/'' + cast(@Year+1 as nvarchar(20))  
	End  
	Else  
	Begin  
		set @ToDate = cast(@mon+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@Year as nvarchar(20))  
	End  
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	 
	if(@DataType = ''SummarizedData'')
		BEGIN
			 SET @Query = ''SELECT '' +  @SelectedFieldNames 
			 SET @Query = @Query + '' FROM  TA_Tbl_PayrollProcessDetails ppd''  
			 SET @Query = @Query + '' inner join TA_Tbl_MonthClosure mc  on mc.MonthClosure_Id = ppd.MonthClosure_Id ''  
			 SET @Query = @Query + '' inner join ta_tbl_employee e on e.swipecardno = ppd.Employee_Id ''  
			 SET @Query = @Query + '' inner join ta_tbl_employeelevel on e.employee_id=ta_tbl_employeelevel.employeeid ''  
			 SET @Query = @Query + '' inner join TA_Tbl_LevelDetails LD on ta_tbl_employeelevel.levelId=LD.Id ''  
			 set @Query = @Query + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
			 set @Query = @Query + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid ''
			 set @Query = @Query + '' Inner join #LevelRights_Company on #LevelRights_Company.LevelId=#EmpLevel.levelid ''
			 SET @Query = @Query + '' WHERE  mc.MonthClosure_Month = '''''' + @Month  + '''''' AND  ''  
			 SET @Query = @Query + '' mc.MonthClosure_Year = '' + CAST(@Year AS NVARCHAR) +''  and  ''  
			 SET @Query = @Query + '' mc.MonthClosure_Id = '' + CAST(@intMonthClosureId AS NVARCHAR(25)) +'' ''
			 Print(@Query)  
			 exec(@Query)  
		 END
	 ELSE
	 BEGIN
	    create table #TempExportData 
		(
			Date  nvarchar(50),
			DateIn nvarchar(20),
			DateOut nvarchar(20),
			InTime  nvarchar(20),
			OutTime  nvarchar(20),			
			Hours_Worked  nvarchar(20),
			Total_OT  nvarchar(20),
			WeekDay_OT  nvarchar(20),
			WeekOff_OT  nvarchar(20),
			Holiday_OT  nvarchar(20),
			EarlyOut  nvarchar(20),
			LateIn  nvarchar(20),
			Defined_WorkHours  nvarchar(20),
			HrsLess  nvarchar(20),
			HrsExtra  nvarchar(20),
			FNAttendanceCode  nvarchar(20),
			ANAttendanceCode  nvarchar(20),
			Employee_ID  nvarchar(20),
			EmployeeName nvarchar(250),
			CardNo  nvarchar(20),
			ShiftCode  nvarchar(250),
			ShiftName  nvarchar(250),
			InReaderId  nvarchar(20),
			OutReaderId  nvarchar(20),
			InReaderName  nvarchar(20),
			OutReaderName  nvarchar(20),
			LevelCode  nvarchar(250),
			LevelName nvarchar(250),
			OverTimeType  nvarchar(50),
			--AttendanceCode  varchar(50),
			Remarks  nvarchar(20)
		)
		/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempExportData] 
		(
			[Date] ASC
		) ON [PRIMARY]		
		CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]
		CREATE TABLE #TempClockDetails
		(
			[Clk_Id] int,
			[Clk_CompId] varchar(10),
			[Clk_EmpId] nvarchar(20),
			[Clk_InDeviceId] nvarchar(20),
			[Clk_InDate] datetime,
			[Clk_InTime] datetime,
			[Clk_InPunchType] nvarchar(25),
			[Clk_OutDeviceId] nvarchar(20),
			[Clk_OutDate] datetime,
			[Clk_OutTime] datetime,
			[Clk_OutPunchType] nvarchar(25),
			[Clk_Process] nvarchar(1),
			[Clk_Remarks] nvarchar(100),
			[Clk_User] nvarchar(20),
			[Clk_Date] datetime,
			[Clk_Status] char(1),
			[IsVoid] bit
	     )
	      /****** Object:  Index [IDX_Clk_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Clk_Date] ON [dbo].[#TempClockDetails] 
		(
			[Clk_Date] ASC
		) ON [PRIMARY]
		  /****** Object:  Index [IDX_Clk_EmpId]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Clk_EmpId] ON [dbo].[#TempClockDetails] 
		(
			[Clk_EmpId] ASC
		) ON [PRIMARY]
		insert into #TempProcessedData 
		select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
		[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
		[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
		inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
		where PD.Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
		--select * from #TempProcessedData
		insert into #TempClockDetails
		select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],
		[Clk_OutDate],[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
		from TA_Tbl_ClockDetails CD 
		inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
		where CD.Clk_Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
		
        insert into #TempExportData(Date,InTime,OutTime,Hours_Worked,Total_OT,WeekDay_OT,WeekOff_OT,Holiday_OT,EarlyOut,LateIn,Defined_WorkHours,HrsLess,HrsExtra,FNAttendanceCode,ANAttendanceCode,Employee_Id,EmployeeName,CardNo,ShiftCode,ShiftName,LevelCode,LevelName,OverTimeType,Remarks,InReaderId,OutReaderId,InReaderName,OutReaderName,DateIn,DateOut)  
        select isnull(PD.Date,''''),
                isnull(PD.InTime,''''),
				isnull(PD.OutTime,''''),
				isnull(PD.HrsWork,''''),
				isnull(PD.HrsOT,''00:00''),
				isnull(PD.NormOT,''00:00''),
				isnull(PD.OffOT,''00:00''),
				isnull(PD.HolOT,''00:00''),
				isnull(PD.EarlyOut,''''),
				isnull(PD.LateIn,''''),
				isnull(PD.WorkHrs,''''),
				isnull(PD.HrsLess,''''),
				isnull(PD.HrsExtra,''''),
				isnull(PD.FNAttendanceCode,''''),
				isnull(PD.ANAttendanceCode,''''),
				isnull(E.Employee_Code_ID,''''),
				isnull(isnull(E.Employee_FirstName,'''') + '' '' + isnull(E.Employee_LastName,''''),''''),
				isnull(E.SwipeCardNo,''''),
				isnull(Sht.Shift_Description,''''),
				isnull(Sht.Shift_Name,case Pd.Shift_Id when ''-1'' then ''Weekly Off'' else '''' end),
				isnull(LD.description,''''),
				isnull(LD.name,''''),
				--isnull(OT.OTType,''''),
				--isnull(AC.AttandanceCode,''''),
				'''','''','''','''','''','''','''','''' 
				from #TempProcessedData PD 
				inner join TA_Tbl_Employee E on E.SwipeCardNo = PD.Employee_Code_Id 
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeID=E.Employee_ID 
				inner join TA_Tbl_LevelDetails LD on EL.LevelId=LD.Id 
				Inner join #EmpLevel on #EmpLevel.EffectiveDate=EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
				Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelid
				Inner join #LevelRights_Company on #LevelRights_Company.LevelId=#EmpLevel.levelid 
				left join TA_Tbl_Shift Sht on PD.Shift_Id=Sht.Shift_Id 
				inner join TA_Tbl_MonthClosure MC on MonthClosure_Id=@intMonthClosureId
				--left join TA_Tbl_OtType OT on 1=1 
				--left join TA_Tbl_AttandanceCode AC on 1=1 
				--where PD.Date between MC.MonthClosure_StartDate and MC.MonthClosure_EndDate 
				where MC.IsDeleted=0 order by PD.Employee_Code_Id,PD.Date
				--and AC.AttandanceValue=''Absent'' 
				--and AC.isdeleted=0 
				--and AC.CompanyID=1 
				--and OT.Isdeleted=0 and OT.OtValue=''WorkingDay'' and OT.CompanyID=@CompanyID
				--select * from #TempExportData
				--updates the FNAttendanceCode in the #TempExportData
				update #TempExportData set FNAttendanceCode=TA_Tbl_AttandanceCode.AttandanceCode from TA_Tbl_AttandanceCode
				inner join #TempExportData on TA_Tbl_AttandanceCode.AttandanceValue=#TempExportData.FNAttendanceCode
				and TA_Tbl_AttandanceCode.CompanyID=@CompanyID and TA_Tbl_AttandanceCode.isdeleted=0
				--select * from #TempExportData
				--updates the ANAttendanceCode in the #TempExportData
				update #TempExportData set ANAttendanceCode=TA_Tbl_AttandanceCode.AttandanceCode from TA_Tbl_AttandanceCode
				inner join #TempExportData on TA_Tbl_AttandanceCode.AttandanceValue=#TempExportData.ANAttendanceCode
				and TA_Tbl_AttandanceCode.CompanyID=@CompanyID and TA_Tbl_AttandanceCode.isdeleted=0
				--select * from #TempExportData
				--updates the OverTimeType in the #TempExportData
				update #TempExportData set OverTimeType =
				case when #TempExportData.WeekDay_OT<>''00:00''
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)=''WorkingDay'' and isdeleted=0 and CompanyId=@CompanyID)
				when #TempExportData.WeekOff_OT<>''00:00''
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)=''WeeklyOff'' and isdeleted=0 and CompanyId=@CompanyID)
				when #TempExportData.Holiday_OT<>''00:00''
				then (select OTType from TA_Tbl_OtType where rtrim(OTValue)=''Holiday'' and isdeleted=0 and CompanyId=@CompanyID)
				else
				''''
				end
				--updates the Total Ot Hours in the #TempExportData
				update #TempExportData set Total_OT = case	when #TempExportData.WeekDay_OT<>''00:00'' then (WeekDay_OT)
															when #TempExportData.WeekOff_OT<>''00:00'' then (WeekOff_OT)
															when #TempExportData.Holiday_OT<>''00:00'' then (Holiday_OT)
															else ''00:00''
													  end
				--updates the terminal id for in punch in temp table
				update #TempExportData set InReaderId=isnull(Clk_InDeviceId,'''') from #TempClockDetails 
				inner join #TempExportData on Clk_EmpId=CardNo and Clk_Date=[Date] and IsVoid=0 and #TempExportData.InTime<>'''' 
				and Clk_InTime=convert(datetime,#TempExportData.InTime)
				--updates the terminal id for out punch in temp table
				
				update #TempExportData set OutReaderId=isnull(Clk_OutDeviceId,'''')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.OutTime<>'''' 
				and Clk_OutTime=convert(datetime,#TempExportData.OutTime)
				
				--updates the DateIn in the temp table
				update #TempExportData set DateIn=isnull(Clk_InDate,'''')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.InTime<>'''' and Clk_InTime=#TempExportData.InTime
				--select * from #TempExportData
				--updates the DateOut in the temp table
				update #TempExportData set DateOut=isnull(Clk_OutDate,'''')
				from #TempClockDetails inner join #TempExportData on Clk_EmpId=CardNo
				and Clk_Date=[Date] and IsVoid=0 and #TempExportData.OutTime<>'''' and Clk_OutTime=#TempExportData.OutTime
				--select * from #TempExportData
				--updates the terminal name for OUT reader id in temp table
				update #TempExportData set InReaderName=isnull(TA_Tbl_Terminal.Terminal_Name,'''')
				from TA_Tbl_Terminal inner join #TempExportData on TA_Tbl_Terminal.Terminal_ReaderId=#TempExportData.InReaderId
				--select * from #TempExportData
				---updates the terminal name for OUT reader id in temp table
				update #TempExportData set OutReaderName=isnull(TA_Tbl_Terminal.Terminal_Name,'''')
				from TA_Tbl_Terminal inner join #TempExportData on TA_Tbl_Terminal.Terminal_ReaderId=#TempExportData.OutReaderId
				--select * from #TempExportData
	    SET @Query = ''select '' + @SelectedFieldNames
		SET @Query = @Query + '' from #TempExportData ''
		exec (@Query)
		drop table #TempExportData
		drop table #TempProcessedData
		drop table #TempClockDetails
	 END
	--Remove the temporary tables here
	drop table #EmpLevel
	drop table #LevelRights
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAllException]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAllException]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_RptAllException ''787,758'',''0,1'',''2017/02/01'',''2022/02/28'',''Manikandan ,'',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''00:40'',1
CREATE PROCEDURE [dbo].[Proc_TA_RptAllException]  
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@MINExceptionHOURS AS VARCHAR(6),
	@EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@MINExceptionHOURS,0,CHARINDEX('':'',@MINExceptionHOURS))*60 + SUBSTRING(@MINExceptionHOURS,CHARINDEX('':'',@MINExceptionHOURS)+1,2)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!=''Superadmin'' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		EarlyOut nvarchar(10),
		EarlyOutMins float,
		EarlyInMins int,
		EarlyInHrs varchar(10),
		HrsExtra nvarchar(10),
		ExtraMins int
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	insert into #TempEmployee 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee emp
	inner join #EmpLevel on #EmpLevel.EmployeeId=emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 
	left join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id 
	left join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
	where SwipeCardNo is not null and emp.Isdeleted=0  and emp.report_exclude=0
	and (isnull(@EmployeeID,'''')='''' or emp.Employee_Code_Id in (select * from #EmployeeID))
	and (isnull(@EmployeeName,'''')='''' or emp.Employee_Code_Id in (select * from #EmployeeName))
	and (isnull(@Gender,''Both'')=''Both'' or emp.Gender=@Gender)
	
	insert into #TempProcessedData select	TE.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.Process_Rec_ID,
											PD.LateIn,
											PD.LateInMins,
											PD.EarlyOut,
											PD.EarlyOutMins,
											PD.EarlyInMins,
											PD.EarlyInHrs,
											PD.LateExitHours,
											PD.lateExitMins 
	from TA_Tbl_ProcessedData PD inner join #TempEmployee TE on TE.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join ta_tbl_shift S on S.Shift_Id=PD.Shift_Id
	where (PD.Date >= @FromDate AND PD.Date <= @ToDate) and 	
	(
		(isnull(LateInMins,0) > 0) or 
		(isnull(PD.EarlyOutMins,0) > 0) or 
		(EarlyInMins!=0 and (cast(S.Shift_StartTime as datetime) > cast(PD.InTime AS datetime)) AND PD.LateInMins=0 and PD.EarlyEntry=1) or 
		(lateexit=1 and PD.OutTime <> ''0'' and PD.OutTime <> ''00:00:00'' and PD.OutTime <> ''00:00'' and PD.OutTime is not null and PD.OutTime <>'''''''' and PD.lateExitMins > 0)
	) 
	and processflag=1 and(isnull(@shift,0)=0 or PD.shift_id=@shift)
	and (isnull(@MINExceptionHOURS,''00:00'')=''00:00'' or PD.LateInMins >=@TOTALExceptionMIN or PD.EarlyOutMins >=@TOTALExceptionMIN or PD.EarlyInMins >=@TOTALExceptionMIN or PD.lateExitMins >=0)
	
	Set @EmployeeName = @EmployeeName 
	SELECT PD.Process_Rec_ID,
	ED.Employee_Code_Id AS CardNo,
	ED.Employee_FirstName + '' '' + isnull(ED.Employee_LastName,'''') AS ''EmployeeName'',  
	replace(T.TitleName,''&amp;'',''&'')  AS Designation,  
	replace(L.name,''&amp;'',''&'')  AS [LevelName],
	sh.Shift_StartTime,sh.Shift_EndTime,replace(sh.shift_shortName,''&amp;'',''&'') as shift_shortName,    
	case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, Date,@dateFormat) 
	end AS Date, 	
	case	when @TimeFormat=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114),0,6)
			else	case	when len(SUBSTRING(intime,0,charindex('':'',intime)))=1 then ''0''+intime
							else InTime 
					end
	end InTime,
	case	when @TimeFormat=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114),0,6) 
			else	case	when len(SUBSTRING(OutTime,0,charindex('':'',OutTime)))=1 then ''0''+ OutTime
							else OutTime 
					end 
	end OutTime,
	LateIn as LateBy,
	LateInMins,
	EarlyOut as EarlyOutBy,
	EarlyOutMins,
	EarlyInHrs as EarlyInBy,
	EarlyInMins,
	isnull(hrsExtra,''00:00'') as LateExitBy,
	ExtraMins as lateExitMins,
	ED.Gender,
	Date as format
	FROM TA_Tbl_Employee ED 
	Inner join #EmpLevel Lev on Lev.employeeid=ED.Employee_Id 
	INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id
	Inner join #EmpDesignation  EDesig on EDesig.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID
	Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id
	INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId
	INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id
	Where 1=1
	and (@UserGroupName=''Superadmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	and (isnull(@isReportingto,0)=0 or ED.Employee_ID IN (select * from #EmployeeIds))
	AND 
	(
		(ED.employee_status=1) or 
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),Date,102))
	)
	order by CardNo,format
	--remove the temporary tables  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
 End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Reprocess_HolidayData]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Reprocess_HolidayData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 12/01/2015
-- Description:	Reprocess the past entries while creating a holidays.
-- [Proc_Ta_Reprocess_HolidayData]''2015-06-10'',''2015-06-10''
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_Reprocess_HolidayData]
	-- Add the parameters for the stored procedure here			
	@FromDate DATETIME,
	@ToDate Datetime	
AS
BEGIN
	set nocount on;
	Declare @HOLIDAYLEVELID nvarchar(max)
	set @HOLIDAYLEVELID =-1
	SELECT @HOLIDAYLEVELID=coalesce(@HOLIDAYLEVELID+'','','''')+convert(varchar(20),hct.LevelId) FROM TA_Tbl_Holiday 
	inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id	
	where 
	(
		((TA_Tbl_Holiday.Holiday_FromDate between @FromDate and @ToDate and TA_Tbl_Holiday.Isdeleted=0) 
		or 
		(TA_Tbl_Holiday.Holiday_ToDate between @FromDate and @ToDate and TA_Tbl_Holiday.Isdeleted=0))	
	) 	
	or 
	(
		((@FromDate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
	 or 
		(@ToDate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))	
	) 
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,''''
	Declare @dtFROMDate datetime
	DELETE FROM TA_Tbl_ProcessedData FROM TA_Tbl_ProcessedData PD inner join ta_tbl_employee E on PD.employee_code_id=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Date BETWEEN @FromDate AND @todate and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
	DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Clk_Date BETWEEN @FROMDate AND @ToDate and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
	SET @dtFROMDate=@fromdate
	WHILE(@dtFROMDate<=@todate)
		BEGIN
			DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
			WHERE Clk_InDate=@dtFROMDate and E.Isdeleted =0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			DELETE FROM TA_Tbl_ClockDetails FROM TA_Tbl_ClockDetails CD inner join ta_tbl_employee E on CD.Clk_EmpId=E.SwipeCardNo
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
			WHERE Clk_OutDate=@dtFROMDate and Clk_InDate is null and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			UPDATE TA_Tbl_ManualTimeEntry set Clk_Process=''N'' FROM Ta_Tbl_ManualTimeEntry MT inner join ta_tbl_employee E on MT.ManualTimeEntry_Employee_Id=E.Employee_Code_Id
			inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
            where (ManualTimeEntry_InDate = @dtFROMDate or ManualTimeEntry_OutDate = @dtFROMDate) and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
			SET @dtFROMDate=DateAdd(d,1,@dtFROMDate)
		END       
	UPDATE TA_Tbl_Clk_RawData SET Clk_Flag = 0,Clk_Process = 0 FROM TA_Tbl_Clk_RawData CR inner join ta_tbl_employee E on CR.CLK_CARDID=E.SwipeCardNo
	inner join #EmpLevel tel on tel.EmployeeId=E.Employee_Id
	WHERE Clk_Date BETWEEN DateAdd(d,-1,@FROMDate) AND DateAdd(d,1,@ToDate) and E.Isdeleted=0 and tel.LevelId in(SELECT * FROM dbo.CSVToTable(@HOLIDAYLEVELID))
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamic]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamic]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author        : Sashma  
-- Create date   : 06-July-2010  
-- Modified date : 12-May-2011  
-- Description   : <Description,,>  
--Modified By    : Thilakraj C  
-- Modified Date : 19-Jul-2013  
-- Description   : Due to Neuland requirement Check the Employee Inactivate Date.  
--Modified By    : Gopinath.k
-- Modified Date : 20-Dec-2013 & 11-Jan-2014
-- Description   :SQL Query Optimization & Emp name filtering
-- =============================================  
-- Proc_TA_RptDetailAttendanceDynamic ''01/Jan/2016'',''31/Jan/2016'',''957'','''',''0'',''SuperAdmin'',''0'','''',0,0,''Both'',0
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamic] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,  
  @DesignationID int,  
  @Gender varchar(10),   
	@ParentID bigint,
	@Export int
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	-------Start
	declare @query as varchar(8000)
	set @query=''''
	set @query = ''select isnull(Employee_FirstName,'''''''') + SPACE(1) + isnull(Employee_MiddleName,'''''''')+ SPACE(1) + isnull(Employee_LastName,'''''''')  + ''''$'''' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],''
	set @query = @query + '' ''''Present'''' = sum( 
	CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END 
	When ''''|'''' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END)+
sum( CASE FNAttendanceCode WHEN ''''CL'''' THEN case when ANAttendanceCode=''''Weekly Off'''' then
			Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END END
			WHEN ''''SL'''' THEN case when ANAttendanceCode=''''Weekly Off'''' then
			Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END END
else 0 END) + 
sum( CASE ANAttendanceCode WHEN ''''CL'''' THEN case when FNAttendanceCode=''''Weekly Off'''' then
Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END end
WHEN ''''SL'''' THEN case when FNAttendanceCode=''''Weekly Off'''' then
Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END end
else 0 END)
	,''
	set @query = @query + '' ''''Absent'''' = sum( CASE FNAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	--angler Specific
	--set @query = @query + '' ''''Weekly Off'''' = sum( CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	set @query = @query + '' ''''Weekly Off'''' = sum( case when upper(DATENAME(dw,Date)) = ''''SUNDAY'''' then CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END END) + sum(case when upper(DATENAME(dw,Date)) = ''''SUNDAY'''' then CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END END),''
	set @query = @query + '' ''''Holiday'''' = sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	set @query = @query + '' ''''CompOff'''' = sum( CASE FNAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	--set @query = @query + '' ''''LOP'''' = 
	--sum
	--(
	--	CASE	When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN	1
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''LOP'''' THEN	1	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Present'''' THEN	0.5	
	--			When FNAttendanceCode=''''Present'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''CL'''' THEN	0.5	
	--			When FNAttendanceCode=''''CL'''' and ANAttendanceCode=''''LOP'''' THEN	0.5				
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''CompOff'''' THEN	0.5	
	--			When FNAttendanceCode=''''CompOff'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''SL'''' THEN	0.5	
	--			When FNAttendanceCode=''''SL'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Holiday'''' THEN	0.5	
	--			When FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			else 0 
	--	END
	--)	 ,''
     	set @query = @query + '' ''''LOP'''' = sum( CASE FNAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	-------
	set @query = @query + '' ''''Total Late Days'''' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , ''
	set @query = @query + '' ''''Total Late Hours'''' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), ''
	--angler Specific
	set @query = @query + '' ''''Total Early Out Days'''' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , ''
	set @query = @query + '' ''''Total Early Out Hours'''' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), ''
	set @query = @query + '' ''''Total OT Days'''' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , ''
	set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE otmins WHEN otmins THEN  otmins END), ''
	set @query = @query + '' ''''Norm OT Hrs''''=sum(CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''WeekOff OT Hrs''''=sum(CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''Holiday OT Hrs''''=sum(CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''
	--For approved only
	--set @query = @query + '' ''''Total OT Days'''' =  count(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END) , ''
	--set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END), ''
	--set @query = @query + '' replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as Level,''
	--set @query = @query + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,''
	DECLARE @sql varchar(8000)
	DECLARE @sumfunc varchar(200)
	set @sumfunc = ''sum(Totaldays)''
	DECLARE @sumfunc1 varchar(100)
	declare @pivot varchar(100)
	declare @pivot1 varchar(100)
	--set @pivot =''LeaveCode''
	set @pivot =''FNAttendanceCode''
	set @pivot1 =''ANAttendanceCode''
	Declare @TotalLeaveCount Decimal(10,5)
	Set @TotalLeaveCount=0;
	---- get the leave type details and form query
	EXEC (''SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2'')
	CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
	(
	[pivot] ASC
	) ON [PRIMARY]
	exec (''INSERT INTO ##pivot select top 5 LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
	SELECT @sql='''',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, '' END)'' )
	declare @delim  varchar(1)
	SELECT  @delim=CASE Sign( CharIndex(''char'', data_type)+CharIndex(''date'', data_type) ) 
	WHEN 0 THEN '''' ELSE '''''''' END 
	FROM tempdb.information_schema.columns 
	WHERE table_name=''##pivot'' AND column_name=''pivot''
	select @sql=''''
	SELECT @sql=@sql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
	+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
	--		+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN '' ) + '', '' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
	FROM ##pivot order by [pivot]
	if len(@sql)>0
	SELECT @sql=left(@sql, len(@sql)-1)
	-- end of leave type
	---- other leave type
	declare @SelectedLeaveType as varchar(500)
	set @SelectedLeaveType =''''
	SELECT @SelectedLeaveType=@SelectedLeaveType + '''''''' + convert(varchar(100), [pivot]) + '''''' , '' 
	FROM ##pivot
	delete  from ##pivot
	if len(@SelectedLeaveType)>0
		begin
			SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
			exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0 and leavetype not in ('' + @SelectedLeaveType + '' )  order by leavetype'')
		end
	else
		begin
			exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
		end
	--delete  from ##pivot
	declare @othSql as varchar(5000)
	select @othSql=''''
	--SELECT @othSql=@othSql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
	/*		
	SELECT @othSql=@othSql + '' '' 
	+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
	FROM ##pivot order by [pivot]
	*/
	if (len(@othSql)>0) 
		begin
			SELECT @othSql=left(@othSql, len(@othSql)-1) + ''+''
		end
	set @query = @query + '' ''''Others'''' =  '' + @othSql + '' sum( CASE FNAttendanceCode WHEN ''''RH'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)''
	set @query = @query + '' + sum( CASE ANAttendanceCode WHEN ''''RH'''' THEN Case TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END),''
	set @query = @query + '' ''''CL'''' =   sum( CASE FNAttendanceCode WHEN ''''CL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''CL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END), ''
	set @query = @query + '' ''''SL'''' =   sum( CASE FNAttendanceCode WHEN ''''SL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) +sum( CASE ANAttendanceCode WHEN ''''SL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END)''
--For satoff
	--set @query=  @query + '' ,SUM(case when upper(DATENAME(dw,Date)) = ''''Saturday'''' then 
	--                                                       case when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode =''''Absent'''' and 
	--                                              ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')
	--                                              then 1 else 0 end
	--                                                else 0 end ) as ''''Saturday Off''''''
	set @query=  @query + '' ,     SUM(case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
	                                                       CASE  when FNAttendanceCode = ''''Absent'''' or ANAttendanceCode =''''Absent'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN  1
	                                                         when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode=''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN 1
	                                                         when FNAttendanceCode= ''''Weekly Off'''' and ANAttendanceCode =''''Absent''''  and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')THEN 1
	                                                         when FNAttendanceCode = ''''Weekly Off'''' and ANAttendanceCode =''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') then 1 
	  													   end 
														   else 
														      0		
														   end 
							 )   as ''''Saturday Off''''''                                                
	              --             set @query=  @query + '' , SUM(case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
															--Case when (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Weekly Off'''') then 1 
															--	 else case when ( (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Present'''') or (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Weekly Off'''') ) then 0.5  
               --                                                            else case when ( (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Present'''')  ) then 0  
															--						 else case when (ANAttendanceCode=''''Weekly Off'''' or FNAttendanceCode=''''Weekly Off'''') then 0.5
															--end 
			            --                                    end  
															--end
															--end 
								       --                    	end
               --                                                           ) as [Intimation] ''                         
	 set @query=  @query + '' , SUM(
				case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
							Case	when (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Weekly Off'''') then 1 
									else	case	when ((ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Present'''') 
													  or (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Weekly Off'''') ) then 0.5  
													else 0
													--case	when ((ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Present'''')  ) then 0  
													--			else	case	when (ANAttendanceCode=''''Weekly Off'''' or FNAttendanceCode=''''Weekly Off'''') then 0.5
													--					end 
													--	 end  
											end
									end 
					end
                                                                          ) as [Intimation] ''                                  
	--end of other leave type
	--if len(@sql)=0
	--SELECT @query=left(@query, len(@query)-1)
	--set @query  = @query + @sql
	declare @query1 as varchar(8000) 
	set @query1=''''
	set @query1 = @query1 + '' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @query1 = @query1 + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id ''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId''
	set @query1 = @query1 + '' inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId''
	set @query1 = @query1 + '' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID ''
		end
	set @query1 = @query1 + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @query1 = @query1 + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @query1 = @query1 + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId ''
	set @query1 = @query1 + '' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId ''
	set @query1 = @query1 + '' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1''
	set @query1 = @query1 + '' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
	set @query1 = @query1 + '' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel 
			--+  '' AND (ta_tbl_employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or ta_tbl_employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''') ''
		end
	if not(@EmployeeName='''')
		begin
		--	set @query1 = @query1 + '' and ta_tbl_employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		Declare @Tempname nvarchar(200)
    set @Tempname= ''(ta_tbl_employee.Employee_FirstName + '''' '''' + isnull(ta_tbl_employee.Employee_LastName,'''''''')''
	set @query1 = @query1 + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 	
		end
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @query1 = @query1 + ''And ta_tbl_employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End
	if not (@empId='''')
		begin
			set @query1 = @query1 + '' and ta_tbl_employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
	if(@DesignationID<>0)  
		 begin  
			set @query1 = @query1 + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))  
		end  
	if(@Gender<>''Both'')  
		begin  
			 set @query1 = @query1 + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		 end  
	--if(@EmpAutoId = 0)
	--	BEGIN
	--		if not(@LevelID='''' or @LevelID=''0'')
	--			begin
	--				set @query1 = @query1 + '' and #EmpLevel.LevelId IN ( '' + @LevelId + '') '' 
	--			end	
	--	END
	if(@isReportingto > 0)
		BEGIN
			set @query1 = @query1 + '' and (ta_tbl_employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	set @query1 = @query1 + '' group by  ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname''
	create table #TempFinal ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] int,[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,Others decimal(18,1),CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,Intimation DECIMAL(18,2))
	DROP TABLE ##pivot
	--exec  (@query + '' '' + @query1)
	insert into #TempFinal 
	exec  (@query + '' '' + @query1)
	--select TF.*,C.CategoryName as [Employee Category]from #TempFinal TF
	--Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	--inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	--inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId order by TF.[Employee Id] 
	--select * from #TempFinal 
    create table #TempFinal2 ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] varchar(50),[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,[Employee Category] nvarchar(500),Others decimal(18,1),CategoryId int,Intimation DECIMAL(18,2))
	Insert into #TempFinal2 
	select [Employee Name] ,[Employee Id] ,Present ,Absent ,[Weekly Off] ,
	Holiday ,CompOff ,Lop ,[Total Late Days] ,
	case when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
				+ ''0'' +convert(varchar(20),[Total Late Hours]/60) + '':0'' + CONVERT(varchar(20),[Total Late Hours]%60)  
	     when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=2 then 
	     + ''0'' +convert(varchar(20),[Total Late Hours]/60) + '':'' + CONVERT(varchar(20),[Total Late Hours]%60)
	     when len(convert(varchar(20),[Total Late Hours]/60))=2 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
	     convert(varchar(20),[Total Late Hours]/60) + '':0'' + CONVERT(varchar(20),[Total Late Hours]%60)
	else convert(varchar(20),[Total Late Hours]/60) + '':'' +CONVERT(varchar(20),[Total Late Hours]%60)  
	end 
	,[Total Early Out Days] ,[Total Early Out Hours] ,
	[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off]
	,C.CategoryName as [Employee Category],Others,C.CategoryId ,Intimation from #TempFinal TF
	Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId
	Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId 
	order by [Employee Id]	
		declare @BelowCategoryId as int
	set @BelowCategoryId=(select top 1 CategoryId from TA_Tbl_Category  order by MonToSat_WorkHrs desc,Sat_WorkHrs desc)
	update #TempFinal2 set [Saturday Off]=0 where CategoryId=@BelowCategoryId 
	update #TempFinal2 set [Intimation]=0 where CategoryId=@BelowCategoryId 
	--update #TempFinal2 set Present=Present+[Saturday Off] where [Employee Id]
	--Update #TempFinal2 Set Present =1 Where upper(DATENAME(dw,Date)) = ''''Saturday'''' THEN 
	--                                                       CASE  when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode =''''Absent'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN  1
	--                                                         when FNAttendanceCode = ''''Absent'''' and FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN 1
	--                                                         when FNAttendanceCode= ''''Weekly Off'''' and FNAttendanceCode =''''Absent''''  and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')THEN 1
	--                                                         when FNAttendanceCode = ''''Weekly Off'''' and FNAttendanceCode =''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') then 1 
	if(@Export=0)
	begin
		select [Employee Name] ,[Employee Id] ,Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,
		Holiday ,CompOff ,Lop ,[Total Late Days] ,isnull([Total Late Hours],''00:00'')[Total Late Hours]  ,[Total Early Out Days] ,[Total Early Out Hours],[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off],[Employee Category],Others,CategoryId ,Intimation from #TempFinal2
	end
	else
	begin
		select ROW_NUMBER()over(order by [Employee Id])[Sl.No],[Employee Id] ,SUBSTRING([Employee Name],0,charindex(''$'',[Employee Name]))[Employee Name],[Employee Category],Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,[Saturday Off],
		Holiday ,CompOff ,Lop ,CL,SL,isnull([Total Late Hours],''00:00'')[Total Late Hours]  ,[Total Late Days] from #TempFinal2
	end
	drop table #tempFinal
	drop table #TempFinal2
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyWagesPenalty]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyWagesPenalty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
[Proc_TA_RptDailyWagesPenalty] @FROMDAT=''2019-10-01 00:00:00'',@TODAT=''2019-10-30 00:00:00'',
@EMPLOYEENAME=N'''',@LEVELID=N'''',@EMPLOYEEID=N'''',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N''SUPERADMIN'',
@GRADELEVEL=N''0'',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N''BOTH'',@SHIFT=0,@EMPAUTOID=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyWagesPenalty]
(   
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@EMPAUTOID BIGINT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_EMPAUTOID BIGINT
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		Shift_DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		EARLYOUTMIN INT,
		CompanyID INT,
		isRemove_LateIn int,
		isRemove_EarlyOut int
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF not(@local_GENDER=''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@local_GENDER AS NVARCHAR(8)) + '''''' ''  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@local_TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@local_EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	IF NOT (@local_EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			LATEINMINS,
			EARLYOUT,
			LATEIN,
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			#EMPLEVEL.LEVELID,
			0,
			0
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  	
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and(isnull(LateInMins,0)!=0 or isnull(EarlyOutMins,0)!=0)
	order by vp.EMPLOYEE_CODE_ID,Date
	
	update #TEMPPROCESSEDDATA set CompanyID=dbo.[Func_TA_GetParentIds](CompanyID)
	,LATEINMIN=case when isRemove_LateIn=1 then 0 else LATEINMIN end
	,EARLYOUTMIN=case when isRemove_EarlyOut=1 then 0 else EARLYOUTMIN end	
	
	update #TEMPPROCESSEDDATA set isRemove_LateIn=a.rowNumber from #TEMPPROCESSEDDATA TP
	inner join
	(	
		select rowNumber=ROW_NUMBER() over(partition by EMPLOYEE_CODE_ID order by EMPLOYEE_CODE_ID,shift_date),Shift_DATE,
		EMPLOYEE_CODE_ID
		from #TEMPPROCESSEDDATA 	where LATEINMIN!=0
	)as a on (TP.EMPLOYEE_CODE_ID=a.EMPLOYEE_CODE_ID and TP.Shift_DATE=a.Shift_DATE)
	
	update #TEMPPROCESSEDDATA set isRemove_EarlyOut=a.rowNumber from #TEMPPROCESSEDDATA TP
	inner join
	(	
		select rowNumber=ROW_NUMBER() over(partition by EMPLOYEE_CODE_ID order by EMPLOYEE_CODE_ID,shift_date),Shift_DATE,
		EMPLOYEE_CODE_ID
		from #TEMPPROCESSEDDATA 	where EARLYOUTMIN!=0
	)as a on (TP.EMPLOYEE_CODE_ID=a.EMPLOYEE_CODE_ID and TP.Shift_DATE=a.Shift_DATE)
	
	--update #TEMPPROCESSEDDATA set LATEINMIN=0 where isRemove_LateIn=1	
	--update #TEMPPROCESSEDDATA set EARLYOUTMIN=0 where isRemove_EarlyOut=1	
	
	--select * from #TEMPPROCESSEDDATA 
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		Shift_DATE DATETIME,
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		CompanyID INT,
		Category int,
		BasicSalary decimal(18,3) default(0),
		LateInDeduction decimal(18,3) default(0),
		EarlyOutDeduction decimal(18,3) default(0),
		WhichDuration int default(0),
		Whichpercentage int default(0)
	)
	
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''''''') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&'''') AS BRANCHNAME,
	REPLACE(T.TITLENAME,''''&AMP;'''',''''&'''') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.Shift_DATE,101) AS DATE,
	PD.EARLYOUT,
	PD.LATEIN,
	LATEINMIN,
	EARLYOUTMIN,
	CompanyID,
	E.penalty,
	E.Basic_Salary,0,0,0,0''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID ''
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.Shift_DATE,102)) )
		AND((PD.Shift_DATE >= CONVERT(DATETIME, '''''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + '''''', 102) AND PD.Shift_DATE <= CONVERT(DATETIME, '''''' + CAST(@local_TODAT AS NVARCHAR(11)) + '''''', 102)))''    
	IF(@local_USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @local_GRADELEVEL + ''''  
		END	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	
	update #TEMPMONTHLYATTENDANCE set Category=case when Category=0 then 2 else Category end
	
	--select * from #TEMPMONTHLYATTENDANCE where EMPLOYEE_ID=7
	
	--SELECT t1.EMPLOYEE_ID,NOoftimes=CASE WHEN t1.Category=1 then
	--						CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
	--								WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
	--								WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 3
	--								ELSE 0
	--						END
	--					when t1.Category=0 then 
	--						CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 4 
	--								WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 5 
	--								WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 6
	--								ELSE 0
	--						END
	--					ELSE 0
	--				END,				
	--				Day1,Day2,Day3,Day4,Day5,Day6,Day7,Day8,Day9,Day10,Day11,Day12,Shift_DATE
	--		from #TEMPMONTHLYATTENDANCE t1 
	--		inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
	--		where (isnull(LATEINMIN,0)!=0)and t1.EMPLOYEE_ID=7
	
	
	--As per cleint requisition the value 30 mentioned as defualt value on 14-Oct-2019 10:52 AM by Manikandan.RR
	Update #TEMPMONTHLYATTENDANCE set LateInDeduction=(isnull(BasicSalary,0)/30.0) 
	*
	(CASE	WHEN NOoftimes=1 and ROWNUMBER=1	THEN Day1/100.0
			WHEN NOoftimes=1 and ROWNUMBER=2	THEN Day2/100.0
			WHEN NOoftimes=1 and ROWNUMBER=3	THEN Day3/100.0
			WHEN NOoftimes=1 and ROWNUMBER>=4	THEN Day4/100.0
			WHEN NOoftimes=2 and ROWNUMBER=1	THEN Day5/100.0
			WHEN NOoftimes=2 and ROWNUMBER=2	THEN Day6/100.0
			WHEN NOoftimes=2 and ROWNUMBER=3	THEN Day7/100.0
			WHEN NOoftimes=2 and ROWNUMBER>=4	THEN Day8/100.0
			when NOoftimes=3 and ROWNUMBER=1	THEN Day9/100.0
			when NOoftimes=3 and ROWNUMBER=2	THEN Day10/100.0
			when NOoftimes=3 and ROWNUMBER=3	THEN Day11/100.0
			when NOoftimes=3 and ROWNUMBER>=4	THEN Day12/100.0
			
			WHEN NOoftimes=4 and ROWNUMBER=1	THEN Day1/100.0
			WHEN NOoftimes=4 and ROWNUMBER=2	THEN Day2/100.0
			WHEN NOoftimes=4 and ROWNUMBER=3	THEN Day3/100.0
			WHEN NOoftimes=4 and ROWNUMBER>=4	THEN Day4/100.0
			WHEN NOoftimes=5 and ROWNUMBER=1	THEN Day5/100.0
			WHEN NOoftimes=5 and ROWNUMBER=2	THEN Day6/100.0
			WHEN NOoftimes=5 and ROWNUMBER=3	THEN Day7/100.0
			WHEN NOoftimes=5 and ROWNUMBER>=4	THEN Day8/100.0
			when NOoftimes=6 and ROWNUMBER=1	THEN Day9/100.0
			when NOoftimes=6 and ROWNUMBER=2	THEN Day10/100.0
			when NOoftimes=6 and ROWNUMBER=3	THEN Day11/100.0
			when NOoftimes=6 and ROWNUMBER>=4	THEN Day12/100.0
	END)
	,WhichDuration=NOoftimes,
	Whichpercentage=ROWNUMBER
	from #TEMPMONTHLYATTENDANCE MA
	inner join	
	(
		SELECT *,ROWNUMBER=ROW_NUMBER()OVER(PARTITION BY a.NOoftimes ORDER BY EMPLOYEE_ID,Shift_DATE) from
		(
			SELECT t1.EMPLOYEE_ID,NOoftimes=CASE WHEN t1.Category=1 then
							CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
									WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
									WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 3
									ELSE 0
							END
						when t1.Category=2 then 
							CASE	WHEN t1.LATEINMIN between t.StartTime1Mins and t.EndTime1Mins THEN 4 
									WHEN t1.LATEINMIN between t.StartTime2Mins and t.EndTime2Mins THEN 5 
									WHEN t1.LATEINMIN between t.StartTime3Mins and t.EndTime3Mins then 6
									ELSE 0
							END
						ELSE 0
					END,				
					Day1,Day2,Day3,Day4,Day5,Day6,Day7,Day8,Day9,Day10,Day11,Day12,Shift_DATE
			from #TEMPMONTHLYATTENDANCE t1 
			inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
			where (isnull(LATEINMIN,0)!=0)
		)AS A
	)AS B on (MA.EMPLOYEE_ID=B.EMPLOYEE_ID and MA.Shift_DATE=B.Shift_DATE)
	where (isnull(LATEINMIN,0)!=0)
	
	--select * from #TEMPMONTHLYATTENDANCE where EMPLOYEE_ID=7
	
	Update #TEMPMONTHLYATTENDANCE set EarlyOutDeduction=(BasicSalary/30) 
	*
	(CASE	WHEN ROWNUMBER=1	THEN Day1/100.0
			WHEN ROWNUMBER=2	THEN Day2/100.0
			WHEN ROWNUMBER=3	THEN Day3/100.0
			WHEN ROWNUMBER>=4	THEN Day4/100.0			
	END)
	from #TEMPMONTHLYATTENDANCE MA
	inner join		
	(
		SELECT t1.EMPLOYEE_ID,ROWNUMBER=
					CASE	WHEN t1.EARLYOUTMIN between t.StartTime1Mins and t.EndTime1Mins THEN 1 
									WHEN t1.EARLYOUTMIN between t.StartTime2Mins and t.EndTime2Mins THEN 2 
									WHEN t1.EARLYOUTMIN between t.StartTime3Mins and t.EndTime3Mins then 3
									ELSE 0
							END,
			Day1,Day2,Day3,Day4,Shift_DATE
			from #TEMPMONTHLYATTENDANCE t1 
			inner join ta_tbl_PenaltyPercentage t on (t1.CompanyId=t.companyid and t.categoryID=t1.Category)
		where (isnull(EARLYOUTMIN,0)!=0)		
	)AS B on (MA.EMPLOYEE_ID=B.EMPLOYEE_ID and MA.Shift_DATE=B.Shift_DATE)
	where (isnull(EARLYOUTMIN,0)!=0)
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	
	SELECT	
	[Employee ID]=EMPLOYEE_ID,
	[Employee Name]=EMPNAME,
	Designation,
	Department=BRANCHNAME,
	[Shift Date]=CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, Shift_DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, Shift_DATE, @DATEFORMAT) END,		
	[Late Hours]=LATEIN,
	LateInDeduction=isnull(LateInDeduction,0),
	[Early Out Hours]=EARLYOUT,
	EarlyOutDeduction=isnull(EarlyOutDeduction,0),
	[Total Amount]=isnull(LateInDeduction,0)+isnull(EarlyOutDeduction,0)
	--,
	--LATEINMIN,	
	--EARLYOUTMIN,	
	--Category,
	--BasicSalary,	
	--WhichDuration,
	--Whichpercentage
	FROM #TEMPMONTHLYATTENDANCE 
	where (LateInDeduction!=0 or EarlyOutDeduction!=0)
	ORDER BY EMPLOYEE_ID,CONVERT(datetime,Shift_DATE)
	
	SELECT	
	[Employee ID]=EMPLOYEE_ID,
	[Employee Name]=EMPNAME,
	Designation,
	Department=BRANCHNAME,
	[Month of Deduction]=datename(month,Shift_DATE),
	TotalLateIn=ISNULL(dbo.ConvertMinsToHours(SUM(isnull(LATEINMIN,0))),''00:00''),	
	LateInDeduction=CONVERT(DECIMAL(18,3),SUM(isnull(LateInDeduction,0))),
	TotalEarlyOut=ISNULL(dbo.ConvertMinsToHours(SUM(isnull(EARLYOUTMIN,0))),''00:00''),
	EarlyOutDeduction=CONVERT(DECIMAL(18,3),SUM(isnull(EarlyOutDeduction,0))),
	[Total Amount]=CONVERT(DECIMAL(18,3),SUM(isnull(LateInDeduction,0)))+CONVERT(DECIMAL(18,3),SUM(isnull(EarlyOutDeduction,0))),
	MonthNo=datepart(month,Shift_DATE)
	FROM #TEMPMONTHLYATTENDANCE where (LateInDeduction!=0 or EarlyOutDeduction!=0)
	GROUP BY EMPLOYEE_ID,EMPNAME,Designation,BRANCHNAME,datename(month,Shift_DATE),datepart(month,Shift_DATE)
	ORDER BY EMPLOYEE_ID,datepart(month,Shift_DATE)
	
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission_email]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyPermission_email]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_RptDailyPermission ''01/Jun/2010'',''3'',''P'',0,0,0,3,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyPermission_email]
 (    
    @fromDat datetime,	
	@LevelID varchar(8000),	
	@Type varchar(1),
	@EmpAutoId bigint,
	@ReportingTo bigint,
	@SanctioningAuthority bigint,
    @ParentId int,
	@UserGroupName varchar(250)
 )
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
(
	[PayId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''''		
		set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_MiddleName,'''''''')  +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation,TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,convert(varchar(5),DateAdd(minute,datediff(mi,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime),0),108) as TotalHours from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''		
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID''
   		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''		
		set @sqlQuery = @sqlQuery + '' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 and e.employee_Status=1	and TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) ''
		if (@Type=''U'')
			begin
				set @sqlQuery = @sqlQuery + '' And (TA_Tbl_Permission.UnPlanned=1) and TA_Tbl_Permission.Permission_Status<>''''Rejected'''' ''
			End
		else
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_Permission.Permission_Status<>''''Rejected'''' and (TA_Tbl_Permission.UnPlanned=0) and (TA_Tbl_Permission.UnPlanned is not null) ''
			End
			if(@EmpAutoId > 0)
		   BEGIN
			  set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
		   END
		   --based on reporting to
			if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + '' and e.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
		  end  
		   --based on Sanctioning Person to
			if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + '' and e.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
		  end  
		   --based on Sanctioning Person to
			if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
		  begin  
		   set @sqlQuery = @sqlQuery + '' and e.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
		   set @sqlQuery = @sqlQuery + '' and e.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
		  end  
		set @sqlQuery = @sqlQuery + '' Group by TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_MiddleName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName order by TA_Tbl_Permission.Permission_Date, Ta_Tbl_levelDetails.name,e.Employee_Code_Id,e.Employee_FirstName,TA_Tbl_Title.TitleName ASC''	
	        exec(@sqlQuery)
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #EmpPay
drop table #EmployeeIds
drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyPermission]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_RptDailyPermission ''01/Jun/2010'',''3'',''P'',0,0,0,3,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyPermission]
(    
	@fromDat datetime,	
	@LevelID varchar(8000),	
	@Type varchar(1),
	@EmpAutoId bigint,
	@ReportingTo bigint,
	@SanctioningAuthority bigint,
	@ParentId int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
	[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
	[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Basic Pay Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
	(
	[PayId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
		--Employee Level insert in Temporary table
		insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) ELevel
		inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null
		--Employee Designation insert in Temporary table
		insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null
		--Employee Type insert in Temporary table
		insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null
		--Employee Category insert in Temporary table
		insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		--Employee Pay insert in Temporary table
		insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
		select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
		inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpBpay
		inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
		AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(MAX)
		set @sqlQuery=''''		
		set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_MiddleName,'''''''')  +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation,TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,convert(varchar(5),DateAdd(minute,datediff(mi,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime),0),108) as TotalHours from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''		
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''		
		set @sqlQuery = @sqlQuery + '' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 and e.employee_Status=1	and TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) ''
		if (@Type=''U'')
			begin
				set @sqlQuery = @sqlQuery + '' And (TA_Tbl_Permission.UnPlanned=1) and TA_Tbl_Permission.Permission_Status<>''''Rejected'''' ''
			End
		else
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_Permission.Permission_Status<>''''Rejected'''' and (TA_Tbl_Permission.UnPlanned=0) and (TA_Tbl_Permission.UnPlanned is not null) ''
			End
		if(@EmpAutoId > 0)
			BEGIN
				set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
		--based on reporting to
		if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + '' and e.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
			end  
		--based on Sanctioning Person to
		if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + '' and e.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
			end  
		--based on Sanctioning Person to
		if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
			begin  
				set @sqlQuery = @sqlQuery + '' and e.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
				set @sqlQuery = @sqlQuery + '' and e.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
			end  
		set @sqlQuery = @sqlQuery + '' Group by TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_MiddleName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName order by TA_Tbl_Permission.Permission_Date, Ta_Tbl_levelDetails.name,e.Employee_Code_Id,e.Employee_FirstName,TA_Tbl_Title.TitleName ASC''	
		exec(@sqlQuery)
		--Remove the temporary tables here  
		drop table #EmpLevel
		drop table #EmpDesignation
		drop table #EmpType
		drop table #EmpCategory
		drop table #EmpPay
		drop table #EmployeeIds
		drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves_Email]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeaves_Email]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- [Proc_TA_RptDailyLeaves] ''01/May/2014'',''3'',''P'',0,0,0,3,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeaves_Email]  
 @fromDat datetime,  
 @LevelID varchar(8000),  
 @IntimationType varchar(1),  
 @EmpAutoId bigint,
 @ReportingTo bigint,
 @SanctioningAuthority bigint,
 @ParentId int,
 @UserGroupName varchar(250)
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
--Temporary table''s creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
 --Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.  
 create table #EmployeeIds(EmpAutoId int)  
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId    
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Basic Pay Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay]   
(  
 [PayId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--Employee Pay insert in Temporary table  
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (  
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep  
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpBpay  
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId  
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null  
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''''    
  set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, ''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''  
  set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name''  
  set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''  
  set @sqlQuery = @sqlQuery + '' left outer JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''  
     set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''  
  set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '' 
   set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''	 
 --dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' and   
  set @sqlQuery = @sqlQuery + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''  
  set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '' 
  set @sqlQuery = @sqlQuery + '' AND ((dbo.TA_Tbl_LeaveApplication.Leave_FromDate >= CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) ) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate >=CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))  + '''''', 102)  ))''  
  --      if(@EmpAutoId = 0)  
		--	  BEGIN   
		--		   if not(@LevelID='''' or @LevelID=''0'')  
		--		   begin  
		--			set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''  
		--		   end   
		--	  END  
		--ELSE  
 if(@EmpAutoId > 0)
	BEGIN  
		set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''    
	END  
  if (@IntimationType=''P'') --planned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.status<>''''Rejected'''' and TA_Tbl_LeaveApplication.IntimationType=''''P'''' ''   end    
  if (@IntimationType=''U'') -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.status<>''''Rejected'''' and  TA_Tbl_LeaveApplication.IntimationType <> ''''P'''' ''  
  end  
   --based on reporting to
    if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
  end  
create table #EmpLeave(Employee_Id varchar(15),  
applicationDate datetime,  
fromDate datetime,  
todate datetime,  
NumberOfDays decimal(18,1),  
leavetype varchar(100),  
Leave_SessionFrom varchar(100),  
Leave_SessionTo varchar(100),  
Reason varchar(1050),  
status varchar(50),  
Remarks varchar(1050),  
TitleName varchar(500),  
empname varchar(500),  
[name] varchar(500),  
)  
insert into #EmpLeave exec(@sqlQuery)  
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)  
select empname as ''Executive Name'',name as Department,fromDate as ''FromDate'',toDate as ToDate,  
NumberOfDays, Leave_SessionFrom, Leave_SessionTo,status  
 from #EmpLeave order by fromDate,name,Employee_Id asc  
--select * from #EmpLeave order by Employee_Id,fromDate asc  
drop table #EmpLeave  
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #EmpPay  
drop table #EmployeeIds  
	 drop table #LevelRights
END ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyLeaves]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyLeaves]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- [Proc_TA_RptDailyLeaves] ''01/May/2014'',''3'',''P'',0,0,0,3,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyLeaves]  
 @fromDat datetime,  
 @LevelID varchar(8000),  
 @IntimationType varchar(1),  
 @EmpAutoId bigint,
 @ReportingTo bigint,
 @SanctioningAuthority bigint,
 @ParentId int,
 @UserGroupName varchar(250)
AS  
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
--Temporary table''s creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
 --Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.  
 create table #EmployeeIds(EmpAutoId int)  
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId    
 insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Basic Pay Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay]   
(  
 [PayId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EL.LevelId is not null  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--Employee Pay insert in Temporary table  
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (  
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep  
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpBpay  
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId  
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and EPay.PayId is not null  
  declare @sqlQuery as varchar(8000)  
  set @sqlQuery = ''''    
  set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, dbo.TA_Tbl_LeaveApplication.Status, ''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''  
  set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name''  
  set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''  
  set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''  
  set @sqlQuery = @sqlQuery + '' left outer JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''  
     set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''  
  set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''  
  set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId '' 
   set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''	 
 --dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' and   
  set @sqlQuery = @sqlQuery + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''  
  set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '' 
  set @sqlQuery = @sqlQuery + '' AND ((dbo.TA_Tbl_LeaveApplication.Leave_FromDate >= CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) ) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate >=CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))  + '''''', 102)  ))''  
  --      if(@EmpAutoId = 0)  
		--	  BEGIN   
		--		   if not(@LevelID='''' or @LevelID=''0'')  
		--		   begin  
		--			set @sqlQuery = @sqlQuery + '' and #EmpLevel.LevelId IN ('' + @LevelID  + '')''  
		--		   end   
		--	  END  
		--ELSE  
 if(@EmpAutoId > 0)
	BEGIN  
		set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''    
	END  
  if (@IntimationType=''P'') --planned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.status<>''''Rejected'''' and TA_Tbl_LeaveApplication.IntimationType=''''P'''' ''   end    
  if (@IntimationType=''U'') -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_LeaveApplication.status<>''''Rejected'''' and  TA_Tbl_LeaveApplication.IntimationType <> ''''P'''' ''  
  end  
   --based on reporting to
    if (@ReportingTo!=0 and @SanctioningAuthority=0) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
  end  
   --based on Sanctioning Person to
    if (@SanctioningAuthority!=0 and @ReportingTo!=0 ) -- unplanned leave  
  begin  
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Leave_Sanc_Authority = '' + cast(@SanctioningAuthority as nvarchar(50)) 
   set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Reporting_To = '' + cast(@ReportingTo as nvarchar(50)) 
  end  
create table #EmpLeave(Employee_Id varchar(15),  
applicationDate datetime,  
fromDate datetime,  
todate datetime,  
NumberOfDays decimal(18,1),  
leavetype varchar(100),  
Leave_SessionFrom varchar(100),  
Leave_SessionTo varchar(100),  
Reason varchar(1050),  
status varchar(50),  
Remarks varchar(1050),  
TitleName varchar(500),  
empname varchar(500),  
[name] varchar(500),  
)  
insert into #EmpLeave exec(@sqlQuery)  
--exec(@sqlQuery+@sqlESIDays+@sqlCompDays+@sqlLOPDays)  
select empname as ''Executive Name'',name as Department,fromDate as ''FromDate'',toDate as ToDate,  
NumberOfDays, Leave_SessionFrom, Leave_SessionTo,status  
 from #EmpLeave order by fromDate,name,Employee_Id asc  
--select * from #EmpLeave order by Employee_Id,fromDate asc  
drop table #EmpLeave  
--Remove the temporary tables here    
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #EmpPay  
drop table #EmployeeIds  
	 drop table #LevelRights
END ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_processeddata where employee_code_id=''222'' and date between ''05-01-2012'' and ''06-30-2012'' and (fnattendancecode=''CL'' 
--or ANAttendanceCode=''CL'')
-- =============================================
-- Author:		Sashma
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modifyied By :	Manjula.P
-- Date			:	09-JUL-2013
-- Description	:	for adding # for indicating manual time entry
-- Modified By	:	Manjula.P
-- Date			:	23-Nov-2013
-- Descriptions	:	Changing CO into C notation for compoff  "C" for Splitting IN and OUT with "O" symbol in formula field. Then also "C" only in Muster roll summary report but not in  Muster roll details 
-- =============================================
--select * from ta_tbl_leavetype
--	Proc_TA_RptEmployeeInOutDetails_Detailed '''','''',''3'',''0'',''0'',''SuperAdmin'',''0'','''',3,'''',''Both'',''2013/01/01'',''2013/01/30''
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_Detailed] 
	 @EmployeeId varchar(50),
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000), 	 
	 @employeeCategory nvarchar(50),
	 @employeeType nvarchar(50)	,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20)	,
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @FromDate1 varchar(50),
	 @ToDate1 varchar(50)	
AS
BEGIN
	Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	Declare @SQLDays nvarchar(2000)
	Declare @SQLFN nvarchar(2000)
	Declare @SQLAN nvarchar(2000)
	Declare @SQL3 varchar(2000)
	Declare @SQL1 varchar(2000)
	set @Fromdate2 = @Fromdate1
	set @Diff = datediff(d,@Fromdate1,@Todate1) + 1
	set @Count=1
	set @SQLDays=''''	
	set @SQLAN=''''
	set @SQLFN =''''
	set @SQLFN = ''F_Day'' + cast(@Count as varchar(10)) + '' nvarchar(100) DEFAULT ''''''''''
	set @SQLDays= @SQLDays + ''Day'' + cast(@Count as varchar(10)) + '' int''
	set @Count=@Count +1
	set @SQL3=''''
	create table #TempHeader(id int)
	while(@Count <=31)
		begin
			set @SQLFN  = @SQLFN + '',F_Day''+ cast(@Count as nvarchar(10)) + '' nvarchar(100) DEFAULT ''''''''''
			set @SQLDays = @SQLDays + '',Day'' + cast(@Count as varchar(10)) + '' int''
			set @Fromdate2=dateadd(d,1,@Fromdate2)
			set @Count=@Count +1
		end	
	set @SQL3 = @SQL3 + ''alter table #TempHeader add ''
	set @SQL3 = @SQL3 + @SQLDays 
	exec(@SQL3)
	Create table #tempClockData(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData1(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData2(Employee_Code_id varchar(50),Date datetime)
	Create table #tempClockData3(Employee_Code_id varchar(50),Date datetime)
	insert into #tempClockData 	select Clk_EmpId,min(Clk_Date) from TA_Tbl_ClockDetails c Right Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=c.Clk_EmpId 
	where (c.Clk_InTime is not null or c.Clk_OutTime is not null) group by Clk_EmpId 
	insert into #tempClockData1	select Employee_Code_Id,MIN(date) from TA_Tbl_ProcessedData 
	where (ANAttendanceCode not in(''Absent'',''Holiday'',''RH'',''Weekly Off'') or FNAttendanceCode not in(''Absent'',''Holiday'',''RH'',''Weekly Off'')) 
	or(InTime is not null or OutTime is not null) group by Employee_Code_Id 	 		
	insert into #tempClockData2 	
	select T1.Employee_Code_id,case when T1.Date<T.Date then T1.Date else T.Date end from #tempClockData T inner join #tempClockData1 T1 
	on T.Employee_Code_id=T1.Employee_Code_id group by T1.Employee_Code_id,T1.Date,T.Date
	insert into #tempClockData2
	select Employee_Code_id,DATE from #tempClockData1 where Employee_Code_id not in(select Employee_Code_id from #tempClockData)	
	insert into #tempClockData3	select SwipeCardNo,'''' from ta_tbl_employee E 
	where SwipeCardNo not in(select distinct Employee_Code_Id from #tempClockData2)	
	insert into #TempHeader(id) values(1)
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,LevelId int,date datetime,
		Otmins numeric(18,1),TotalDays numeric(18, 1),Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,Designation nvarchar(250) ,
		empname nvarchar(50) ,Father_Name nvarchar(50),DesignationID int,Grade_Level int
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50) ,FatherName nvarchar(50) ,Designation nvarchar(250) , 
		Employee_Code_Id nvarchar(15) ,Present numeric(18,1),Absent numeric(18,1),
		Leave numeric(18,1),
		Holiday numeric(18,1)default(0.0),
		TotalOT numeric(18,1),
		CountDays  numeric(18,1) default(0.0),DesignationID int,Grade_Level int
	)
	set @SQL1=''''
	set @SQL1 = @SQL1 + ''alter table #AllEmpInOutDetails add ''
	set @SQL1 = @SQL1 + @SQLFN 	
	exec(@SQL1)
	--select * from #AllEmpInOutDetails
	create table #LeaveCount(Employee_code_Id nvarchar(15) ,LeaveCount numeric(18,1))
	create table #OTMins(Employee_code_Id nvarchar(15) ,OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15) ,NFHolidays numeric(18,1))
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15) ,Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15) ,FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15) ,FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15) ,FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),OtMins float,TotalDays numeric(18, 1),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20)
	,earlyoutmins varchar(20),LateInmins varchar(20),HrsWork varchar(20),ShiftId int,Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20) ) 
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
	(
	[Grade_Id] ASC
	) ON [PRIMARY]
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102) and EL.LevelId is not null
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(cast(9+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(2009 as nvarchar(20)) as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime 
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,cast(@FromDate1 as nvarchar(50)), 102) and Date <=CONVERT(DATETIME,cast(@ToDate1 as nvarchar(50)), 102)
	update #TempProcessedData set anattendanceCode='''',fnattendanceCode='''' from #TempProcessedData TP
	inner join #tempClockData2 TC on TP.Employee_Code_Id=TC.Employee_Code_id where TP.Date<TC.Date	
	update #TempProcessedData set anattendanceCode='''',fnattendanceCode='''' from #TempProcessedData TP
	where Employee_Code_Id in(select Employee_Code_Id from #tempClockData3 TC)
	Set @EmployeeName = isnull(@EmployeeName,'''') + ''%''
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery2=''''
	set @sqlQuery =''Insert into #EmpInOutDetails select TA_Tbl_Employee.Employee_code_id,#EmpLevel.LevelId,''  	
	set @sqlQuery = @sqlQuery + '' #TempProcessedData.date, #TempProcessedData.OtMins, #TempProcessedData.TotalDays,''
	set @sqlQuery = @sqlQuery + '' Attendance1 = case #TempProcessedData.Attendance ''
	set @sqlQuery = @sqlQuery + '' when ''''Present'''' then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) end''
	set @sqlQuery = @sqlQuery + '' when ''''Absent'''' then ''''A'''' ''	
	set @sqlQuery = @sqlQuery + '' when ''''Holiday'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**H'''' else ''''H'''' end''
	set @sqlQuery = @sqlQuery + '' when ''''RH'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**RH'''' else  ''''RH'''' end''	
	set @sqlQuery = @sqlQuery + '' when ''''Comp Off'''' then ''''C'''' ''
	set @sqlQuery = @sqlQuery + '' when ''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end ''
	set @sqlQuery = @sqlQuery + '' when ''''CL'''' then ''''<b>L</b>'''' ''
	set @sqlQuery = @sqlQuery + '' end ''
	set @sqlQuery = @sqlQuery + '' ,Attendance2 = cast(isnull('''' i:'''' +#TempProcessedData.InTime,'''''''')as nvarchar)  +  cast(isnull('''' O:'''' + #TempProcessedData.OutTime,'''''''') as nvarchar)''
	set @sqlQuery = @sqlQuery + '' ,Attendance = case  when fnattendanceCode=''''Present'''' and isnull(mdIn.ManualTimeEntry_Id,0)=0 then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
    					  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
						  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
						  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) end''
--for adding manual time entry intime and outtime for fore noon by manjula.P on 27-Jun-2013
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Present'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''''''')<>''''''''  and isnull(#TempProcessedData.InTime,'''''''')!='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')<>''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' #'''' + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #'''' 
		 end ''
   set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Present'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')<>'''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')=''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' #'''' + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
		 end ''
  set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Present'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')<>''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #'''' 
		 end ''
   set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Present'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and isnull(mdIn.ManualTimeEntry_InDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')=''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) 
		 end ''
	-------------------------------------------------------------------------------------------			
	set @sqlQuery = @sqlQuery + '' when  fnattendancecode=''''Absent''''  then ''''A'''' ''	
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end''		
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Holiday'''' and anattendanceCode<>''''Holiday'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**H'''' else ''''H''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Holiday'''' and anattendanceCode=''''Holiday''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**H'''' else ''''H''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''RH'''' and anattendanceCode<>''''RH'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**RH'''' else ''''RH''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''RH'''' and anattendanceCode=''''RH''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**RH'''' else  ''''RH''''	 end''	
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Comp Off''''  then ''''C'''' ''	
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode is null  then ''''''''	''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''CL'''' then ''''<b>L</b>'''' ''
	set @sqlQuery = @sqlQuery + '' end + '''''''' + isnull( ''
	set @sqlQuery = @sqlQuery + ''case  ''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=anattendanceCode then null''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' and isnull(mdOut.ManualTimeEntry_Id,0)=0  then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' )then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  else  '''' /'''' +   cast(isnull('''' i:'''' +#TempProcessedData.InTime,'''''''')as nvarchar)  +  cast(isnull('''' O:'''' + #TempProcessedData.OutTime,'''''''') as nvarchar)end''
	  --for adding manual time entry intime and outtime for fore noon by manjula.P on 27-Jun-2013
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')!='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')<>''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' #'''' + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #'''' 
		 end ''
   set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')<>'''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')=''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  +'''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' #''''  + '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' #'''' + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
		 end ''
  set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')<>''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #''''
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)+ '''' #'''' 
		 end ''
   set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and isnull(mdOut.ManualTimeEntry_OutDate,'''''''')<>'''''''' and isnull(#TempProcessedData.InTime,'''''''')='''''''' and  
	isnull(#TempProcessedData.OutTime,'''''''')=''''''''
	then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) 
					then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)+ '''' O*:''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
			  else '''' i:'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) + '''' O:'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) 
		 end ''
	--------------------------------------------------------------------------------------------
	set @sqlQuery = @sqlQuery + '' when  anattendancecode=''''Absent''''  then ''''/A'''' ''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Weekly Off''''  then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''')then ''''**Off'''' else ''''/Off'''' end''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Holiday'''' then  case when (OutTime is not null and OutTime<>''''00:00'''' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''''**H'''' else ''''/H''''	 end''	  	
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''RH'''' then  case when (OutTime is not null and OutTime<>''''00:00'''' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''''**RH'''' else ''''/RH''''	 end''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Comp Off''''  then ''''/C'''' ''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode is null  then '''''''' ''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''CL'''' then ''''/<b>L</b>''''''
	set @sqlQuery = @sqlQuery + '' end ,'''''''')''
	set @sqlQuery = @sqlQuery + ''  ,#TempProcessedData.employee_code_id, Replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''''''') as empname, ta_tbl_employee.Father_Name ''   
	set @sqlQuery = @sqlQuery + '' ,TA_Tbl_Title.TitleId,TA_Tbl_Grade.Grade_Level FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId ''  	
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sqlQuery  = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''	
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	--*********By Manjula.P on 09-Jul-2013 for joining Manual time entry notation.
    set @sqlQuery = @sqlQuery + '' left outer join TA_Tbl_ManualTimeEntry mdIn on mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date
	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''''Approved'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''''Y'''' and mdIn.IsOnDuty=''''0''''
	left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''''Approved'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''''Y''''  and mdOut.IsOnDuty=''''0''''  '' 
	--****************************************************************************.
	set @sqlQuery = @sqlQuery + '' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )''  	
	if(@UserGroupName<>''SuperAdmin'')
		begin	
			SET @sqlQuery2 = @sqlQuery2 + ''	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)''
		end
	if (@EmployeeName<>'''')  
		begin  	
			set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_Employee.Employee_FirstName + case when TA_Tbl_Employee.Employee_MiddleName is not null then '''' '''' + cast(TA_Tbl_Employee.Employee_MiddleName as varchar(50)) else '''' '''' end + isnull(TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + @EmployeeName + '''''' ''
		end  
	If (@EmpSwipeCard <> '''')  
		Begin  
			Set @sqlQuery2 = @sqlQuery2 + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	if (@EmployeeId<>'''')  
		begin  
			set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''  
		end
	if(@employeeCategory<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
		end	
	if(@DesignationID<>0)
		begin
			set @sqlQuery2 = @sqlQuery2 + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))	
		end	
	if(@Gender<>''Both'')
		begin
			set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlQuery2 = @sqlQuery2 + '' order by #TempProcessedData.Employee_code_id''  
	Exec(@sqlQuery+@sqlQuery2) 
	--select * from #EmpInOutDetails 
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level from #EmpInOutDetails	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
			if(@Count <=@Diff)
				begin
					set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(20)) + '' = #EmpInOutDetails.Attendance ''
					set @SQLFN1 = @SQLFN1 + '' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	''
					set @SQLFN1 = @SQLFN1 + '' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, '''''' + @FromDate3 + '''''' , 102) ''
					exec(@SQLFN1)
					set @SQLFN1=''''									
					if not exists(select DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
						begin							
							set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
							exec(@SQLFN1)																			
						end
				end
			else
				begin
					set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
					exec(@SQLFN1)
				end
			set @FromDate3=dateadd(d,1,@FromDate3)
			set @Count=@Count +1
		end	 
	set @Count=1
	set @FromDate3=@Fromdate1
	while(@Count <=31)
	begin
		set @SQLTemp = @SQLTemp + '' update #TempHeader set Day''+cast(@Count as varchar(10)) + ''='' + cast(datepart(d,@FromDate3)as varchar(10)) + ''where id=1''
		exec(@SQLTemp)
		set @SQLTemp=''''	
		set @FromDate3=dateadd(d,1,@FromDate3)
		set @Count=@Count +1
	end
	 --Leave Count
    DECLARE @LeaveCount AS NUMERIC(8,1)
	insert into #LeaveCount 
	select e.employee_code_id,ISNULL(sum(NumberOfDays),0) as LeaveCount from ta_tbl_leaveapplication la 
	inner join ta_tbl_employee e on e.Employee_Id = la.Employee_Id
	where ((la.Leave_FromDate between @FromDate1 and @Todate1) and (la.Leave_ToDate between @FromDate1 and @Todate1))	
	and la.Status = ''Approved'' 	
	group by e.employee_code_id
	--Present
	insert into #Present (Employee_code_Id,FNPresent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''Present'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Present set ANPresent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''Present'' and (Date between @FromDate1 and @Todate1)	
	and  #Present.Employee_code_Id=E.Employee_code_Id)
	update #Present set Present=FNPresent+ANPresent
	update #AllEmpInOutDetails set Present= case #Present.Present when null then ''0.0'' else #Present.Present end from #Present 
	inner join #AllEmpInOutDetails 
	on #Present.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Absent
	insert into #Absent (Employee_code_Id,FNAbsent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''Absent'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Absent set ANAbsent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''Absent'' and 
	(Date >= @FromDate1 and date >= @Todate1)
	and  #Absent.Employee_code_Id=E.Employee_code_Id)
	update #Absent set Absent=FNAbsent+ANAbsent
	--select * from #Absent
	update #AllEmpInOutDetails set Absent=#Absent.Absent from #Absent 
	inner join #AllEmpInOutDetails 
	on #Absent.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id 
	--BonusLeave
	insert into #BonusLeave (Employee_code_Id,FNBL)select E.Employee_code_Id,count(*)/2.0 
	from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''BL'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #BonusLeave set ANBL=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''BL'' and
	(Date between @FromDate1 and @Todate1)
	and  #BonusLeave.Employee_code_Id=E.Employee_code_Id)
	update #BonusLeave set BL=FNBL+ANBL
	--select * from #BonusLeave
	--Leave
	update #AllEmpInOutDetails set Leave=(isnull(#LeaveCount.LeaveCount,0)) from #LeaveCount	
	inner join #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	update #AllEmpInOutDetails set Leave=(isnull(#AllEmpInOutDetails.Leave,0)+isnull(#BonusLeave.BL,0)) from #AllEmpInOutDetails
	inner join #BonusLeave on #BonusLeave.Employee_code_Id=#AllEmpInOutDetails.Employee_Code_Id	
	--Ot Mins
	insert into #OTMins select E.Employee_code_Id,sum(OtMins) as OTMins from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_id
	update #AllEmpInOutDetails set TotalOT = #OTMins.OtMins from #OTMins inner join #AllEmpInOutDetails on #OTMins.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	insert into #Holiday select E.Employee_code_Id,COUNT(*)	                  
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	--TotalWorkingDays
	insert into #TotalWorkedDays select E.Employee_code_Id,
	sum(case 
				  when FNAttendanceCode=''Present'' and ANAttendanceCode=''Present'' then 1   
				  when FNAttendanceCode=''Present'' and ANAttendanceCode=''Absent'' then 0.5 
				  when FNAttendanceCode=''Absent'' and ANAttendanceCode=''Present'' then 0.5                 
                  when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then 1
                  when FNAttendanceCode=''RH'' and ANAttendanceCode=''RH'' then 1
                  when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (InTime<>''00:00'' or OutTime<>''00:00'') then  1                  
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and  (OutTime is null or OutTime='''') then 0.5
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
                   when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and (InTime is null or InTime='''') then 0.5
                  when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
                  when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
                  when fnattendanceCode=''Present'' and anattendanceCode not in(''Holiday'',''Absent'',''Present'',''RH'',''Weekly Off'') then 0.5
                  when anattendanceCode=''Present'' and fnattendanceCode not in(''Holiday'',''Absent'',''Present'',''RH'',''Weekly Off'') then 0.5
          end)
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	where (Date between @FromDate1 and @Todate1) and ((InTime<>''00:00'' or InTime is not null )
	or (OutTime<>''00:00'' or OutTime is not null))
	--or fnattendanceCode in (''Tour'',''Training'') or anattendanceCode in (''Tour'',''Training''))
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	update #AllEmpInOutDetails set TotalOT=''0'' 
	select * from #AllEmpInOutDetails A order by A.Grade_Level,Name
	select * from #TempHeader	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author      : Sashma
-- Create date : <Create Date,,>
-- Description : <Description,,>
--	Modified by	:	A.K.T.MOORTHI
--	Modified On	:	18-Feb-2014
--	Descriptions	:	Add OD Notation when OnDuty occur
/*
Proc_TA_RptEmployeeInOutDetails ''787'','''',''0'',''0'',''0'',''SuperAdmin'',''0'','''',0,''2015-04-01'',''2015-04-30'',0,''Both''
exec Proc_TA_RptEmployeeInOutDetails @EmployeeId=''Emp1'',@EmployeeName='''',@LevelID=''0,1'',@employeeCategory=N''0'',@employeeType=N''0'',@UserGroupName=''SuperAdmin'',@GradeLevel=''0'',@EmpSwipeCard='''',@ParentId=0,@FromDate1=''01/Jun/2013'',@ToDate1=''30/Jun/2013'',@DesignationID=0,@Gender=''Both''
*/
create PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails_beforelogix] 
	--@SelectedMonth nvarchar(20),  
	--@SelectedYear nvarchar(20),  
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),  
	@LevelID varchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
    @FromDate1 varchar(50),
    @ToDate1 varchar(50),
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
    Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	set @Fromdate2 = @Fromdate1
	set @Diff = datediff(d,@Fromdate1,@Todate1) + 1
	set @Count=1
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	insert into #TempHeader(id) values(1)
	SET NOCOUNT ON;
	--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,LevelId int,date datetime,
		Otmins numeric(18,1),TotalDays numeric(18, 1),Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,Designation nvarchar(250) ,
		empname nvarchar(50) ,Father_Name nvarchar(50),DesignationID int,Grade_Level int,OrderBy int
		,isManualTimeEntryFH bit default 0 not null,
	isManualTimeEntrySH bit default 0 not null
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50) ,FatherName nvarchar(50) ,Designation nvarchar(250) , Employee_Code_Id nvarchar(15) ,Present numeric(18,1),Absent numeric(18,1),Leave numeric(18,1),Holiday numeric(18,1)default(0.0),TotalOT numeric(18,1),CountDays  numeric(18,1) default(0.0),DesignationID int,Grade_Level int,OrderBy int,
		F_Day1 nvarchar(100) DEFAULT '''',F_Day2 nvarchar(100) DEFAULT '''',F_Day3 nvarchar(100) DEFAULT '''',F_Day4 nvarchar(100) DEFAULT '''',F_Day5 nvarchar(100) DEFAULT '''',F_Day6 nvarchar(100) DEFAULT '''',F_Day7 nvarchar(100) DEFAULT '''',F_Day8 nvarchar(100) DEFAULT '''',F_Day9 nvarchar(100) DEFAULT '''',F_Day10 nvarchar(100) DEFAULT '''',F_Day11 nvarchar(100) DEFAULT '''',F_Day12 nvarchar(100) DEFAULT '''',F_Day13 nvarchar(100) DEFAULT '''',F_Day14 nvarchar(100) DEFAULT '''',F_Day15 nvarchar(100) DEFAULT '''',F_Day16 nvarchar(100) DEFAULT '''',F_Day17 nvarchar(100) DEFAULT '''',F_Day18 nvarchar(100) DEFAULT '''',F_Day19 nvarchar(100) DEFAULT '''',F_Day20 nvarchar(100) DEFAULT '''',F_Day21 nvarchar(100) DEFAULT '''',F_Day22 nvarchar(100) DEFAULT '''',F_Day23 nvarchar(100) DEFAULT '''',F_Day24 nvarchar(100) DEFAULT '''',F_Day25 nvarchar(100) DEFAULT '''',F_Day26 nvarchar(100) DEFAULT '''',F_Day27 nvarchar(100) DEFAULT '''',F_Day28 nvarchar(100) DEFAULT '''',F_Day29 nvarchar(100) DEFAULT '''',F_Day30 nvarchar(100) DEFAULT '''',F_Day31 nvarchar(100) DEFAULT ''''
	)
	create table #LeaveCount(Employee_code_Id nvarchar(15) ,LeaveCount numeric(18,1))
	create table #OTMins(Employee_code_Id nvarchar(15) ,OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15) ,NFHolidays numeric(18,1))
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15) ,Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15) ,FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15) ,FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15) ,FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(
	EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),OtMins float,TotalDays numeric(18, 1),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20)
		,earlyoutmins varchar(20),LateInmins varchar(20),HrsWork varchar(20),ShiftId int,Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20)
		 ) 
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade] 
	(
	[Grade_Id] ASC
	) ON [PRIMARY]
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],	[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
--Employee Level insert in Temporary table
insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate1,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate1,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate1,@EmployeeId,@employeeCategory	
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
Declare @sqlEmpLevel nvarchar(4000)		
set @sqlEmpLevel=
''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate1 as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
execute(@sqlEmpLevel)	
Declare @sqlTempProcess varchar(8000)
Declare @sqlTempProcess1 varchar(8000)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=	
	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id''
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End	
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''		
	execute(@sqlTempProcessedData1)	
   select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0
Declare @sqlTempProcessedData varchar(8000)
set @sqlTempProcessedData=		
	''insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,''''''+cast(@FromDate1 as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@ToDate1 as nvarchar(50))+'''''', 102)''
Execute(@sqlTempProcessedData)	
set @sqlTempProcessedData1=		
	''insert into #TempProcessedData
		select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
		PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,PD.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime 
		from TA_Tbl_ProcessedData PD
		inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
		where date>=CONVERT(DATETIME,''''''+cast(@FromDate1 as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@ToDate1 as nvarchar(50))+'''''', 102)
		and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)''
	Execute(@sqlTempProcessedData1)
	Set @EmployeeName = isnull(@EmployeeName,'''') + ''%''
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
    set @sqlQuery=''''
	set @sqlQuery2=''''
	set @sqlQuery1 =''''
	set @sqlQuery =''Insert into #EmpInOutDetails select TA_Tbl_Employee.Employee_code_id,#EmpLevel.LevelId,''  	
	set @sqlQuery = @sqlQuery + '' #TempProcessedData.date, #TempProcessedData.OtMins, #TempProcessedData.TotalDays,''
	set @sqlQuery = @sqlQuery + '' Attendance1 = case #TempProcessedData.Attendance ''
	set @sqlQuery = @sqlQuery + '' when ''''Present'''' then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*~''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' O~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  else 
	  '''' i~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) end''
	set @sqlQuery = @sqlQuery + '' when ''''Absent'''' then ''''A'''' ''	
	set @sqlQuery = @sqlQuery + '' when ''''Holiday'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**H'''' else ''''H'''' end''
	set @sqlQuery = @sqlQuery + '' when ''''RH'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**RH'''' else  ''''RH'''' end''
	set @sqlQuery = @sqlQuery + '' when ''''Comp Off'''' then ''''C'''' ''
	set @sqlQuery = @sqlQuery + '' when ''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end ''
	set @sqlQuery = @sqlQuery + '' Else ''''L'''' ''
	set @sqlQuery = @sqlQuery + '' end ''
	set @sqlQuery = @sqlQuery + '' ,Attendance2 = cast(isnull('''' i~'''' +#TempProcessedData.InTime,'''''''')as nvarchar)  +  cast(isnull('''' o~'''' + #TempProcessedData.OutTime,'''''''') as nvarchar)''
	set @sqlQuery = @sqlQuery + '' ,Attendance = case  when fnattendanceCode=''''Present'''' then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' o*~''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
    					  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' o~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
						  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' o*~''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
						  else '''' i~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' o~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) end''
	set @sqlQuery = @sqlQuery + '' when  fnattendancecode=''''Absent''''  then ''''A'''' ''	
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end''		
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Holiday'''' and anattendanceCode<>''''Holiday'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**H'''' else ''''H''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Holiday'''' and anattendanceCode=''''Holiday''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**H'''' else ''''H''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''RH'''' and anattendanceCode<>''''RH'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**RH'''' else ''''RH''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''RH'''' and anattendanceCode=''''RH''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**RH'''' else  ''''RH''''	 end''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=''''Comp Off''''  then ''''C'''' ''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode is null  then ''''-''''	''
	set @sqlQuery = @sqlQuery + '' else ''''L'''' ''
	set @sqlQuery = @sqlQuery + '' end + '''''''' + isnull( ''
	set @sqlQuery = @sqlQuery + ''case  ''
	set @sqlQuery = @sqlQuery + '' when fnattendanceCode=anattendanceCode then null''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Present'''' then case when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' )then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.LateInmins <> ''''0'''') then '''' i*~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +'''' O~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  when (#TempProcessedData.earlyoutmins <> ''''0'''' ) then '''' i~'''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + '''' O*~'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
	  else  '''' /'''' +   cast(isnull('''' i~'''' +#TempProcessedData.InTime,'''''''')as nvarchar)  +  cast(isnull('''' O~'''' + #TempProcessedData.OutTime,'''''''') as nvarchar)end''
	set @sqlQuery = @sqlQuery + '' when  anattendancecode=''''Absent''''  then ''''/A'''' ''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Weekly Off''''  then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''')then ''''**Off'''' else ''''/Off'''' end''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Holiday'''' then  case when (OutTime is not null and OutTime<>''''00:00'''' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''''**H'''' else ''''/H''''	 end''	  	
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''RH'''' then  case when (OutTime is not null and OutTime<>''''00:00'''' and cast(OutTime as datetime)>=cast(#TempProcessedData.Shift_SecondHalf_StartTime as datetime)) then ''''**RH'''' else ''''/RH''''	 end''	  	
	set @sqlQuery = @sqlQuery + '' when anattendanceCode=''''Comp Off''''  then ''''/C'''' ''
	set @sqlQuery = @sqlQuery + '' when anattendanceCode is null  then ''''-'''' ''
	set @sqlQuery = @sqlQuery + '' else ''''/L''''	''
	set @sqlQuery = @sqlQuery + '' end ,'''''''')''
	set @sqlQuery = @sqlQuery + ''  ,#TempProcessedData.employee_code_id, Replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''''''') as empname, ta_tbl_employee.Father_Name ''   
	set @sqlQuery = @sqlQuery + '' ,TA_Tbl_Title.TitleId,TA_Tbl_Grade.Grade_Level,0,0,0 FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId ''  			
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id ''    
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id ''
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId '' 
	SET @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''  
	set @sqlQuery1 = @sqlQuery1 + '' inner join #EmpCategory on TA_Tbl_Employee.Employee_Id = #EmpCategory.EmployeeId''  	
	set @sqlQuery1 = @sqlQuery1 + '' inner join #EmpType on TA_Tbl_Employee.Employee_Id = #EmpType.EmployeeId''  	
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''	
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId''
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId''	
	 set @sqlQuery1 = @sqlQuery1 + '' left outer join TA_Tbl_ManualTimeEntry mdIn on mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date
	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''''Approved'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''''Y'''' and mdIn.IsOnDuty=''''0''''
	left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''''Approved'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''''Y'''' and mdOut.IsOnDuty=''''0'''' '' 
	set @sqlQuery1 = @sqlQuery1 + '' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )''  
	if(@UserGroupName<>''SuperAdmin'')
		begin	
			SET @sqlQuery2 = @sqlQuery2 + ''	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery2 = @sqlQuery2 + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	set @sqlQuery2 = @sqlQuery2 + '' order by #TempProcessedData.Employee_code_id''  
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2)
	update Emp set Emp.isManualTimeEntryFH=  
	case when (P.FNAttendanceCode=''Present'' OR FNAttendanceCode=''*Present'' OR FNAttendanceCode=''Holiday'' OR FNAttendanceCode=''*Holiday'' OR FNAttendanceCode=''Weekly Off'' OR FNAttendanceCode=''*Weekly Off'') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
		 else 0 
	end ,	
	Emp.isManualTimeEntrySH= 
	case when (P.FNAttendanceCode=''Present'' OR FNAttendanceCode=''*Present'' OR FNAttendanceCode=''Holiday'' OR FNAttendanceCode=''*Holiday'' OR FNAttendanceCode=''Weekly Off'' OR FNAttendanceCode=''*Weekly Off'') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
		 else 0 end
	from #EmpInOutDetails Emp	
	inner join Ta_Tbl_ManualTimeEntry M on M.ManualTimeEntry_Employee_Id=Emp.employee_code_id
	inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	and Emp.date=P.Date
	and (cast(P.Date+CONVERT(datetime,P.InTime) as datetime)=cast(M.ManualTimeEntry_InDate+CONVERT(datetime,M.ManualTimeEntry_InTime) as datetime)
	or cast( P.Date+convert(datetime,P.OutTime) as datetime)=cast(M.ManualTimeEntry_OutDate+CONVERT(datetime,M.ManualTimeEntry_OutTime) as datetime))
	where M.ManualTimeEntry_Status=''Approved'' and M.Isdeleted=0 
	and isnull(M.IsOnDuty,0)=0
	--Update OnDuty Entry As ''OD'' <-- Start By A.K.T.MOORTHI (18-Feb-2014)
	UPDATE #EmpInOutDetails SET 
		Attendance1 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id, ''FN'', PD.Shift_Id, Attendance1),
		Attendance2 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, ''AN'', PD.Shift_Id, Attendance2)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	UPDATE #EmpInOutDetails SET Attendance = 
		(CASE WHEN Attendance1 = ''OD'' AND Attendance2 = ''OD'' THEN ''OD''
				WHEN Attendance1 = ''OD'' THEN (CASE WHEN Attendance LIKE ''%/%'' THEN (''OD '' + SUBSTRING(Attendance, CHARINDEX(''/'', Attendance, 0), 10000)) WHEN Attendance LIKE ''% %'' THEN (''OD '' + SUBSTRING(Attendance, CHARINDEX('' '', Attendance, 0), 10000))  ELSE Attendance END)
		WHEN Attendance2 = ''OD'' THEN (CASE WHEN Attendance LIKE ''%/%'' THEN (SUBSTRING(Attendance, 0, CHARINDEX(''/'', Attendance, 0)) + ''/ OD '') WHEN Attendance LIKE ''% %'' THEN ((SUBSTRING(Attendance, 0, CHARINDEX('' '', Attendance, 0))) + '' OD'')  ELSE Attendance END) ELSE Attendance END)
	FROM #EmpInOutDetails WHERE Attendance1 LIKE ''%OD%'' OR Attendance2 LIKE ''%OD%''
	--End BY A.K.T.MOORTHI(18-Feb-2014)-->
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
		set @SQLTemp = @SQLTemp + '' update #TempHeader set Day''+cast(@Count as varchar(10)) + ''='' + cast(datepart(d,@FromDate3)as varchar(10)) + ''where id=1''
		exec(@SQLTemp)
		set @SQLTemp=''''
			if(@Count <=@Diff)
				begin
					set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(20)) + '' = #EmpInOutDetails.Attendance ''
					set @SQLFN1 = @SQLFN1 + '' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	''
					set @SQLFN1 = @SQLFN1 + '' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, '''''' + @FromDate3 + '''''' , 102) ''
					exec(@SQLFN1)
					set @SQLFN1=''''									
					if not exists(select DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
						begin							
							set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
							exec(@SQLFN1)																			
						end
				end
			else
				begin
					set @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
					exec(@SQLFN1)
				end
			set @FromDate3=dateadd(d,1,@FromDate3)
			set @Count=@Count +1
		end	 
	 --Leave Count
    DECLARE @LeaveCount AS NUMERIC(8,1)
	insert into #LeaveCount select e.employee_code_id,ISNULL(sum(NumberOfDays),0) as LeaveCount from ta_tbl_leaveapplication la 
	inner join ta_tbl_employee e on e.Employee_Id = la.Employee_Id
	where ((la.Leave_FromDate between @FromDate1 and @Todate1) and (la.Leave_ToDate between @FromDate1 and @Todate1))
	and la.Status = ''Approved'' 
	group by e.employee_code_id
	--Present
	insert into #Present (Employee_code_Id,FNPresent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''Present'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Present set ANPresent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''Present'' and (Date between @FromDate1 and @Todate1)
	and  #Present.Employee_code_Id=E.Employee_code_Id)
	update #Present set Present=FNPresent+ANPresent
	update #AllEmpInOutDetails set Present= case #Present.Present when null then ''0.0'' else #Present.Present end from #Present 
	inner join #AllEmpInOutDetails 
	on #Present.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Absent
	insert into #Absent (Employee_code_Id,FNAbsent)select E.Employee_code_Id,count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''Absent'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #Absent set ANAbsent=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''Absent'' and 
	(Date >= @FromDate1 and date >= @Todate1)
	and  #Absent.Employee_code_Id=E.Employee_code_Id)
	update #Absent set Absent=FNAbsent+ANAbsent
	update #AllEmpInOutDetails set Absent=#Absent.Absent from #Absent 
	inner join #AllEmpInOutDetails 
	on #Absent.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id 
	--BonusLeave
	insert into #BonusLeave (Employee_code_Id,FNBL)select E.Employee_code_Id,count(*)/2.0 
	from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where FNAttendanceCode=''BL'' and (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_Id
	update #BonusLeave set ANBL=(select count(*)/2.0 from #TempProcessedData B 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=B.Employee_code_Id 
	where 
	ANAttendanceCode=''BL'' and
	(Date between @FromDate1 and @Todate1)
	and  #BonusLeave.Employee_code_Id=E.Employee_code_Id)
	update #BonusLeave set BL=FNBL+ANBL
	--Leave
	update #AllEmpInOutDetails set Leave=(#LeaveCount.LeaveCount+#BonusLeave.BL) from #LeaveCount
	inner join #BonusLeave on #BonusLeave.Employee_code_Id=#LeaveCount.Employee_Code_Id
	inner join #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	--Ot Mins
	insert into #OTMins select E.Employee_code_Id,sum(OtMins) as OTMins from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id where (Date between @FromDate1 and @Todate1)
	group by E.Employee_code_id
	update #AllEmpInOutDetails set TotalOT = #OTMins.OtMins from #OTMins inner join #AllEmpInOutDetails on #OTMins.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
   --NFHolidays
	insert into #Holiday select E.Employee_code_Id,count(*) from #TempProcessedData C 
	inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	where (fnattendanceCode in (''Holiday'') and anattendanceCode in(''Holiday'')) and (Date between @FromDate1 and @Todate1) 
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set Holiday = #Holiday.NFHolidays from #Holiday 
	inner join #AllEmpInOutDetails on #Holiday.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	--TotalWorkingDays
	insert into #TotalWorkedDays select E.Employee_code_Id,
	sum(case 
				  when FNAttendanceCode=''Present'' and ANAttendanceCode=''Present'' then 1   
				  when FNAttendanceCode=''Present'' and ANAttendanceCode=''Absent'' then 0.5 
				  when FNAttendanceCode=''Absent'' and ANAttendanceCode=''Present'' then 0.5                 
                  when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then 1
                  when FNAttendanceCode=''RH'' and ANAttendanceCode=''RH'' then 1
                  when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (InTime<>''00:00'' or OutTime<>''00:00'') then  1                  
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and  (OutTime is null or OutTime='''') then 0.5
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
                  when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
                   when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and (InTime is null or InTime='''') then 0.5
                  when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
                  when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
                  when fnattendanceCode=''Present'' and anattendanceCode not in(''Holiday'',''Absent'',''Present'',''Restricted Holiday'',''Weekly Off'') then 0.5
                  when anattendanceCode=''Present'' and fnattendanceCode not in(''Holiday'',''Absent'',''Present'',''Restricted Holiday'',''Weekly Off'') then 0.5
          end)
	from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	where (Date between @FromDate1 and @Todate1) and ((InTime<>''00:00'' or InTime is not null )
	or (OutTime<>''00:00'' or OutTime is not null) or fnattendanceCode in (''Tour'',''Training'') or anattendanceCode in (''Tour'',''Training''))
	group by E.Employee_code_Id
	update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	update #AllEmpInOutDetails set TotalOT=''0'' 
	select * from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	select * from #TempHeader	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author      : Sashma
-- Create date : <Create Date,,>
-- Description : <Description,,>
--	Modified by	:	A.K.T.MOORTHI
--	Modified On	:	18-Feb-2014
--	Descriptions	:	Add OD Notation when OnDuty occur
/*
[Proc_TA_RptEmployeeInOutDetails] '''','''',''0'',''0'',''0'',''SuperAdmin'',''0'','''',0,''20180701'',''20180731'',0,''Both'',0
exec Proc_TA_RptEmployeeInOutDetails @EmployeeId=''7877'',@EmployeeName='''',@LevelID=''0,1'',@employeeCategory=N''0'',@employeeType=N''0'',@UserGroupName=''SuperAdmin'',@GradeLevel=''0'',@EmpSwipeCard='''',@ParentId=0,@FromDate1=''01/Jan/2019'',@ToDate1=''30/jan/2019'',@DesignationID=0,@Gender=''Both'',@EmpAutoID=0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutDetails] 	
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),  
	@LevelID varchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
    @FromDate1 varchar(50),
    @ToDate1 varchar(50),
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeId varchar(max)
	DECLARE @local_EmployeeName varchar(max)
	DECLARE @local_LevelID varchar(1000)
	DECLARE @local_employeeCategory nvarchar(50)
	DECLARE @local_employeeType nvarchar(50)
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
    DECLARE @local_FromDate1 varchar(50)
    DECLARE @local_ToDate1 varchar(50)
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoID int
	
	set @local_EmployeeId=@EmployeeId
	set @local_EmployeeName=@EmployeeName
	set @local_LevelID=@LevelID
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
    set @local_FromDate1=@FromDate1
    set @local_ToDate1=@ToDate1
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoID=@EmpAutoID
		
	Declare @Fromdate2 datetime
	Declare @Count int
	declare @Diff int
	set @Fromdate2 = @local_FromDate1
	set @Diff = datediff(d,@local_FromDate1,@local_ToDate1) + 1
	set @Count=1
	
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))	
	create table #EmployeeIds(EmpAutoId int)	
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	
	create table #EmpInOutDetails
	(
		Employee_code_id nvarchar(15) ,
		LevelId int,date datetime,
		Otmins numeric(18,1),
		TotalDays numeric(18, 1),
		Attendance1 varchar(max) ,
		Attendance2 varchar(max) ,
		Attendance varchar(max) ,
		employee_code_id1 nvarchar(15) ,
		Designation nvarchar(250) ,
		empname nvarchar(150) ,
		Father_Name nvarchar(50),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		isManualTimeEntryFH bit default 0 not null,
		isManualTimeEntrySH bit default 0 not null
	)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(150),
		FatherName nvarchar(150) ,
		Designation nvarchar(250) ,
		Employee_Code_Id nvarchar(15),
		Present numeric(18,1),
		Absent numeric(18,1),
		Leave numeric(18,1),
		Holiday numeric(18,1)default(0.0),
		TotalOT numeric(18,1),
		CountDays  numeric(18,1) default(0.0),
		DesignationID int,
		Grade_Level int,
		OrderBy int,
		F_Day1 nvarchar(100) DEFAULT '''',
		F_Day2 nvarchar(100) DEFAULT '''',
		F_Day3 nvarchar(100) DEFAULT '''',
		F_Day4 nvarchar(100) DEFAULT '''',
		F_Day5 nvarchar(100) DEFAULT '''',
		F_Day6 nvarchar(100) DEFAULT '''',
		F_Day7 nvarchar(100) DEFAULT '''',
		F_Day8 nvarchar(100) DEFAULT '''',
		F_Day9 nvarchar(100) DEFAULT '''',
		F_Day10 nvarchar(100) DEFAULT '''',
		F_Day11 nvarchar(100) DEFAULT '''',
		F_Day12 nvarchar(100) DEFAULT '''',
		F_Day13 nvarchar(100) DEFAULT '''',
		F_Day14 nvarchar(100) DEFAULT '''',
		F_Day15 nvarchar(100) DEFAULT '''',
		F_Day16 nvarchar(100) DEFAULT '''',
		F_Day17 nvarchar(100) DEFAULT '''',
		F_Day18 nvarchar(100) DEFAULT '''',
		F_Day19 nvarchar(100) DEFAULT '''',
		F_Day20 nvarchar(100) DEFAULT '''',
		F_Day21 nvarchar(100) DEFAULT '''',
		F_Day22 nvarchar(100) DEFAULT '''',
		F_Day23 nvarchar(100) DEFAULT '''',
		F_Day24 nvarchar(100) DEFAULT '''',
		F_Day25 nvarchar(100) DEFAULT '''',
		F_Day26 nvarchar(100) DEFAULT '''',
		F_Day27 nvarchar(100) DEFAULT '''',
		F_Day28 nvarchar(100) DEFAULT '''',
		F_Day29 nvarchar(100) DEFAULT '''',
		F_Day30 nvarchar(100) DEFAULT '''',
		F_Day31 nvarchar(100) DEFAULT ''''
	)
	create table #TotalWorkedDays(Employee_code_Id nvarchar(15) ,TotalWorkedDays numeric(18,1))
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		OtMins float,
		TotalDays numeric(18, 1),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		earlyoutmins varchar(20),
		LateInmins varchar(20),
		HrsWork varchar(20),
		ShiftId int,
		Shift_FirstHalf_EndTime nvarchar(20),
		Shift_SecondHalf_StartTime nvarchar(20),
		BreakOutTime varchar(10),
		BreakInTime varchar(10)
	)	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	insert into #TempHeader(id) values(1)
	if(@isReportingto > 0)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	end
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId	
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@local_GradeLevel
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate1,@local_EmployeeId,@local_DesignationID	
	
	if(@local_employeeType > 0)
	BEGIN
		INSERT INTO #EmpType exec [Proc_TA_EmpType] @local_ToDate1,@local_EmployeeId,@local_employeeType
	END
	if(@local_employeeCategory > 0)
	BEGIN
		INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate1,@local_EmployeeId,@local_employeeCategory
	END
	
	if(@local_EmployeeId is not null and @local_EmployeeId <> '''')
	begin
		create table #EmployeeID(EmployeeID varchar(25))
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@local_EmployeeId)
	end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
	begin
		create table #EmployeeName(EmployeeID varchar(25))
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
	end	
	Declare @sqlEmpLevel nvarchar(4000)		
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId ''
	If Not (@local_EmployeeId = '''')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id ''
	End
	If Not (@local_EmployeeName = '''')  
	Begin  
		SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id ''
	End
	SET @sqlEmpLevel = @sqlEmpLevel + '' where emp.Isdeleted=0 ''
	IF(@local_Gender<>''Both'')
	BEGIN
		SET @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
	END	
	set @sqlEmpLevel=@sqlEmpLevel+'' group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate1 as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	execute(@sqlEmpLevel)	
	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee e
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id''	
	SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' where SwipeCardNo is not null and e.Isdeleted=0''			
	EXECUTE(@sqlTempProcessedData1)	
	
	SELECT SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee e
	inner join #TempEmployee on #TempEmployee.EmpAutoId=e.Employee_Id
	where inactivedate is not null and Employee_Status=0
	
	DECLARE @sqlTempProcessedData varchar(8000)
	SET @sqlTempProcessedData=		
	''insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''''''',''''''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,''''''+cast(@local_FromDate1 as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@local_ToDate1 as nvarchar(50))+'''''', 102)''
	Execute(@sqlTempProcessedData)
	
	set @sqlTempProcessedData1=		
	''insert into #TempProcessedData
	select #TempEmployee.EmpAutoId,PD.Date,PD.Employee_Code_Id,PD.InTime,PD.OutTime,PD.OtMins,PD.TotalDays,PD.Attendance,PD.fnattendanceCode,PD.anattendanceCode,
	PD.EarlyOutMins,PD.LateInMins,PD.HrsWork,PD.Shift_Id,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,'''''''',''''''''
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id 
	where date>=CONVERT(DATETIME,''''''+cast(@local_FromDate1 as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@local_ToDate1 as nvarchar(50))+'''''', 102)
	and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)''
	Execute(@sqlTempProcessedData1)
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	--update #TempProcessedData set BreakOutTime=mp.Clk_InTime,BreakInTime=mp.Clk_OutTime 
	--from #TempProcessedData TPD
	--inner join
	--(
	--select clk_empid,row=ROW_NUMBER()over(partition by clk_empid,clk_indate,clk_outdate order by clk_empid),
	--Clk_InDate,
	--case when RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7)<>''00:00'' then
	--case	when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(25),DATEADD(minute,0,convert(datetime,Clk_InTime,0))),13,5)
	--else case	when len(ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,CHARINDEX('':'',RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7)))))=1 then ''0''+ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,6))+'' ''+substring(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),6,2)
	--			else SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),0,6)+'' ''+substring(RIGHT(CONVERT(VARCHAR, Clk_InTime, 100), 7),6,2)
	--	 end
	--end
	--else '''' 
	--end	Clk_InTime,
	--Clk_OutDate,
	--case when RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7)<>''00:00'' then
	--case	when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(25),DATEADD(minute,0,convert(datetime,Clk_OutTime,0))),13,5)
	--else case	when len(ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,CHARINDEX('':'',RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7)))))=1 then ''0''+ltrim(SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,6))+'' ''+substring(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),6,2)
	--			else SUBSTRING(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),0,6)+'' ''+substring(RIGHT(CONVERT(VARCHAR, Clk_OutTime, 100), 7),6,2)
	--	 end
	--end
	--else '''' 
	--end	Clk_OutTime,Clk_InPunchType,Clk_OutPunchType,Clk_Date from ta_tbl_matchedpunches 
	--where (Clk_InPunchType=''Break out'' or Clk_OutPunchType=''Break in'')
	--and(Clk_Date>=CONVERT(DATETIME,cast(@local_FromDate1 as nvarchar(50)), 102) and Clk_Date<=CONVERT(DATETIME,cast(@local_ToDate1 as nvarchar(50)), 102))
	--)as mp on ((TPD.Employee_Code_Id=mp.Clk_EmpId) and (mp.Clk_Date=TPD.Date))
	--inner join #TempEmployee te on te.EmpSwipeCardNo=mp.Clk_EmpId
	--where mp.row=1	
	Set @local_EmployeeName = isnull(@EmployeeName,'''') + ''%''
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery2=''''
	set @sqlQuery1 =''''
	set @sqlQuery =''Insert into #EmpInOutDetails 
					select	TA_Tbl_Employee.Employee_code_id,
							#EmpLevel.LevelId,
							#TempProcessedData.date, 
							#TempProcessedData.OtMins,
							#TempProcessedData.TotalDays,
							Attendance1 = case #TempProcessedData.Attendance 
												when ''''Present'''' then case	when (#TempProcessedData.earlyoutmins <> ''''0'''' and #TempProcessedData.LateInmins <> ''''0'''' ) then '''' '''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + ''''#''''+ cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
																			when (#TempProcessedData.LateInmins <> ''''0'''')	then '''' '''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  +''''#'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
																			when (#TempProcessedData.earlyoutmins <> ''''0'''' )then '''' '''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + ''''#'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
																			else '''' '''' +cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar)  + ''''#'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar) 
																	  end
												when ''''Absent'''' then ''''A''''
												when ''''Holiday'''' then case	when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**H'''' else ''''H'''' end
												when ''''RH'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**RH'''' else  ''''RH'''' end
												when ''''Comp Off'''' then ''''C''''
												when ''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end
												Else ''''L''''
										  end,
							Attendance2 =cast(isnull('''' '''' +#TempProcessedData.InTime,'''''''')as nvarchar)  +  cast(isnull(''''#'''' + #TempProcessedData.OutTime,'''''''') as nvarchar),
							Attendance	=case	when (#TempProcessedData.InTime <> ''''00:00'''' or #TempProcessedData.outtime <> ''''00:00'''' ) then cast(isnull(#TempProcessedData.InTime,'''''''')as nvarchar) +''''#'''' + cast(isnull(#TempProcessedData.OutTime,'''''''') as nvarchar)
												when  fnattendancecode=''''Absent''''  then ''''A''''
												when fnattendanceCode=''''Weekly Off'''' then case when (InTime is not null and InTime<> ''''00:00'''') or (OutTime is not null and OutTime<>''''00:00'''') then ''''**Off'''' else ''''Off'''' end
												when fnattendanceCode=''''Holiday'''' and anattendanceCode<>''''Holiday'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**H'''' else ''''H''''	 end
												when fnattendanceCode=''''Holiday'''' and anattendanceCode=''''Holiday''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**H'''' else ''''H''''	 end
												when fnattendanceCode=''''RH'''' and anattendanceCode<>''''RH'''' then  case when (InTime is not null and InTime<> ''''00:00'''' and cast(InTime as DateTime)<=cast(#TempProcessedData.Shift_FirstHalf_EndTime as datetime)) then ''''**RH'''' else ''''RH''''	 end
												when fnattendanceCode=''''RH'''' and anattendanceCode=''''RH''''  then  case when (InTime<> ''''00:00'''' Or Outtime<>''''00:00'''') then ''''**RH'''' else  ''''RH''''	 end
												when fnattendanceCode=''''Comp Off''''  then ''''C''''
												when fnattendanceCode is null  then ''''-''''
												else ''''L''''
										end
										--+''''##''''+cast(isnull(#TempProcessedData.BreakOutTime,'''''''')as nvarchar)  + ''''#''''+ cast(isnull(#TempProcessedData.BreakInTime,'''''''') as nvarchar)
										+''''##''''+ case when #TempProcessedData.HrsWork<>''''00:00'''' then cast(isnull(#TempProcessedData.HrsWork,'''''''') as nvarchar) else '''''''' end,
							#TempProcessedData.employee_code_id, 
							Replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,
							TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''''''') as empname, 
							ta_tbl_employee.Father_Name,
							TA_Tbl_Title.TitleId,
							TA_Tbl_Grade.Grade_Level,
							0,
							0,
							0 
							FROM  dbo.#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_Id=dbo.#TempProcessedData.EmpAutoId
							Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id
							INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id
							INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId
							INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
	if(@local_employeeCategory>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #EmpCategory TEC on TA_Tbl_Employee.Employee_Id = TEC .EmployeeId
										INNER JOIN TA_Tbl_Category c on TEC.CategoryId = c.CategoryId''
	END
	if(@local_employeeType>0)
	BEGIN
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #EmpType TET on TA_Tbl_Employee.Employee_Id = TET.EmployeeId
										INNER JOIN TA_Tbl_Type T on TET.TypeId = TA_Tbl_Type.TypeId''	
	END
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''	
	--set @sqlQuery1 = @sqlQuery1 + '' left outer join TA_Tbl_ManualTimeEntry mdIn on (mdIn.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	--								and mdIn.ManualTimeEntry_InDate=#TempProcessedData.Date	and mdIn.Isdeleted=0 and mdIn.ManualTimeEntry_Status=''''Approved'''' and isnull(mdIn.ManualTimeEntry_Id,0)<>0 and mdIn.Clk_Process=''''Y'''' and mdIn.IsOnDuty=''''0''''
	--								left outer join TA_Tbl_ManualTimeEntry mdOut on mdOut.ManualTimeEntry_Employee_Id=#TempProcessedData.Employee_Code_Id
	--								and mdOut.ManualTimeEntry_OutDate=#TempProcessedData.Date
	--								and mdOut.Isdeleted=0 and mdOut.ManualTimeEntry_Status=''''Approved'''' and isnull(mdOut.ManualTimeEntry_Id,0)<>0 and mdOut.Clk_Process=''''Y'''' and mdOut.IsOnDuty=''''0'''')'' 
	set @sqlQuery1 = @sqlQuery1 + '' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )''  
	if(@local_UserGroupName<>''SuperAdmin'')
	begin	
		SET @sqlQuery2 = @sqlQuery2 + ''	and TA_Tbl_Title.GradeId in (select Grade_Id from #EmpGrade)''
	end	
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery2 = @sqlQuery2 + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	set @sqlQuery2 = @sqlQuery2 + '' order by #TempProcessedData.Employee_code_id''  
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2)
	
	--select * from #EmpInOutDetails
	--update Emp set Emp.isManualTimeEntryFH=  
	--case	when (P.FNAttendanceCode=''Present'' OR FNAttendanceCode=''*Present'' OR FNAttendanceCode=''Holiday'' OR FNAttendanceCode=''*Holiday'' OR FNAttendanceCode=''Weekly Off'' OR FNAttendanceCode=''*Weekly Off'') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
	--		else 0 
	--end,	
	--Emp.isManualTimeEntrySH= 
	--case	when (P.FNAttendanceCode=''Present'' OR FNAttendanceCode=''*Present'' OR FNAttendanceCode=''Holiday'' OR FNAttendanceCode=''*Holiday'' OR FNAttendanceCode=''Weekly Off'' OR FNAttendanceCode=''*Weekly Off'') and M.ManualTimeEntry_InTime IS NOT NULL  and P.InTime is not null then 1 
	--		else 0 
	--end	from #EmpInOutDetails Emp	inner join Ta_Tbl_ManualTimeEntry M on M.ManualTimeEntry_Employee_Id=Emp.employee_code_id
	--inner join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	--and Emp.date=P.Date
	--and (cast(P.Date+CONVERT(datetime,P.InTime) as datetime)=cast(M.ManualTimeEntry_InDate+CONVERT(datetime,M.ManualTimeEntry_InTime) as datetime)
	--or cast( P.Date+convert(datetime,P.OutTime) as datetime)=cast(M.ManualTimeEntry_OutDate+CONVERT(datetime,M.ManualTimeEntry_OutTime) as datetime)))
	--where M.ManualTimeEntry_Status=''Approved'' and M.Isdeleted=0 
	--and isnull(M.IsOnDuty,0)=0
	
	UPDATE #EmpInOutDetails SET 
	Attendance1 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id, ''FN'', PD.Shift_Id, Attendance1),
	Attendance2 = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, ''AN'', PD.Shift_Id, Attendance2)
	FROM #EmpInOutDetails IOD INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	
	UPDATE #EmpInOutDetails SET Attendance = 
	(CASE WHEN Attendance1 = ''OD'' AND Attendance2 = ''OD'' THEN ''OD''
	WHEN Attendance1 = ''OD'' THEN (CASE WHEN Attendance LIKE ''%/%'' THEN (''OD '' + SUBSTRING(Attendance, CHARINDEX(''/'', Attendance, 0), 10000)) WHEN Attendance LIKE ''% %'' THEN (''OD '' + SUBSTRING(Attendance, CHARINDEX('' '', Attendance, 0), 10000))  ELSE Attendance END)
	WHEN Attendance2 = ''OD'' THEN (CASE WHEN Attendance LIKE ''%/%'' THEN (SUBSTRING(Attendance, 0, CHARINDEX(''/'', Attendance, 0)) + ''/ OD '') WHEN Attendance LIKE ''% %'' THEN ((SUBSTRING(Attendance, 0, CHARINDEX('' '', Attendance, 0))) + '' OD'')  ELSE Attendance END) ELSE Attendance END)
	FROM #EmpInOutDetails WHERE Attendance1 LIKE ''%OD%'' OR Attendance2 LIKE ''%OD%''
	
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails	
	
	set @Count=1
	Declare @SQLFN1 varchar(max)
	set @SQLFN1=''''
	Declare @SQLAN1 varchar(max)
	set @SQLAN1=''''
	Declare @SQLTemp varchar(max)
	set @SQLTemp=''''
	Declare @FromDate3 varchar(50)
	set @FromDate3=@local_FromDate1
	while(@Count <=31)
	BEGIN
		SET @SQLTemp = @SQLTemp + '' update #TempHeader set Day''+cast(@Count as varchar(10)) + ''='' + cast(datepart(d,@FromDate3)as varchar(10)) + ''where id=1''
		exec(@SQLTemp)
		set @SQLTemp=''''
		if(@Count <=@Diff)
		BEGIN
			SET @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(20)) + '' = #EmpInOutDetails.Attendance ''
			SET @SQLFN1 = @SQLFN1 + '' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	''
			SET @SQLFN1 = @SQLFN1 + '' #EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date = CONVERT(DATETIME, '''''' + @FromDate3 + '''''' , 102) ''
			EXEC(@SQLFN1)
			SET @SQLFN1=''''									
			IF NOT EXISTS(SELECT DATE from TA_Tbl_ProcessedData where Date=CONVERT(DATETIME,  @FromDate3, 102))
			BEGIN							
				SET @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
				EXEC(@SQLFN1)																			
			END
		END
		ELSE
		BEGIN
			SET @SQLFN1 = @SQLFN1 + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as varchar(10)) + '' = ''''-''''''
			EXEC(@SQLFN1)
		END
		SET @FromDate3=dateadd(d,1,@FromDate3)
		SET @Count=@Count +1
	END	 
	
	--Present
	--update #AllEmpInOutDetails set Present=a.total from #AllEmpInOutDetails
	--inner join
	--(
	--	select 	Employee_code_Id,sum(case when FNAttendanceCode=''Present'' then 0.5 else 0 end)+
	--							 sum(case when ANAttendanceCode=''Present'' then 0.5 else 0 end) as total 
	--	from #TempProcessedData group by Employee_code_Id
	--)as a on a.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----Absent
	--update #AllEmpInOutDetails set Absent=sum(case when FNAttendanceCode=''Absent'' then 0.5 else 0 end)+
	--									   sum(case when ANAttendanceCode=''Absent'' then 0.5 else 0 end)  from #TempProcessedData 
	--inner join #AllEmpInOutDetails 
	--on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----Ot Mins
	----update #AllEmpInOutDetails set TotalOT=sum(OtMins)from #TempProcessedData 
	----inner join #AllEmpInOutDetails on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	----NFHolidays
	--update #AllEmpInOutDetails set Absent=sum(case when FNAttendanceCode=''Holiday'' then 0.5 else 0 end)+
	--									   sum(case when ANAttendanceCode=''Holiday'' then 0.5 else 0 end)  from #TempProcessedData 
	--inner join #AllEmpInOutDetails 
	--on #TempProcessedData.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	
	--TotalWorkingDays
	--insert into #TotalWorkedDays select E.Employee_code_Id,
	--sum(case 
	--when FNAttendanceCode=''Present'' and ANAttendanceCode=''Present'' then 1   
	--when FNAttendanceCode=''Present'' and ANAttendanceCode=''Absent'' then 0.5 
	--when FNAttendanceCode=''Absent'' and ANAttendanceCode=''Present'' then 0.5                 
	--when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then 1
	--when FNAttendanceCode=''RH'' and ANAttendanceCode=''RH'' then 1
	--when FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' and (InTime<>''00:00'' or OutTime<>''00:00'') then  1                  
	--when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and  (OutTime is null or OutTime='''') then 0.5
	--when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)>= cast(S.Shift_SecondHalf_StartTime as datetime)) then 1
	--when (FNAttendanceCode=''Present'') and(anattendanceCode=''Holiday'') and S.Shift_SecondHalf_StartTime is not null and (cast(OutTime as datetime)< cast(S.Shift_SecondHalf_StartTime as datetime)) then 0.5
	--when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and (InTime is null or InTime='''') then 0.5
	--when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and (cast(InTime as datetime)<= cast(S.Shift_FirstHalf_EndTime as datetime)) then 1
	--when (anattendanceCode=''Present'') and(FNAttendanceCode=''Holiday'') and S.Shift_FirstHalf_EndTime is not null and  (cast(InTime as datetime)> cast(S.Shift_FirstHalf_EndTime as datetime)) then 0.5  
	--when fnattendanceCode=''Present'' and anattendanceCode not in(''Holiday'',''Absent'',''Present'',''Restricted Holiday'',''Weekly Off'') then 0.5
	--when anattendanceCode=''Present'' and fnattendanceCode not in(''Holiday'',''Absent'',''Present'',''Restricted Holiday'',''Weekly Off'') then 0.5
	--else 0
	--end)
	--from #TempProcessedData C inner join Ta_Tbl_Employee E on E.SwipeCardNo=C.Employee_code_Id 
	--Left Outer join  TA_Tbl_Shift S on S.Shift_Id=C.ShiftId 
	--where (Date between @local_FromDate1 and @local_ToDate1) and ((InTime<>''00:00'' or InTime is not null )
	--or (OutTime<>''00:00'' or OutTime is not null) or fnattendanceCode in (''Tour'',''Training'') or anattendanceCode in (''Tour'',''Training''))
	--group by E.Employee_code_Id
	--update #AllEmpInOutDetails set CountDays = #TotalWorkedDays.TotalWorkedDays from #TotalWorkedDays inner join #AllEmpInOutDetails on #TotalWorkedDays.Employee_code_Id=#AllEmpInOutDetails.Employee_code_Id
	
	--update #AllEmpInOutDetails set TotalOT=''0'' 
	
	select
	ROW_NUMBER()over(order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name) SlNo,
	Employee_Code_Id,
	Name,
	Designation, 
	F_Day1,
	F_Day2,
	F_Day3,
	F_Day4,
	F_Day5,
	F_Day6,
	F_Day7,
	F_Day8,
	F_Day9 ,
	F_Day10 ,
	F_Day11 ,
	F_Day12 ,
	F_Day13 ,
	F_Day14 ,
	F_Day15 ,
	F_Day16 ,
	F_Day17 ,
	F_Day18 ,
	F_Day19 ,
	F_Day20 ,
	F_Day21 ,
	F_Day22 ,
	F_Day23 ,
	F_Day24 ,
	F_Day25 ,
	F_Day26 ,
	F_Day27 ,
	F_Day28 ,
	F_Day29 ,
	F_Day30 ,
	F_Day31,	
	EF_Day1=Replace(F_Day1,''#'',Space(2)),
	EF_Day2=Replace(F_Day2,''#'',Space(2)),
	EF_Day3=Replace(F_Day3,''#'',Space(2)),
	EF_Day4=Replace(F_Day4,''#'',Space(2)),
	EF_Day5=Replace(F_Day5,''#'',Space(2)),
	EF_Day6=Replace(F_Day6,''#'',Space(2)),
	EF_Day7=Replace(F_Day7,''#'',Space(2)),
	EF_Day8=Replace(F_Day8,''#'',Space(2)),
	EF_Day9=Replace(F_Day9,''#'',Space(2)),
	EF_Day10=Replace(F_Day10,''#'',Space(2)),
	EF_Day11=Replace(F_Day11 ,''#'',Space(2)),
	EF_Day12=Replace(F_Day12 ,''#'',Space(2)),
	EF_Day13=Replace(F_Day13 ,''#'',Space(2)),
	EF_Day14=Replace(F_Day14 ,''#'',Space(2)),
	EF_Day15=Replace(F_Day15 ,''#'',Space(2)),
	EF_Day16=Replace(F_Day16 ,''#'',Space(2)),
	EF_Day17=Replace(F_Day17 ,''#'',Space(2)),
	EF_Day18=Replace(F_Day18 ,''#'',Space(2)),
	EF_Day19=Replace(F_Day19 ,''#'',Space(2)),
	EF_Day20=Replace(F_Day20 ,''#'',Space(2)),
	EF_Day21=Replace(F_Day21 ,''#'',Space(2)),
	EF_Day22=Replace(F_Day22 ,''#'',Space(2)),
	EF_Day23=Replace(F_Day23 ,''#'',Space(2)),
	EF_Day24=Replace(F_Day24 ,''#'',Space(2)),
	EF_Day25=Replace(F_Day25 ,''#'',Space(2)),
	EF_Day2=Replace(F_Day26 ,''#'',Space(2)),
	EF_Day27=Replace(F_Day27 ,''#'',Space(2)),
	EF_Day28=Replace(F_Day28 ,''#'',Space(2)),
	EF_Day29=Replace(F_Day29 ,''#'',Space(2)),
	EF_Day30=Replace(F_Day30 ,''#'',Space(2)),
	EF_Day31=Replace(F_Day31 ,''#'',Space(2))	
	from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	select * from #TempHeader	
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #TempProcessedData
	drop table #TempEmployee	
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOut]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOut]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_RptEmployeeInOut '''',''2009/04/01'',''2012/04/30'','''',0,0,0,''SuperAdmin'',''0'',''1'',0,0,''Both''
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOut]      
(
	@EmployeeID VarChar(50), 
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)      
AS      
BEGIN   
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--select * from #LevelRights
	--Employee Level Indexes
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,
		[Clk_CompId] varchar(10),
		[Clk_EmpId] nvarchar(20),
		[Clk_InDeviceId] nvarchar(20),
		[Clk_InDate] datetime,
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25),
		[Clk_OutDeviceId] nvarchar(20),
		[Clk_OutDate] datetime,
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25),
		[Clk_Process] nvarchar(1),
		[Clk_Remarks] nvarchar(100),
		[Clk_User] nvarchar(20),
		[Clk_Date] datetime,
		[Clk_Status] char(1),
		[IsVoid] bit
	)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId]  ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
	If Not (@EmpSwipeCard = '''')  
			Begin  
				Set @sqlCommon = @sqlCommon + '' And SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			End
		if not(@EmployeeId='''' or @EmployeeId=''0'')  
			begin  
				set @sqlCommon = @sqlCommon + '' and (Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
			end 
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	Execute(@sqlEmpLevel + @sqlCommon)
	--Employee Designation insert in Temporary table
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(100)) + '''''')''
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
	Execute(@sqlEmpCategory)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	/****** Object:  Index [IDX_EmpSwipeCardNo]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmpSwipeCardNo] ON [dbo].[#TempEmployee] 
	(
		[EmpSwipeCardNo] ASC
	)ON [PRIMARY]
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	--select * from #TempEmployee
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @sqlCommonEmpId nvarchar(1000)
	set @sqlCommonEmpId=''''
	If Not (@EmpSwipeCard = '''')  
			Begin  
				Set @sqlCommonEmpId = @sqlCommonEmpId + '' And Clk_EmpId = '''''' + @EmpSwipeCard + '''''' ''  
			End
	set @sqlTempProcessedData=	
	''insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails
	where ta_tbl_clockdetails.IsVoid=0 
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,''''''+cast(@FromDate as nvarchar(11))+'''''', 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(11))+'''''', 102)''
	--select * from #TempClockDetails
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20),Shift_ID int,Date datetime)
	/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	)ON [PRIMARY]
	Declare @sqlCommonEmployee_Code_Id nvarchar(1000)
	set @sqlCommonEmployee_Code_Id=''''
	If Not (@EmpSwipeCard = '''')  
			Begin  
				Set @sqlCommonEmployee_Code_Id = @sqlCommonEmployee_Code_Id + '' and (TA_Tbl_ProcessedData.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''    
			End
	set @sqlTempProcessedData1=	
	''insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date 
	from TA_Tbl_ProcessedData inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,''''''+cast( @FromDate as nvarchar(50))+'''''', 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102))''
	Execute(@sqlTempProcessedData +@sqlCommonEmpId)	
		Execute(@sqlTempProcessedData1+@sqlCommonEmployee_Code_Id)	 
--select * from #TempProcessedData
		 -- SET NOCOUNT ON added to prevent extra result sets from      
		 -- interfering with SELECT statements.      
		 Declare @SelectSQL As Varchar(8000)      
		 Set @EmployeeName = isnull(@EmployeeName,'''') + ''%''      
		 Set @SelectSQL = '' ''        
		Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id, ''      
		Set @SelectSQL = @SelectSQL + ''ltrim(ED.Employee_FirstName) + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',''      
		Set @SelectSQL = @SelectSQL + '' case isnull(CD.Clk_InTime,'''''''') when '''''''' then ''''Missing In'''' else right(convert(varchar(20),CD.Clk_InTime,100),7) end as InTime ,''      
		Set @SelectSQL = @SelectSQL + '' case isnull(CD.Clk_OutTime,'''''''') when '''''''' then ''''Missing Out'''' else right(convert(varchar(20),CD.Clk_OutTime,100),7) end as OutTime,CONVERT(VARCHAR,CD.Clk_Date,101) as ClockDate,ED.Gender FROM TA_Tbl_Employee ED ''      
		set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
   		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date''   
		Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and ED.employee_status=1 and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + isnull(ED.Employee_LastName,'''''''') like '''''' + @EmployeeName + '''''' ''  
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
		-- If (@EmployeeId <> '''' and @EmployeeId is not null)      
		-- Begin      
		--  Set @SelectSQL = @SelectSQL + ''And ED.employee_code_id = '''''' + @EmployeeId + '''''' ''      
		-- End      
		--If (@EmpSwipeCard <> '''' and @EmpSwipeCard is not null)  
		-- Begin  
		--  Set @SelectSQL = @SelectSQL + ''And ED.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		-- End
		if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		if(@shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  PD.Shift_Id = '' +  cast(@shift  as nvarchar(20))   
		end 
		 If (@FromDate <> '''')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + ''And CD.Clk_Date >= '''''' + @FromDate + '''''' ''      
		 End      
		 If (@ToDate <> '''')      
		 Begin      
		  Set @SelectSQL = @SelectSQL + ''And CD.Clk_Date <= '''''' + @ToDate + '''''' ''      
		 End      
		--if(@employeeCategory<>0)
		--begin
		--	set @SelectSQL = @SelectSQL + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar) 
		--end
		--if(@employeeType<>0)
		--begin
		--	set @SelectSQL = @SelectSQL + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar) 
		--end   
		--if(@DesignationID<>0)
		--begin
		--	  set @SelectSQL = @SelectSQL + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		--end	
		if(@Gender<>''Both'')
		begin
			  set @SelectSQL = @SelectSQL + '' and ED.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end  
		Set @SelectSQL = @SelectSQL + '' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc''      
 	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay  
	drop table #LevelRights  
	drop table #TempEmployee  
	drop table #TempClockDetails    
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistoryNew '''',''03/26/2009'','''',0,'''',''47'',0,0,''SuperAdmin'',7,'''',323,0,''Both''
-- Description:	Report Employee History Details
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew_Arabic]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		declare @sqlQuery1 as nvarchar(4000)
		declare @sqlQuery2  as nvarchar(4000)
		declare @sqlQuery3  as nvarchar(4000)
		declare @sqlQuery4  as nvarchar(4000)
		declare @sqlQuery5  as nvarchar(4000)
		declare @sqlCommon  as varchar(8000)
		declare @EmployeeLevel1 as nvarchar(50)
        set @EmployeeLevel1= (select (N''????? ??????''))
        declare @EmployeeDesignation1 as nvarchar(50)
        set @EmployeeDesignation1= (select (N''???? ??????''))
        declare @EmployeeCategory1 as nvarchar(50)
        set @EmployeeCategory1= (select (N''??? ??????''))
        declare @EmployeeType1 as nvarchar(50)
        set @EmployeeType1= (select (N''??? ??????''))
        declare @Employeebasicpay1 as nvarchar(50)
        set @Employeebasicpay1= (select (N''???? ??????''))
        declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	set @sqlCommon=''''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlCommon = @sqlCommon + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		if not(@fromDat='''')		
		begin
		set @sqlCommon = @sqlCommon + '' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''		End
		if not (@ToDat='''')
		begin
		set @sqlCommon = @sqlCommon + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		end
		if not(@EmployeeName='''')
		begin
			Declare @Tempname nvarchar(200)
         set @Tempname= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
	     set @sqlCommon = @sqlCommon + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 
		--	set @sqlCommon = @sqlCommon + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' +  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if not (@EmployeeId='''')
		begin
			set @sqlCommon = @sqlCommon + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
		end
		If Not (@EmpSwipeCard = '''')  
		Begin  
			  Set @sqlCommon = @sqlCommon + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
		if not (@EmployeeCategory=0)
		begin
			set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))
		end
		if(@DesignationID<>0)
		begin
			  set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	    if(@Gender<>''Both'')
		begin
			  set @sqlCommon = @sqlCommon + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
--Select employee level
set @sqlQuery1 = ''''
		set @sqlQuery1 = @sqlQuery1 + ''SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery1 = @sqlQuery1 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery1 = @sqlQuery1 + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_EmployeeLevel.EffectiveDate as EffectiveDate,  N'''''' + @EmployeeLevel1 + '''''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender ''
		set @sqlQuery1 = @sqlQuery1 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery1 = @sqlQuery1 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery1 = @sqlQuery1 + @sqlCommon
		set @sqlQuery2 = '' Union ''
		set @sqlQuery2 = @sqlQuery2 + ''SELECT    distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery2 = @sqlQuery2 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery2 = @sqlQuery2 + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as name,TA_Tbl_EmployeeDesignation.EffectiveDate as EffectiveDate,  N'''''' + @EmployeeDesignation1 + '''''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery2 = @sqlQuery2 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery2 = @sqlQuery2 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery2 = @sqlQuery2 + @sqlCommon
set @sqlQuery3 = '' Union ''
		set @sqlQuery3 = @sqlQuery3 + ''SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery3 = @sqlQuery3 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery3 = @sqlQuery3 + '' dbo.TA_Tbl_Category.CategoryName AS name,TA_Tbl_EmployeeCategory.EffectiveDate as EffectiveDate,  N'''''' + @EmployeeCategory1 + '''''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery3 = @sqlQuery3 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery3 = @sqlQuery3 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery3 = @sqlQuery3 + @sqlCommon
set @sqlQuery4 = '' Union ''
		set @sqlQuery4 = @sqlQuery4 + ''SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery4 = @sqlQuery4 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery4 = @sqlQuery4 + '' dbo.TA_Tbl_Type.TypeName AS name,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate,  N'''''' + @EmployeeType1 + '''''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery4 = @sqlQuery4 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery4 = @sqlQuery4 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery4 = @sqlQuery4 + @sqlCommon
set @sqlQuery5 =  '' Union ''
		set @sqlQuery5 = @sqlQuery5 + ''SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery5 = @sqlQuery5 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery5 = @sqlQuery5 + '' cast(dbo.TA_Tbl_EmployeePay.BasicPay as nvarchar) AS name,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate,  N'''''' + @Employeebasicpay1 + '''''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''		
		set @sqlQuery5 = @sqlQuery5 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId''		
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery5 = @sqlQuery5 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
	    set @sqlQuery5 = @sqlQuery5 + @sqlCommon
		exec(@sqlQuery1 + @sqlQuery2 + @sqlQuery3 + @sqlQuery4 + @sqlQuery5)
		drop table #LevelRights
--exec(@sqlQuery1)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeHistoryNew]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeHistoryNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Prabakaran.P
-- Created  date: 28-May-08   
-- Proc_Ta_RptEmployeeHistoryNew '''',''03/26/2009'','''',0,'''',''47'',0,0,''SuperAdmin'',7,'''',323,0,''Both''
-- Description:	Report Employee History Details
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_RptEmployeeHistoryNew]
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		declare @sqlQuery1 as varchar(8000)
		declare @sqlQuery2  as varchar(8000)
		declare @sqlQuery3  as varchar(8000)
		declare @sqlQuery4  as varchar(8000)
		declare @sqlQuery5  as varchar(8000)
		declare @sqlCommon  as varchar(8000)
		declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	set @sqlCommon=''''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlCommon = @sqlCommon + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		if not(@fromDat='''')		
		begin
		set @sqlCommon = @sqlCommon + '' And     (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''		End
		if not (@ToDat='''')
		begin
		set @sqlCommon = @sqlCommon + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		end
		If Not (@EmpSwipeCard = '''')  
		Begin  
			  Set @sqlCommon = @sqlCommon + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
		if not (@EmployeeCategory=0)
		begin
			set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))
		end
		if(@DesignationID<>0)
		begin
			  set @sqlCommon = @sqlCommon + '' and TA_Tbl_EmployeeDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	    if(@Gender<>''Both'')
		begin
			  set @sqlCommon = @sqlCommon + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
--Select employee level
set @sqlQuery1 = ''''
		set @sqlQuery1 = @sqlQuery1 + ''SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery1 = @sqlQuery1 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery1 = @sqlQuery1 + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_EmployeeLevel.EffectiveDate as EffectiveDate, ''''Employee Level '''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender ''
		set @sqlQuery1 = @sqlQuery1 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery1 = @sqlQuery1 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery1 = @sqlQuery1 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		set @sqlQuery1 = @sqlQuery1 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery1=@sqlQuery1 + @sqlCommon
		set @sqlQuery2 = '' Union ''
		set @sqlQuery2 = @sqlQuery2 + ''SELECT    distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery2 = @sqlQuery2 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery2 = @sqlQuery2 + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as name,TA_Tbl_EmployeeDesignation.EffectiveDate as EffectiveDate, ''''Employee Designation '''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery2 = @sqlQuery2 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery2 = @sqlQuery2 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
			If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery2 = @sqlQuery2 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		set @sqlQuery2 = @sqlQuery2 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery2 = @sqlQuery2 + @sqlCommon
set @sqlQuery3 = '' Union ''
		set @sqlQuery3 = @sqlQuery3 + ''SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery3 = @sqlQuery3 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery3 = @sqlQuery3 + '' dbo.TA_Tbl_Category.CategoryName AS name,TA_Tbl_EmployeeCategory.EffectiveDate as EffectiveDate, ''''Employee Category '''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery3 = @sqlQuery3 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery3 = @sqlQuery3 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
			If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery3 = @sqlQuery3 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		set @sqlQuery3 = @sqlQuery3 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery3 = @sqlQuery3 + @sqlCommon
set @sqlQuery4 = '' Union ''
		set @sqlQuery4 = @sqlQuery4 + ''SELECT  distinct  dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery4 = @sqlQuery4 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery4 = @sqlQuery4 + '' dbo.TA_Tbl_Type.TypeName AS name,TA_Tbl_EmployeeType.EffectiveDate as TypeEffectiveDate, ''''Employee Type '''' as HistoryType,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender  ''
		set @sqlQuery4 = @sqlQuery4 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery4 = @sqlQuery4 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
			If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery4 = @sqlQuery4 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		set @sqlQuery4 = @sqlQuery4 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery4 = @sqlQuery4 + @sqlCommon
set @sqlQuery5 =  '' Union ''
		set @sqlQuery5 = @sqlQuery5 + ''SELECT   distinct dbo.TA_Tbl_Employee.Employee_code_Id as employee_id, status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery5 = @sqlQuery5 + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname, ''
		set @sqlQuery5 = @sqlQuery5 + '' cast(dbo.TA_Tbl_EmployeePay.BasicPay as nvarchar) AS name,dbo.TA_Tbl_EmployeePay.EffectiveDate as BPayEffectiveDate, ''''Employee Basic Pay '''' as HistoryType ,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender ''		
		set @sqlQuery5 = @sqlQuery5 + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER  JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN dbo.TA_Tbl_EmployeePay on dbo.ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId''		
		set @sqlQuery5 = @sqlQuery5 + '' INNER JOIN #LevelRights on #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery5 = @sqlQuery5 + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
			If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery5 = @sqlQuery5 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
		set @sqlQuery5 = @sqlQuery5 + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')''		
		set @sqlQuery5 = @sqlQuery5 + @sqlCommon
		exec(@sqlQuery1 + @sqlQuery2 + @sqlQuery3 + @sqlQuery4 + @sqlQuery5)
		drop table #LevelRights
--exec(@sqlQuery1)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeCompOffStatus]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeCompOffStatus]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*   
Procedure Name	:	Proc_TA_EmployeeCompOffOTSanction
Tables Included :	TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
					TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
					TA_Tbl_Grade,ta_tbl_shift
Modified On		:   20-Jun-2016
Description		:	Report Issue
Modified By		:   Karthikeyan.R
Description		:	Remove The Date Convertion In Expaire Date Calculation
EXEC Proc_TA_RptEmployeeCompOffStatus @FromDate=''2015-01-01 00:00:00'',@ToDate=''2015-10-03 00:00:00'',@EmpId=N'''',@ShiftId=0,@EmployeeName=N'''',@LevelID=N''0'',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''1'',@Status=N''All'',@EmpSwipeCard=N'''',@ParentId=0,@DesignationID=0,@Gender=N''Both''
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeCompOffStatus]
(
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmpId VARCHAR(100),
	@ShiftId INT,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeCategory INT, 
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@Status VARCHAR(20)	,
	@EmpSwipeCard VARCHAR(20),
	@ParentId INT,
	@DesignationID INT,
    @Gender VARCHAR(10),
    @EmpAutoID int
)
AS
BEGIN
	set nocount on;
	DECLARE @SQLQuery VARCHAR(MAX)
	SET @SQLQuery = ''''
	--Get the Current date time format
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	--End
--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	CREATE TABLE #LevelRights(LevelId INT)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	INSERT INTO #LevelRights 
		SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ,[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ,[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@empId,@employeeCategory
	--To split up the comma separated values
	if(@empId is not null and @empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@empId)
		end
			if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
If Not (@empId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo ''
		End
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
execute(@sqlEmpLevel)	
--AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''''00:00''''), 108) != ''''00:00''''
--AND CONVERT(VARCHAR(5), DATEADD(MI, ISNULL(PD.OtMins, 0), ''''00:00''''), 108) != ''''00:00'''' 
	SET @SQLQuery = ''SELECT Emp.SwipeCardNo, RTRIM(LTRIM(Emp.Employee_FirstName + SPACE(1) + ISNULL(Emp.Employee_LastName , ''''''''))) EmployeeName,''
	SET @SQLQuery = @SQLQuery + '' Emp.Gender,case	when '' + CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR(11), PD.[Date], ''+ CONVERT(varchar,@dateFormat) +''),'''' '''',''''-'''') else CONVERT(VARCHAR(11), PD.[Date], ''+ CONVERT(varchar,@dateFormat) +'') end AS [Date], PD.HrsExtra,PD.ActHrsExtra, PD.OTSanctioned, PD.CompoffSanctioned, PD.OverTimeStatus, PD.CompOffSatus, ISNULL(S.Shift_ShortName, ''''Off'''') AS Shift_ShortName , PD.[NoOfDaysTaken], PD.ExtraMins,PD.ActExtraMins FROM''
	SET @SQLQuery = @SQLQuery + '' (SELECT OTS.Employee_Id, OTS.Process_RecID,  OTS.[Date] [Date], OTS.HrsExtra,isnull(OTS.ActHrsExtra,OTS.HrsExtra) [ActHrsExtra], (CASE WHEN OTS.OTEligible = 1 THEN OTS.HrsExtra ELSE ''''00:00'''' END) OTSanctioned,''
	SET @SQLQuery = @SQLQuery + '' (CASE WHEN OTS.CompOffEligible = 1 THEN OTS.HrsExtra ELSE ''''00:00'''' END) CompoffSanctioned, OTS.OverTimeStatus, (CASE WHEN OTS.OverTimeStatus = ''''Approved'''' AND OTS.CompOffEligible = 1 THEN ''''Taken'''' ELSE ''''-'''' END) [CompOffSatus], PD.Employee_Code_Id, PD.Shift_Id, (ISNULL(OTS.NoOfDays, 0.0) - ISNULL(OTS.RemainingDays, 0.0)) [NoOfDaysTaken], OTS.ExtraMins,ISNULL(OTS.ActExtraMins,OTS.ExtraMins) [ActExtraMins] FROM TA_Tbl_OverTimeStatus OTS''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OTS.Process_RecID''
	SET @SQLQuery = @SQLQuery + '' WHERE PD.OtMins != 0 AND OTS.NoOfDays > OTS.RemainingDays AND ISNULL(OTS.LeaveApplicationId, '''''''') != '''''''' AND PD.[Date] BETWEEN '''''' + CONVERT(VARCHAR(11), @FromDate, 101) + '''''' AND '''''' + CONVERT(VARCHAR(11), @ToDate, 101) + '''''' UNION ALL'' 
	SET @SQLQuery = @SQLQuery + '' SELECT OTS.Employee_Id, OTS.Process_RecID, CONVERT(VARCHAR(11), OTS.[Date], 101) [Date], OTS.HrsExtra,isnull(OTS.ActHrsExtra,OTS.HrsExtra) [ActHrsExtra], (CASE WHEN OTS.OTEligible = 1 THEN OTS.HrsExtra ELSE ''''00:00'''' END) OTSanctioned,''
	SET @SQLQuery = @SQLQuery + '' (CASE WHEN OTS.CompOffEligible = 1 THEN OTS.HrsExtra ELSE ''''00:00'''' END) CompoffSanctioned, OTS.OverTimeStatus, (CASE WHEN ISNULL(OTS.DateToExpired, PD.[Date]) < GETDATE() AND OTS.CompOffEligible = 1 THEN ''''Expired'''' WHEN OTS.CompOffEligible = 0 THEN ''''-'''' ELSE ISNULL(OTS.CompOffSatus, OTS.OverTimeStatus) END) [CompOffSatus], PD.Employee_Code_Id, PD.Shift_Id, ISNULL(OTS.RemainingDays, 0.0) [NoOfDaysTaken], OTS.ExtraMins,ISNULL(OTS.ActExtraMins,OTS.ExtraMins) [ActExtraMins] FROM TA_Tbl_OverTimeStatus OTS''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OTS.Process_RecID''
	SET @SQLQuery = @SQLQuery + '' WHERE PD.OtMins != 0 AND (OTS.RemainingDays > 0.0 OR OTS.RemainingDays IS NULL) AND ISNULL(OTS.CompOffSatus, ''''Not Taken'''') != ''''Taken'''' AND PD.[Date] BETWEEN '''''' + CONVERT(VARCHAR(11), @FromDate, 101) + '''''' AND '''''' + CONVERT(VARCHAR(11), @ToDate, 101) + '''''' UNION ALL''
	SET @SQLQuery = @SQLQuery + '' SELECT EMP.Employee_Id, PD.Process_Rec_ID, CONVERT(VARCHAR(11), PD.[Date], 101) [Date],''
	SET @SQLQuery = @SQLQuery + '' (CASE WHEN PD.HrsOT != ''''00:00'''' THEN PD.HrsOT WHEN PD.NormOT != ''''00:00'''' THEN PD.NormOT WHEN PD.OffOT != ''''00:00'''' THEN PD.OffOT WHEN PD.HolOT != ''''00:00'''' THEN PD.HolOT END) [HrsExtra],''
SET @SQLQuery = @SQLQuery + '' (CASE WHEN isnull(PD.ActHrsOT,PD.HrsOT) != ''''00:00'''' THEN isnull(PD.ActHrsOT,PD.HrsOT) WHEN isnull(PD.ActNormOT,PD.NormOT) != ''''00:00'''' THEN isnull(PD.ActNormOT,PD.NormOT) WHEN isnull(PD.ActOffOT,PD.OffOT) != ''''00:00'''' THEN isnull(PD.ActOffOT,PD.OffOT) WHEN isnull(PD.ActHolOT,PD.HolOT) != ''''00:00'''' THEN isnull(PD.ActHolOT,PD.HolOT) END) [ActHrsExtra],''	
	SET @SQLQuery = @SQLQuery + '' ''''00:00'''' OTSanctioned, ''''00:00'''' CompoffSanctioned, ISNULL(PD.OverTimeStatus, ''''Pending'''') OverTimeStatus,''
	SET @SQLQuery = @SQLQuery + '' ISNULL(PD.OverTimeStatus, ''''Pending'''') [CompOffSatus],''
	SET @SQLQuery = @SQLQuery + '' PD.Employee_Code_Id,PD.Shift_Id, 0.0 [NoOfDaysTaken],PD.OtMins, isnull(PD.ActOtMins,PD.OtMins) [OtMins]  FROM TA_Tbl_ProcessedData PD''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo''	
	SET @SQLQuery = @SQLQuery + '' WHERE Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1 AND PD.OtMins != 0 AND PD.Process_Rec_ID NOT IN (SELECT Process_RecID FROM TA_Tbl_OverTimeStatus) AND PD.[Date] BETWEEN '''''' + CONVERT(VARCHAR(11), @FromDate, 101) + '''''' AND '''''' + CONVERT(VARCHAR(11), @ToDate, 101) + '''''') PD'' 
	SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.EmployeeId = Emp.Employee_Id''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id = ELP.LeavePolicy_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId''
	SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_Shift S ON S.Shift_Id = PD.Shift_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel EL ON EL.EmployeeId = Emp.Employee_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation ED ON ED.EmployeeId = Emp.Employee_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType ET ON ET.EmployeeId = Emp.Employee_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory EC ON EC.EmployeeId = Emp.Employee_Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = EL.LevelId''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
	SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''	 
	SET @SQLQuery = @SQLQuery + '' WHERE Emp.OT_Eligible = 1 AND Emp.CompOff_Eligible = 1''
	SET @SQLQuery = @SQLQuery + '' AND Emp.IsDeleted = 0 AND Emp.Employee_Status = 1''
	SET @SQLQuery = @SQLQuery + '' AND YS.IsActive = 1 AND Emp.Report_Exclude = 0 AND'' --LP.OtDayWise = 1 AND 
	SET @SQLQuery = @SQLQuery + '' ((Emp.Employee_Status=1) OR (Emp.Employee_Status = 0 AND CONVERT(NVARCHAR(11), Emp.InActiveDate, 102) >= CONVERT(NVARCHAR(11), PD.[Date], 102)))''	
	IF(@UserGroupName <> ''SuperAdmin'')
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel  
	END
	IF(@ShiftId<>0) 
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND PD.[Shift_Id] = '' + CAST(@ShiftId AS NVARCHAR(50))  
	END
	--IF NOT(@EmployeeName = '''')
	--BEGIN
	--Declare @Tempname nvarchar(200)
 --        set @Tempname= ''(Emp.Employee_FirstName + '''' '''' + isnull(Emp.Employee_LastName,'''''''')''
	--     set @sqlQuery = @sqlQuery + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 
	--	--SET @SQLQuery = @SQLQuery + '' AND (Emp.Employee_FirstName + '''' '''' + ISNULL(Emp.Employee_LastName, '''''''') LIKE '''''' + @EmployeeName + ''%'''')''
	--END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@EmployeeCategory AS VARCHAR(10))
	END
	IF(@EmployeeType<>0)
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@EmployeeType AS VARCHAR(10))
	END
	IF NOT(@EmpSwipeCard = '''')  
    BEGIN
		SET @SQLQuery = @SQLQuery + '' AND Emp.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
	END
	--IF NOT(@EmpId='''')
	--BEGIN
	--	SET @SQLQuery = @SQLQuery + '' AND Emp.Employee_Code_Id = '''''' + CAST(@EmpId AS VARCHAR(50)) + ''''''''
	--END
	IF(@DesignationID<>0)
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND ED.DesignationId = '' + CAST(@DesignationID AS NVARCHAR(8))
	END
	IF(@Gender<>''Both'')
	BEGIN
		SET @SQLQuery = @SQLQuery + '' AND Emp.Gender = '''''' + CAST(@Gender AS NVARCHAR(8)) + ''''''''
	END
	if(@isReportingto > 0)
    BEGIN
       set @SQLQuery = @SQLQuery + '' and (Emp.Employee_ID IN (select * from #EmployeeIds)) ''  
    END
	IF NOT(@Status = '''' OR @Status = ''All'')
	BEGIN
		IF(@Status = ''Pending'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (PD.OvertimeStatus IS NULL OR PD.OvertimeStatus = '''''' + @Status + '''''')''
		END
		ELSE
		BEGIN
		    SET @SQLQuery = @SQLQuery + '' AND PD.OvertimeStatus = '''''' + @status + ''''''''
		END
    END
	SET @SQLQuery = @SQLQuery + '' ORDER BY PD.Employee_Code_Id, PD.[Date]''
	EXEC(@SQLQuery)
--Remove the temporary tables here
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployee]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- ALTER  date: 04August08   
-- Modified By	:	Sashma	
-- Modified On	:	12-May-2011
-- Proc_Ta_RptEmployee '''',''04/Feb/2020'','''',0,'''',''1'',''0'',''0'',''all'',''SuperAdmin'',''0'','''','''',1,0,''Both'',1
-- Description:	Report Employee Details
-- Modified By		:	Gopinath.K
-- Modified Date	:	21-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployee]
(
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@SwipeOpt varchar(10),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
)
AS
BEGIN
	--added by velumani for ASNIP Report
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	
	--print @DATEFORMAT
		---
	if(charIndex(''-'',@ToDat)>0)
		begin
			set @ToDat=(select convert(varchar(30),getdate(),102))
		end
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId]  ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @todat,@EmployeeId
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''SELECT dbo.TA_Tbl_Employee.Employee_code_Id as employee_id,''
	set @sqlQuery = @sqlQuery + ''isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname,
								replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
								TA_Tbl_Employee.Gender,
								replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, 
								Convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as dateJoin,
								convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as dateOfBirth,
								dbo.TA_Tbl_Employee.Nationality,''		
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Visa_No''
	set @sqlQuery = @sqlQuery + '', CASE	WHEN ''+CAST(@DATEFORMAT AS NVARCHAR(10))+''=106 THEN
						REPLACE(CONVERT(VARCHAR, dbo.TA_Tbl_Employee.Visa_expirydate,''+CAST(@DATEFORMAT AS NVARCHAR(10))+''),'''''''',''''-'''') 
				ELSE CONVERT(VARCHAR, dbo.TA_Tbl_Employee.Visa_expirydate,''+CAST(@DATEFORMAT AS NVARCHAR(10))+'') END AS Visa_expirydate,''	
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee.Passport_No''
	set @sqlQuery = @sqlQuery + '', CASE	WHEN ''+CAST(@DATEFORMAT AS NVARCHAR(10))+''=106 THEN
						REPLACE(CONVERT(VARCHAR, dbo.TA_Tbl_Employee.Passport_expirydate,''+CAST(@DATEFORMAT AS NVARCHAR(10))+''),'''''''',''''-'''') 
				ELSE CONVERT(VARCHAR, dbo.TA_Tbl_Employee.Passport_expirydate,''+CAST(@DATEFORMAT AS NVARCHAR(10))+'') END AS Passport_expirydate,''	
				
	set @sqlQuery = @sqlQuery + ''dbo.TA_Tbl_Employee.CustomField1, CASE	WHEN ''+CAST(@DATEFORMAT AS NVARCHAR(10))+''=106 THEN
						REPLACE(CONVERT(VARCHAR, dbo.TA_Tbl_Employee.CustomField2,''+CAST(@DATEFORMAT AS NVARCHAR(10))+''),'''''''',''''-'''') 
				ELSE CONVERT(VARCHAR, dbo.TA_Tbl_Employee.CustomField2,''+CAST(@DATEFORMAT AS NVARCHAR(10))+'') END AS CustomField2,
	
								status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end,''
	set @sqlQuery = @sqlQuery + '' isnull(replace(dept.name,''''&amp;'''',''''&''''),''''-'''') as department''
	set @sqlQuery = @sqlQuery + '' ,dbo.TA_Tbl_Employee.Employee_Id as empAutoId,dbo.TA_Tbl_Employee.Report_Exclude  FROM dbo.TA_Tbl_Employee ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''') ''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
		end
	if not(@fromDat='''')		
		begin
			set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''			End
	if not (@ToDat='''')
		begin
			set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 			end
	if (@SwipeOpt=''Exists'')    
		Begin    
			set @sqlQuery= @sqlQuery +'' And TA_Tbl_Employee.swipecardno is not null and TA_Tbl_Employee.swipecardno!='''''''' '' 
		End 
	if (@SwipeOpt=''Not Exists'')    
		Begin    
			set @sqlQuery= @sqlQuery +'' And (TA_Tbl_Employee.swipecardno is null or TA_Tbl_Employee.swipecardno='''''''') '' 
		End 
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@EmployeeStatus=''Active'')
		begin
			set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_Status = 1) ''
		end		
	else if(@EmployeeStatus=''InActive'')
		begin		
			set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_Status = 0) ''	
		end	
	set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_Employee.Employee_code_Id ''
	print @sqlQuery
	exec(@sqlQuery)
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEarlyEntry]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEarlyEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_RptEarlyEntry '''',''1'',''01/June/2018'',''30/June/2018'','''',0,0,0,''UxHOD Distribution'',''0'','''',0,0,''Both'',1,'''',94
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptEarlyEntry]
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@ExportType int,
	@MINExceptionHOURS AS VARCHAR(6),
	@EmpAutoID int
)  
AS
BEGIN		
	SET NOCOUNT ON;
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_empId varchar(100)
	Declare @local_shift int
	Declare @local_EmployeeName varchar(50)
	Declare @local_LevelID varchar(8000)
	Declare @local_EmployeeCategory int
	Declare @local_EmployeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_ExportType int
	Declare @local_MINExceptionHOURS AS VARCHAR(6)
	Declare @local_EmpAutoID int
	
	Set @local_fromDat=@FromDate
	Set @local_ToDat=@ToDate
	Set @local_empId=@EmployeeID
	Set @local_shift=@shift
	Set @local_EmployeeName=@EmployeeName
	Set @local_LevelID=@LevelID
	Set @local_EmployeeCategory=@EmployeeCategory
	Set @local_EmployeeType=@EmployeeType
	Set @local_UserGroupName=@UserGroupName
	Set @local_EmpSwipeCard=@EmpSwipeCard
	Set @local_ParentId=@ParentId
	Set @local_DesignationID=@DesignationID
	Set @local_Gender=@Gender
	Set @local_ExportType=@ExportType
	Set @local_MINExceptionHOURS=@MINExceptionHOURS
	Set @local_EmpAutoID=@EmpAutoID
	Set @local_GradeLevel=@GradeLevel
	
	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX('':'',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX('':'',@local_MINExceptionHOURS)+1,2)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		shift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		LateEntryReason nvarchar(260),
		Exactshift_StartTime nvarchar(25),
		EarlyInMins int,
		EarlyInHrs varchar(10)
	)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId] ASC  
	)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId] ASC  
	)ON [PRIMARY]	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_empId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_empId,@local_EmployeeType
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_empId,@local_EmployeeCategory
	--To split up the comma separated values
	if(@local_empId is not null and @local_empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@local_empId)
		end	
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@local_empId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData= ''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	If Not (@local_empId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.report_exclude=0 ''
		if(@local_Gender<>''Both'')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + '' and TA_Tbl_Employee.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end	
		if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1= ''insert into #TempProcessedData
	select	#TempEmployee.EmpAutoId,
			pd.Date,
			pd.Employee_Code_Id,
			pd.InTime,
			pd.OutTime,
			pd.Shift_Id,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime),
			pd.Process_Rec_ID,
			pd.LateIn,
			pd.LateInMins,
			pd.LateEntryReason,
			cast(S.Shift_startTime as datetime),
			EarlyInMins,
			EarlyInHrs
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
	inner join ta_tbl_shift S on S.Shift_Id=PD.Shift_Id	
	where pd.InTime is not null AND pd.InTime <> ''''0'''' AND pd.InTime <> ''''00:00'''' and 
	(cast(s.Shift_StartTime as datetime) > cast(PD.InTime AS datetime)) and PD.EarlyEntry=1 AND
	(PD.FNAttendanceCode<>''''CL'''' or PD.ANAttendanceCode<>''''CL'''') and	
	(pd.Date>=CONVERT(DATETIME,''''''+cast(@local_fromDat as nvarchar(50))+'''''', 102) and pd.Date <=CONVERT(DATETIME,''''''+cast(@local_ToDat as nvarchar(50))+'''''', 102))''
	if(@local_shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' and PD.shift_id= ''+  cast (@local_shift as nvarchar(50))
		end
	IF (@local_MINExceptionHOURS<>'''')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND PD.EarlyInMins >= '' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode=''CL'' 
	Declare @SelectSQL As Varchar(8000)  
	Set @EmployeeName = @local_EmployeeName  
	Set @SelectSQL = '' ''
	
	
	Set @SelectSQL = @SelectSQL + ''	SELECT ED.Employee_Code_Id AS CardNo, ''  
	Set @SelectSQL = @SelectSQL + ''	ED.Employee_FirstName + ''  
	Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''  
	Set @SelectSQL = @SelectSQL + ''	replace(L.name,''''&amp;'''',''''&'''')  AS [Level Name],replace(T.TitleName,''''&amp;'''',''''&'''')  AS Designation,Gender as Gender, ''  
	set @SelectSQL = @SelectSQL + ''	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, pd.Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
											else CONVERT(VARCHAR, pd.Date, ''+CONVERT(varchar,@dateFormat)+'') 
									end as Date,
									replace(sh.shift_shortName,''''&amp;'''',''''&'''') as shift_shortName,
									case when (select TimeFormat from TA_Tbl_DateandTimeFormat)=''''hh:mm tt'''' then PD.Shift_StartTime else CONVERT(varchar(5), DATEADD(minute,0,convert(datetime,PD.Shift_StartTime,0)), 114) end as Shift_StartTime, ''
	Set @SelectSQL = @SelectSQL + ''	CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,pd.intime,0)), 114)
											ELSE SUBSTRING(pd.intime,13,5)+'''' '''' + SUBSTRING(pd.intime,18,2) 
									END InTime,
									case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
											''''0''''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) 
										else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) 
									end
									+ '''':'''' + 
									case	when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''''00''''
											else	case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
															''''0''''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
														else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) 
													end
									end As EarlyBy,
									PD.LateEntryReason as Reason,
									((SUBSTRING(ISNULL(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''''0''''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '''':'''' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''''00''''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''''0''''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end,''''00:00''''),0,CHARINDEX('''':'''',case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''''0''''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '''':'''' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''''00''''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''''0''''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end))*60) + (SUBSTRING(ISNULL(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''''0''''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '''':'''' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''''00''''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''''0''''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end,''''00:00''''),(LEN(case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60))=1 then
									''''0''''+convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) else
									convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))/60) end
							+ '''':'''' + case when convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)=0 then ''''00''''
									else  case when len(convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60))=1 then
									''''0''''+ convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60)
									else convert(varchar(20),cast(datediff(mi,PD.InTime,PD.Exactshift_StartTime)as varchar(20))%60) end
									end)-1),2))) AS EarlyInMins,PD.Process_Rec_ID,pd.Date as format
									FROM TA_Tbl_Employee ED  ''  
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId ''  
	Set @SelectSQL = @SelectSQL + '' INNER JOIN ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID ''	
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid=ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id ''    
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= ED.Employee_Id ''  
	Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId ''  
	SET @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID''  
	set @SelectSQL = @SelectSQL + '' inner join #EmpCategory on ED.Employee_Id = #EmpCategory.EmployeeId''  	
	set @SelectSQL = @SelectSQL + '' inner join #EmpType on ED.Employee_Id = #EmpType.EmployeeId''  	
	Set @SelectSQL = @SelectSQL + '' INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id ''  
	set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''   
	Set @SelectSQL = @SelectSQL + '' Where 1=1 and 
									( (ED.Employee_Status=1) or
									( ED.Employee_Status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102))
									) ''
	Set @SelectSQL = @SelectSQL + '' and (cast(PD.Exactshift_StartTime as datetime) > cast(PD.InTime AS datetime)) AND PD.LateInMins=0  ''  		
	set @SelectSQL = @SelectSQL + '' order by [CardNo],format , pd.Intime,PD.Shift_StartTime''  
	if(@local_ExportType=1)
		begin
			exec (@SelectSQL)  
		end
	else
		begin
			Create table #TempEarlyEntry
			(		
				CardNo nVarchar(30), 
				[Employee Name] nvarchar(100),
				[Level Name] nvarchar(100),
				designation nvarchar(100),
				Gender nvarchar(10),
				Date nvarchar(20),
				shift_shortName nvarchar(4),
				Shift_StartTime nvarchar(20),
				InTime nvarchar(10),
				EarlyBy nvarchar(10),
				Reason nvarchar(200),		
				EarlyInMins decimal(18,2),
				Peocess_Rec_ID int, 
				fromat datetime
			)
			insert into #TempEarlyEntry exec (@SelectSQL)
			create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
			create table #TempDate(ID int identity(1,1),Date nvarchar(20))
			insert into #TempLevelName 
			select distinct [Level Name] from #TempEarlyEntry
			insert into #TempDate 
			select distinct Date from #TempEarlyEntry
			declare @couLevel int
			set @couLevel=(select COUNT(*) from #TempLevelName)
			declare @couDate int
			set @couDate=(select COUNT(*) from #TempDate)
			declare @i int
			set @i=1
			declare @j int
			set @j=1
			declare @SQLString1 nvarchar(Max)
			set @SQLString1=''''
			while @i<=@couLevel
			begin
				declare @Levelstr nvarchar(100)
				set @Levelstr =(select Name from #TempLevelName where ID=@i)
				set @SQLString1 = @SQLString1 + @Levelstr + ''@''
				while @j<=@couDate
				begin
					declare @RowCount int
					set @RowCount=(select COUNT(*) from #TempEarlyEntry where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
					if(@RowCount!=0)
					begin
						set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
					end
					else
					begin
						set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
					end
					set @j=@j+1
				end
				SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
				set @SQLString1 = @SQLString1 + ''#''
				set @j=1
				set @i=@i+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			select @SQLString1 as ''Value''
			drop table #TempDate
			drop table #TempEarlyEntry
			drop table #TempLevelName
		end
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  	
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptDocumentExpiry]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptDocumentExpiry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Senthil
-- ALTER  date: <01-Aug-2007>
-- Description:	<Report - Document Expiry>
-- Proc_Ta_RptDocumentExpiry ''01/01/2009'',''01/01/2030'','''','''','''','''',1,1,''SuperAdmin'',''0'','''',0,0,''Both''
-- =============================================
CREATE          PROCEDURE [dbo].[Proc_Ta_RptDocumentExpiry] 
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @EmpAutoID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	 --Get Current date time format
      DECLARE @dateFormat as int
      DECLARE @date as nvarchar(25)             
      SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
      IF(@date=''dd/MM/yyyy'')
      BEGIN
            SET @dateFormat = 103
      END
      ELSE IF(@date=''MM/dd/yyyy'')
      BEGIN
            SET @dateFormat = 101
      END
      ELSE
      BEGIN
            SET @dateFormat = 106
      END   
      --End
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
if(@EmployeeId is not null and @EmployeeId <> '''')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	if(@Gender<>''Both'')  
		begin  
			set @sqlCommon = @sqlCommon + '' and Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommon = @sqlCommon + '' and (Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 ''
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
			End
	If Not (@EmployeeName = '''')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.SwipeCardNo ''
			End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @TODAT,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @TODAT,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @TODAT,@EMPLOYEEID,@EMPLOYEECATEGORY
		declare @sqlQuery as varchar(8000)
		set @sqlQuery=''''
		set @sqlQuery = @sqlQuery + '' select Passport_No,case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, Passport_expiryDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, Passport_expiryDate, ''+CONVERT(varchar,@dateFormat)+'') end
										 as passport_expiryDate,
										Visa_no,case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, Visa_expiryDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, Visa_expiryDate, ''+CONVERT(varchar,@dateFormat)+'') end
										as visa_expiryDate,
										Ta_tbl_Employee.Employee_Code_Id as employee_id,
										isnull(Employee_FirstName,'''''''') +  space(1) + isnull(Employee_LastName,'''''''')  as empName,
										replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
										ta_tbl_employee.Gender 
										from ta_tbl_employee ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
		SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=#EmpDesignation.DesignationId''
		SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''		
		set @sqlQuery = @sqlQuery + '' where Ta_tbl_Employee.Isdeleted=0 and 
		((employee_Status=1 ))
		and report_exclude=0''
		set @sqlQuery = @sqlQuery + '' And((passport_expirydate >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and passport_expirydate <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102))''
		set @sqlQuery = @sqlQuery + '' or  (visa_expirydate>= CONVERT(DATETIME,'''''' +  cast(@fromDat as nvarchar(11)) + '''''', 102) and visa_expirydate <= CONVERT(DATETIME,'''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		set @sqlQuery = @sqlQuery + '' order by ta_tbl_employee.Employee_Code_Id''		
		exec(@sqlQuery)
 drop table #EmpLevel
 drop table #EmpDesignation
 drop table #EmpType
 drop table #EmpCategory
 --drop table #EmpPay
 drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_RptDiscrepancy]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_RptDiscrepancy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- proc_ta_RptDiscrepancy ''2016/01/01'',''2016/12/31'','''',''0'','''','''',0,0,''SuperAdmin'',''0'','''',0,0,''Both'',0,1
CREATE PROCEDURE [dbo].[proc_ta_RptDiscrepancy]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,[Clk_CompId] varchar(10),
		[Clk_EmpId] nvarchar(50),[Clk_InDeviceId] nvarchar(20),
		[Clk_InDate] datetime,[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25),[Clk_OutDeviceId] nvarchar(20),
		[Clk_OutDate] datetime,[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25),[Clk_Process] nvarchar(1),
		[Clk_Remarks] nvarchar(500),[Clk_User] nvarchar(20),
		[Clk_Date] datetime,[Clk_Status] char(1),[IsVoid] bit
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))	
	create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(20))	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @todat,@empId
	--To split up the comma separated values
	if(@empId is not null and @empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails where ta_tbl_clockdetails.IsVoid=0 
	and (ta_tbl_clockdetails.clk_inTime is null or ta_tbl_clockdetails.clk_outTime is null)
	and ta_tbl_clockdetails.clk_Date >= @fromDat
	and ta_tbl_clockdetails.clk_Date <= @toDat
	
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo=''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	If Not (@empId = '''')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''
	Execute(@sqlCommonSwipeCardNo)	
	Declare @sqlTempProcessedData2 varchar(8000)	
	set @sqlTempProcessedData2=	''insert into  #TempProcessedData 
	select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
	from #TempEmployee INNER JOIN TA_Tbl_ProcessedData ON #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id and 
	Date between CONVERT(DATETIME,''''''+cast(@fromDat as nvarchar(50))+'''''', 102) and CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102)''
	if(@shift<>0)  
		begin  
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + '' And TA_Tbl_ProcessedData.shift_id= ''+  cast (@shift as nvarchar(50))  
		end
	Execute(@sqlTempProcessedData2)
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''select #TempClockDetails.clk_id,dbo.TA_Tbl_Employee.Employee_Code_Id as clk_EmpId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''''''') as empName ,right(#TempClockDetails.clk_InTime,8) as clk_InTime,''
	set @sqlQuery = @sqlQuery + ''case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_InDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_InDate, ''+CONVERT(varchar,@dateFormat)+'') end as inDate,
										case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_OutDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_OutDate, ''+CONVERT(varchar,@dateFormat)+'') end  as outDate , right(#TempClockDetails.clk_OutTime,8) as clk_OutTime,case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, #TempClockDetails.clk_Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, #TempClockDetails.clk_Date, ''+CONVERT(varchar,@dateFormat)+'') end  as ClockDate,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],TA_Tbl_Title.Titlename as Designation,ta_tbl_Employee.Gender,#TempClockDetails.clk_Date as format  from #TempClockDetails''
	set @sqlQuery = @sqlQuery + '' inner join ta_tbl_Employee on #TempClockDetails.clk_EmpId = ta_tbl_employee.SwipeCardNo''
    set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=#EmpDesignation.DesignationId''
	SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData on #TempProcessedData.EmpAutoId = TA_Tbl_Employee.Employee_Id and #TempProcessedData.Date = #TempClockDetails.CLK_Date''  
	set @sqlQuery = @sqlQuery + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ((ta_tbl_employee.employee_status=1)
	or (ta_tbl_employee.employee_status=0 and convert( nvarchar(11),ta_tbl_employee.InActiveDate,102)>=CONVERT(nvarchar(11),#TempProcessedData.Date,102))
	))''
	if(@Gender<>''Both'')
		begin
		   set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end	
	set @sqlQuery = @sqlQuery + ''  order by  lower(#TempClockDetails.clk_EmpId),#TempClockDetails.clk_Date,#TempClockDetails.clk_InDate ,#TempClockDetails.clk_InTime, #TempClockDetails.clk_OutDate, #TempClockDetails.clk_outTime,ta_tbl_Employee.Employee_FirstName ''
	if(@ExportType=1)
		begin	
			exec(@sqlQuery)	
		end
	else
		begin
		Create table #TempEarlyEntry(clk_id int, clk_EmpId nVarchar(30), empName nvarchar(100),clk_InTime nvarchar(30),indate nvarchar(20),outDate nvarchar(20),clk_OutTime nvarchar(30),ClockDate nvarchar(20),[Level Name] nvarchar(100),Designation nvarchar(100),Gender nvarchar(10),format datetime)
		insert into #TempEarlyEntry exec (@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempEarlyEntry
		insert into #TempDate 
		select distinct CAST(format as datetime),ClockDate from #TempEarlyEntry order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + ''@''
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempEarlyEntry where [Level Name]=@Levelstr and ClockDate=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + ''#''
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
		end
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamicNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Drop procedure Proc_TA_RptDetailAttendanceDynamicNew 
-- Proc_TA_RptDetailAttendanceDynamicNew ''2019/01/01'',''2020/08/29'',''2'','''',''0,1'',''SuperAdmin'',''0'','''',0,0,''Both'',0,0,1
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicNew]   
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId NVARCHAR(max),   
	@EmployeeName NVARCHAR(max),
	@LevelID NVARCHAR(max),  
	@UserGroupName NVARCHAR(250),  
	@GradeLevel NVARCHAR(20)  ,  
	@EmpSwipeCard NVARCHAR(20),  
	@ParentId int,  
	@DesignationID int,  
	@Gender NVARCHAR(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON
	CREATE TABLE #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),
		[Employee Id] NVARCHAR(50),
		[Department]NVARCHAR(250),
		Present numeric(8,1),
		Absent numeric(8,1),
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		LOPCount float,
		[Total Late Days] numeric(8,1),
		[Total Late Hours] numeric(8,1),
		[Total Early Exit Days] numeric(18,1),
		[Total Early Exit Hours] numeric(8,1) default(0),
		[Total OT Days] numeric(8,1),
		[Total OT Hours] numeric(8,1),
		[Norm OT Hrs] numeric(8,1),
		[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),
		Others numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,		
		Total_HoursWorkInMins int,
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,		
		SwipeCardNo NVARCHAR(50),
		Gender NVARCHAR(20),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	DECLARE @isReportingto AS INT
	CREATE TABLE #EmployeeIds(EmpAutoId int)
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
	CREATE TABLE #EmpAttendanceDetails
	(
		EmployeeID  NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateHours numeric(8,1),
		TotalOTDays numeric(8,1),
		TotalOTHours numeric(8,1),
		NormalOTHrs numeric(8,1),
		WeekOffOTHrs numeric(8,1),
		HolidayOTHours numeric(8,1),
		EarlyOutInMins float,
		TotalEarlyOutDays numeric(8,1),
		EmployeeCategory int,
		EmpCategory nvarchar(200),
		EmployeeType int,
		WeeklyOff numeric(8,1),
		Holiday numeric(8,1),
		Leave Numeric(8,1),
		LOP numeric(8,1),
		Total_HoursWorkInMins numeric(8,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours int,
		PermissionDays int,
		LOPCount float,
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	CREATE TABLE #LevelRights(LevelId int)
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id NVARCHAR(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Attendance nvarchar(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		Shift_Id int,
		TotalDays numeric(18,1),
		LateInMins float,
		OtMins float,
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		EarlyOutMins float,
		HoursWorkInMins decimal(18,1),
		Total_Spec_NormOT1 int,
		Total_Spec_NormOT2 int,
		Total_Spec_OffOT1 int,
		Total_Spec_OffOT2 int,
		Total_Spec_HOT1 int,
		Total_Spec_HOT2 int,
		PermissionHours float,
		PermissionDays int,
		LOPCount float,
		EmpSwipeCardNo NVARCHAR(20),
		EmployeeName nvarchar(200) ,
		Gender NVARCHAR(20),
		Department nvarchar(250),
		PayMonth int,
		PayYear int,
		PayMonthName varchar(15)
	)
	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	INSERT INTO #tempLeavetype SELECT Top 10 LeaveType  FROM ta_tbl_leavetype where LeaveType!=''WFH''
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID NVARCHAR(25))
	create table #EmployeeName(EmployeeID NVARCHAR(25))
	if(@empId is not null and @empId <> '''')
		begin			
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		left outer join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
		where emp.Isdeleted=0 
		and(isnull(@empId,0)=0 or emp.Employee_Code_Id in(select * from #EmployeeID))
		and(isnull(@EmployeeName,'''')='''' or emp.Employee_Code_Id in(select * from #EmployeeName))
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= @ToDat and EL.LevelId is not null
		
	insert into #TempProcessedData 
	select	E.Employee_Id,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Attendance,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.Shift_Id,
			PD.TotalDays,
			PD.LateInMins,
			PD.OtMins,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			PD.EarlyOutMins,
			isnull(PD.HoursWorkInMins,0),
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) else isnull(PD.SPEC_NormOTMins1,0) end,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_NormOTMins2,PD.SPEC_NormOTMins2) else isnull(PD.SPEC_NormOTMins2,0) end,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_OffOTMins1,PD.SPEC_OffOTMins1) else isnull(PD.SPEC_OffOTMins1,0) end,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_OffOTMins2,PD.SPEC_OffOTMins2) else isnull(PD.SPEC_OffOTMins2,0) end,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_HolOTMins1,PD.SPEC_HOLOTMins1) else isnull(PD.SPEC_HOLOTMins1,0) end,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_HolOTMins2,PD.SPEC_HOLOTMins2)else isnull(PD.SPEC_HOLOTMins2,0) end,
			Pd.PermissionHrsInMins,
			case when Pd.PermissionHrsInMins > 0 then 1 else 0 end,
			case WHEN (PD.FNAttendanceCode=''LOP'' and PD.ANAttendanceCode=''LOP'') THEN 1 WHEN (PD.FNAttendanceCode=''LOP'' or PD.ANAttendanceCode=''LOP'') THEN 0.5  ELSE 0 END,
			E.SwipeCardNo,
			E.Employee_FirstName,
			E.Gender,
			ld.name,
			Paymonth=MONTH(pd.Date),
			Payyear=year(pd.Date),
			DATENAME(MONTH,pd.Date)
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN TA_Tbl_Employee  e on E.SwipeCardNo=PD.Employee_Code_Id
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
	Inner join #EMPCATEGORY cat on cat.employeeid=e.Employee_Id 
	Inner join #EMPTYPE type on type.employeeid=e.Employee_Id 
	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	inner join ta_tbl_leveldetails ld on ld.id=#EmpLevel.LevelId	
	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
	where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 
	and (@UserGroupName=''Superadmin'' or TA_Tbl_Grade.Grade_Level >=@GradeLevel)
	and (isnull(@Gender,''Both'')=''Both'' or  e.Gender =@Gender)
	and (isnull(@isReportingto,0)=0 or (e.Employee_ID IN (select * from #EmployeeIds)))
	and (PD.date >= CONVERT(DATETIME,@fromDat, 102)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
	INSERT INTO #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender,Department,PayMonth,PayYear,PayMonthName) 
	SELECT DISTINCT Employee_Code_Id,Employee_Code_Id,EmployeeName,Gender,Department,PayMonth,PayYear,PayMonthName FROM #TempProcessedData	
	
	INSERT INTO #EmpAttendanceDetails 
	SELECT TPD.Employee_code_Id,  
			Present= 
			sum
			(
				CASE	WHEN FNAttendanceCode=''Present''	 AND ANAttendanceCode=''Present''		THEN 1.0
						WHEN ((FNAttendanceCode=''Present''  AND ANAttendanceCode!=''Present'')or(FNAttendanceCode!=''Present'' AND ANAttendanceCode=''Present'')) THEN 0.5
						WHEN FNAttendanceCode=''Comp Off'' AND ANAttendanceCode=''Comp Off''	THEN 1.0
						WHEN FNAttendanceCode=''BL'' AND  ANAttendanceCode=''BL''				THEN 1.0						
						ELSE 0.0
				END
			),
			Absent=
			sum
			(
				CASE	WHEN FNAttendanceCode=''Absent''	 AND  ANAttendanceCode=''Absent''	THEN 1.0 
						WHEN ((FNAttendanceCode=''Absent'' AND  ANAttendanceCode!=''Absent'') or (FNAttendanceCode!=''Absent'' AND  ANAttendanceCode=''Absent'')) THEN 0.5
						WHEN ((FNAttendanceCode IS NULL    AND  ANAttendanceCode IS NULL) or (FNAttendanceCode='''' AND ANAttendanceCode=''''))	THEN 1
						ELSE 0.0
				END
			), 
			[Total Late Days]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0 THEN  1 else 0 END),
			[Total Late Hours]	=SUM(CASE WHEN ISNULL(lateinmins,0)!=0	THEN  lateinmins END),
			[Total OT Days]		=SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN 1 else 0 END),  
			[Total Ot Hours]	=
			isnull(SUM(CASE WHEN ISNULL(otmins,0)!=0 THEN  otmins END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT1,0)!=0 THEN  TPD.Total_Spec_NormOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_NormOT2,0)!=0 THEN  TPD.Total_Spec_NormOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT1,0)!=0 THEN  TPD.Total_Spec_OffOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_OffOT2,0)!=0 THEN  TPD.Total_Spec_OffOT2 END),0)+
			isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT1,0)!=0 THEN  TPD.Total_Spec_HOT1 END),0)+isnull(SUM(CASE WHEN ISNULL(TPD.Total_Spec_HOT2,0)!=0 THEN  TPD.Total_Spec_HOT2 END),0),  
			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,''00:00'')=''00:00''	THEN 0 ELSE OtMins END),
			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,''00:00'')=''00:00''	THEN 0 ELSE OtMins END),
			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,''00:00'')=''00:00''	THEN 0 ELSE OtMins END), 
			[Total EarlyOut Hours]=SUM(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),  
			[Total EarlyOut Days]=COUNT(CASE WHEN ISNULL(EarlyOutmins,0)!=0		THEN  EarlyOutmins END),
			0,
			0,
			0,
			''WeeklyOff''	=sum(CASE WHEN FNAttendanceCode=''Weekly Off'' and ANAttendanceCode=''Weekly Off'' THEN 1 ELSE 0 END),
			''Holiday''	=sum(CASE	WHEN FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' THEN 1 
								WHEN ((FNAttendanceCode=''Holiday'' and ANAttendanceCode!=''Holiday'') or (FNAttendanceCode!=''Holiday'' and ANAttendanceCode=''Holiday''))THEN 0.5 
								ELSE 0 
							END), 
			''Leave''		=SUM(CASE WHEN FNAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 0.5 else 0 END) + 
						 SUM(CASE WHEN ANAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 0.5 else 0 END), 
			''LOP''		=SUM(CASE	WHEN FNAttendanceCode=''LOP'' and ANAttendanceCode=''LOP'' THEN 1 
									WHEN ((FNAttendanceCode=''LOP'' and ANAttendanceCode!=''LOP'') or (FNAttendanceCode!=''LOP'' and ANAttendanceCode=''LOP'')) THEN 0.5 
									ELSE 0 
							END), 
			''Total_HoursWorkInMins'' =  sum(CASE WHEN isnull(HoursWorkInMins,0)!=0 THEN HoursWorkInMins else 0 END),
			isnull(SUM(TPD.Total_Spec_NormOT1),0),
			isnull(SUM(TPD.Total_Spec_NormOT2),0),
			isnull(SUM(TPD.Total_Spec_OffOT1),0),
			isnull(SUM(TPD.Total_Spec_OffOT2),0),
			isnull(SUM(TPD.Total_Spec_HOT1),0),
			isnull(SUM(TPD.Total_Spec_HOT2),0),
			isnull(SUM(TPD.PermissionHours),0),
			isnull(sum(TPD.PermissionDays),0),
			isnull(sum(TPD.LOPCount),0),
			TPD.PayMonth,
			TPD.PayYear,
			TPD.PayMonthName
			from #TempProcessedData  TPD
			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
			--Inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=TPD.Employee_Code_Id			
			group by TPD.Employee_Code_ID,TPD.PayMonth,TPD.PayYear,TPD.PayMonthName
	
	update #TempDetailedAttendance set Present = TEAD.Present,
	Absent = TEAD.Absent,  
	[Total Late Days]	= TEAD.TotalLateDays,
	[Total Late Hours]	= TEAD.TotalLateHours,  
	[Total OT Days]		= TEAD.TotalOTDays,
	[Total OT Hours]	= TEAD.TotalOTHours,  
	[Norm OT Hrs]		= TEAD.NormalOTHrs,
	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
	[Total Early Exit Hours]=TEAD.EarlyOutInMins,
	[Total Early Exit Days]= TEAD.TotalEarlyOutDays,
	EmployeeCategory	=TEAD.EmployeeCategory,
	EmpCategory			=TEAD.EmpCategory,
	EmployeeType		=TEAD.EmployeeType,
	Total_HoursWorkInMins=TEAD.Total_HoursWorkInMins,
	Total_Spec_NormOT1	=isnull(TEAD.Total_Spec_NormOT1,0),
	Total_Spec_NormOT2	=isnull(TEAD.Total_Spec_NormOT2,0),
	Total_Spec_OffOT1	=isnull(TEAD.Total_Spec_OffOT1,0),
	Total_Spec_OffOT2	=isnull(TEAD.Total_Spec_OffOT2,0),
	Total_Spec_HOT1		=isnull(TEAD.Total_Spec_HOT1,0),
	Total_Spec_HOT2		=isnull(TEAD.Total_Spec_HOT2,0),
	PermissionHours=TEAD.PermissionHours,
	PermissionDays=TEAD.PermissionDays,
	LOPCount = TEAD.LOPCount,
	WeeklyOff=TEAD.WeeklyOff,
	Holiday=TEAD.Holiday,
	PayMonthName=#TempDetailedAttendance.PayMonthName
	from #EmpAttendanceDetails TEAD 
	inner join #TempDetailedAttendance on (TEAD.EmployeeID=#TempDetailedAttendance.SwipeCardNo and TEAD.PayMonth=#TempDetailedAttendance.PayMonth and TEAD.PayYear=#TempDetailedAttendance.PayYear)
	
	
	---Sum of PermissionHours, PermissionDays,LOPCount ---
    update  a set PermissionHours = (b.PermissionHours),PermissionDays = (b.PermissionDays)
	from #TempDetailedAttendance a 
	inner join
	( 
		select EmployeeID,sum(PermissionHours) PermissionHours,sum(PermissionDays)PermissionDays,PayMonth,PayYear 
		from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	update  a set LOPCount = (b.LOPCount)
	from #TempDetailedAttendance a 
	inner join 
	(
		select EmployeeID,sum(LOPCount) LOPCount,PayMonth,PayYear from #EmpAttendanceDetails group by EmployeeID,PayMonth,PayYear
	) b on (b.EmployeeID = a.SwipeCardNo and b.PayMonth=a.PayMonth and b.PayYear=a.PayYear)
	
	--Inserts the Others details in the temporary table  
	declare @SqlOthers NVARCHAR(4000)  
	create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
	Insert into #Others 
	select Employee_Code_Id ,	
	sum
	(
		CASE	WHEN (FNAttendanceCode=''RH'' or FNAttendanceCode=''LOP'' or FNAttendanceCode=''ESI'') THEN 0.5
				ELSE 0 
		END
	)+ 
	sum
	( 
		CASE WHEN (ANAttendanceCode=''RH'' or ANAttendanceCode=''LOP'' or ANAttendanceCode=''ESI'') THEN 0.5
			 ELSE 0 
		END
	)
	from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance)
	group by Employee_Code_ID
	
	Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
	INSERT INTO #tempLeaveTypeforOthers 
	SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
	LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
	WHERE TLT.Leavetype is null
	declare @LTOthersCount int  
	declare @totLeaveType int
	set @LTOthersCount=1  
	select @totLeaveType=count(*) from #tempLeaveTypeforOthers
	while(@LTOthersCount<=@totLeaveType)  
		BEGIN  
			declare @LeaveTypeForOthers NVARCHAR(10)  
			select @LeaveTypeForOthers =LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount
			declare @SqlUpdateOthers NVARCHAR(3000)
			set @SqlUpdateOthers=''''
			set @SqlUpdateOthers = @SqlUpdateOthers + '' Update #Others set Others = Others + A.TotalDays from ''   
			set @SqlUpdateOthers =@SqlUpdateOthers  + '' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN ''''''+ @LeaveTypeForOthers + '''''' THEN CASE PD.TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else PD.TotalDays END else 0 END)''  
			set @SqlUpdateOthers = @SqlUpdateOthers + '' + sum( CASE PD.ANAttendanceCode WHEN ''''''+ @LeaveTypeForOthers + '''''' THEN CASE PD.TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else PD.TotalDays END else 0 END)) as TotalDays''
			set @SqlUpdateOthers = @SqlUpdateOthers + '' from #TempProcessedData PD ''  
			set @SqlUpdateOthers = @SqlUpdateOthers + '' group by PD.Employee_Code_Id) A''  
			set @SqlUpdateOthers = @SqlUpdateOthers + '' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id''  
			set @LTOthersCount=@LTOthersCount+1  
			exec(@SqlUpdateOthers)  
		END
	--Updates the Others column in the temporary table  
	update #TempDetailedAttendance set Others=#Others.Others from #Others 
	inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo
	
	--Adding the Leave type column in the #TempDetailedAttendance table.  
	declare @LeaveTypeCount int  
	set @LeaveTypeCount=1  
	declare @Column NVARCHAR(max)
	set @Column=''''
	declare @Column_Sum NVARCHAR(max)
	set @Column_Sum=''''
	while(@LeaveTypeCount<=10)  
		BEGIN  
			declare @LeaveType nvarchar(50)  
			set @LeaveType=''''
			select @LeaveType=Leavetype from #tempLeavetype where slno=@LeaveTypeCount
			if @LeaveType is not null and @LeaveType!=''''
			BEGIN
				DECLARE @AlterQuery NVARCHAR(100)  
				set @AlterQuery=''Alter table #TempDetailedAttendance add ['' + @LeaveType + ''] numeric(18,1)''  
				if(@Column='''')
				begin
					set @Column=quotename(@LeaveType)
					set @Column_Sum=quotename(@LeaveType)
				end
				else
				begin
					set @Column=@Column+'',''+quotename(@LeaveType)
					set @Column_Sum=@Column_Sum+''+''+quotename(@LeaveType)
				end
				exec(@AlterQuery)  
				set @AlterQuery=''''
				declare @UpdateQuery NVARCHAR(4000)  
				set @UpdateQuery=''''
				set @UpdateQuery = @UpdateQuery + ''update #TempDetailedAttendance  set [''+ @LeaveType +'']''  
				set @UpdateQuery = @UpdateQuery + ''=A.TotalDays from''  
				set @UpdateQuery = @UpdateQuery +'' (select Employee_Code_ID,TDA.PayMonth,TDA.PayYear,(sum(CASE WHEN PD.FNAttendanceCode='''''' + @LeaveType + '''''' THEN 0.5 else 0 END) ''  
				set @UpdateQuery = @UpdateQuery + '' + sum(CASE WHEN PD.ANAttendanceCode='''''' + @LeaveType + '''''' THEN 0.5 else 0 END)) as TotalDays ''  
				set @UpdateQuery = @UpdateQuery + '' from #TempProcessedData PD''  
				set @UpdateQuery = @UpdateQuery + '' inner join #TempDetailedAttendance TDA on (TDA.SwipeCardNo=PD.Employee_code_ID and TDA.PayMonth=PD.PayMonth and TDA.PayYear=PD.PayYear)''
				set @UpdateQuery = @UpdateQuery + '' group by PD.Employee_Code_ID,TDA.PayMonth,TDA.PayYear) A''  
				set @UpdateQuery = @UpdateQuery + '' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID AND TempAttendance.PayMonth=A.PayMonth AND TempAttendance.PayYear=A.PayYear''  
				exec(@UpdateQuery)  
				--PRINT(@UpdateQuery)  
				set @UpdateQuery=''''
			end
			set @LeaveTypeCount=@LeaveTypeCount+1  
	END  
	
		
	--SELECT * FROM #TempDetailedAttendance 
	declare @SqlPresent NVARCHAR(max)
	set @SqlPresent=''''
	set @SqlPresent=@SqlPresent+'' select 	
		[Employee Id],
		[Employee Name],
		SwipeCardNo,				
		Gender,	
		Present,
		Absent,
		WeeklyOff,
		Holiday,				
		[Total Late Days],		
		[Total Early Exit Days],		
		[Total OT Days],		
		[Norm OT Hrs]=dbo.ConvertMinsToHours([Norm OT Hrs]),
		[WeekOff OT Hrs]=dbo.ConvertMinsToHours([WeekOff OT Hrs]),
		[Holiday OT Hrs]=dbo.ConvertMinsToHours([Holiday OT Hrs]),
		Others,
		Total_HoursWorkInMins=dbo.ConvertMinsToHours(Total_HoursWorkInMins),		
		[WD Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
		[WD Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_NormOT2),
		[WO Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_OffOT1),
		[WO Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_OffOT2),
		[H Spec.OT1]=dbo.ConvertMinsToHours(Total_Spec_HOT1),
		[H Spec.OT2]=dbo.ConvertMinsToHours(Total_Spec_HOT2),
		PermissionHours=dbo.ConvertMinsToHours(PermissionHours) 
		,PermissionDays 
		,LOPCount
		,[Total Late Hours]=dbo.ConvertMinsToHours([Total Late Hours]),
		[Total Early Exit Hours]=dbo.ConvertMinsToHours([Total Early Exit Hours]),
		[Total OT Hours]=dbo.ConvertMinsToHours([Total OT Hours]),
		PayDays=Present+WeeklyOff+Holiday+''+(@Column_Sum)+''
		,TotalDays=DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,convert(varchar(20),payyear)+right(''''00''''+convert(varchar(20),PayMonth),2)+right(''''00''''+convert(varchar(20),1),2)),0))),
		[Month]=PaymonthName,
		''+(@Column)+''
		
		--,convert(varchar(20),payyear)+right(''''00''''+convert(varchar(20),PayMonth),2)+right(''''00''''+convert(varchar(20),1),2)
	 from #TempDetailedAttendance where 1=1 order by PayMonth,paymonthName,[Employee Id] ''	
	--print (@SqlPresent) 
	exec (@SqlPresent)
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpAttendanceDetails  
	drop table #Others  
	drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDetailAttendanceDynamicExport]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDetailAttendanceDynamicExport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author        : Sashma  
-- Create date   : 06-July-2010  
-- Modified date : 12-May-2011  
-- Description   : <Description,,>  
--Modified By    : Thilakraj C  
-- Modified Date : 19-Jul-2013  
-- Description   : Due to Neuland requirement Check the Employee Inactivate Date.  
--Modified By    : Gopinath.k
-- Modified Date : 20-Dec-2013 & 11-Jan-2014
-- Description   :SQL Query Optimization & Emp name filtering
-- =============================================  
-- [Proc_TA_RptDetailAttendanceDynamicExport] ''01/jul/2016'',''31/jul/2016'','''','''',''0'',''SuperAdmin'',''0'','''',0,0,''Both'',0
CREATE PROCEDURE [dbo].[Proc_TA_RptDetailAttendanceDynamicExport] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	 ,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,  
    @DesignationID int,  
    @Gender varchar(10),   
	@ParentID bigint
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
	[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
	[EmployeeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	-------Start
	declare @query as varchar(8000)
	set @query=''''
	set @query = ''select isnull(Employee_FirstName,'''''''') + SPACE(1) + isnull(Employee_MiddleName,'''''''')+ SPACE(1) + isnull(Employee_LastName,'''''''')  + ''''$'''' + Ta_Tbl_levelDetails.name AS [Employee Name],ta_tbl_employee.employee_code_id as [Employee Id],''
	set @query = @query + '' ''''Present'''' = sum( 
	CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END 
	When ''''|'''' Then TotalDays else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END)+
sum( CASE FNAttendanceCode WHEN ''''CL'''' THEN case when ANAttendanceCode=''''Weekly Off'''' then
			Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END END
			WHEN ''''SL'''' THEN case when ANAttendanceCode=''''Weekly Off'''' then
			Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END END
else 0 END) + 
sum( CASE ANAttendanceCode WHEN ''''CL'''' THEN case when FNAttendanceCode=''''Weekly Off'''' then
Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END end
WHEN ''''SL'''' THEN case when FNAttendanceCode=''''Weekly Off'''' then
Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END end
else 0 END)
	,''
	set @query = @query + '' ''''Absent'''' = sum( CASE FNAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	--angler Specific
	--set @query = @query + '' ''''Weekly Off'''' = sum( CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	set @query = @query + '' ''''Weekly Off'''' = sum( case when upper(DATENAME(dw,Date)) = ''''SUNDAY'''' then CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END END) + sum(case when upper(DATENAME(dw,Date)) = ''''SUNDAY'''' then CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END END),''
	set @query = @query + '' ''''Holiday'''' = sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	set @query = @query + '' ''''CompOff'''' = sum( CASE FNAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	--set @query = @query + '' ''''LOP'''' = 
	--sum
	--(
	--	CASE	When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN	1
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''LOP'''' THEN	1	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Present'''' THEN	0.5	
	--			When FNAttendanceCode=''''Present'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''CL'''' THEN	0.5	
	--			When FNAttendanceCode=''''CL'''' and ANAttendanceCode=''''LOP'''' THEN	0.5				
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''CompOff'''' THEN	0.5	
	--			When FNAttendanceCode=''''CompOff'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''SL'''' THEN	0.5	
	--			When FNAttendanceCode=''''SL'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			When FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Holiday'''' THEN	0.5	
	--			When FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''LOP'''' THEN	0.5	
	--			else 0 
	--	END
	--)	 ,''
     	set @query = @query + '' ''''LOP'''' = sum( CASE FNAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''
	-------
	set @query = @query + '' ''''Total Late Days'''' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , ''
	set @query = @query + '' ''''Total Late Hours'''' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), ''
	--angler Specific
	set @query = @query + '' ''''Total Early Out Days'''' =  count(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN 0 THEN  EarlyOutMins END) - count(CASE EarlyOutMins WHEN null THEN EarlyOutMins END)   , ''
	set @query = @query + '' ''''Total Early Out Hours'''' =  sum(CASE EarlyOutMins WHEN EarlyOutMins THEN  EarlyOutMins END), ''
	set @query = @query + '' ''''Total OT Days'''' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , ''
	set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE otmins WHEN otmins THEN  otmins END), ''
	set @query = @query + '' ''''Norm OT Hrs''''=sum(CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''WeekOff OT Hrs''''=sum(CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''Holiday OT Hrs''''=sum(CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''
	--For approved only
	--set @query = @query + '' ''''Total OT Days'''' =  count(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END) , ''
	--set @query = @query + '' ''''Total Ot Hours'''' =  sum(CASE OvertimeStatus WHEN ''''Approved'''' THEN  otmins END), ''
	--set @query = @query + '' replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as Level,''
	--set @query = @query + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,''
	DECLARE @sql varchar(8000)
	DECLARE @sumfunc varchar(200)
	set @sumfunc = ''sum(Totaldays)''
	DECLARE @sumfunc1 varchar(100)
	declare @pivot varchar(100)
	declare @pivot1 varchar(100)
	--set @pivot =''LeaveCode''
	set @pivot =''FNAttendanceCode''
	set @pivot1 =''ANAttendanceCode''
	Declare @TotalLeaveCount Decimal(10,5)
	Set @TotalLeaveCount=0;
	---- get the leave type details and form query
	EXEC (''SELECT LeaveType AS [pivot] INTO ##pivot FROM ta_tbl_leavetype WHERE 1=2'')
	CREATE NONCLUSTERED INDEX [pivot] ON [dbo].[##pivot] 
	(
	[pivot] ASC
	) ON [PRIMARY]
	exec (''INSERT INTO ##pivot select top 5 LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
	SELECT @sql='''',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, '' END)'' )
	declare @delim  varchar(1)
	SELECT  @delim=CASE Sign( CharIndex(''char'', data_type)+CharIndex(''date'', data_type) ) 
	WHEN 0 THEN '''' ELSE '''''''' END 
	FROM tempdb.information_schema.columns 
	WHERE table_name=''##pivot'' AND column_name=''pivot''
	select @sql=''''
	SELECT @sql=@sql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
	+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
	--		+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN '' ) + '', '' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
	FROM ##pivot order by [pivot]
	if len(@sql)>0
	SELECT @sql=left(@sql, len(@sql)-1)
	-- end of leave type
	---- other leave type
	declare @SelectedLeaveType as varchar(500)
	set @SelectedLeaveType =''''
	SELECT @SelectedLeaveType=@SelectedLeaveType + '''''''' + convert(varchar(100), [pivot]) + '''''' , '' 
	FROM ##pivot
	delete  from ##pivot
	if len(@SelectedLeaveType)>0
		begin
			SELECT @SelectedLeaveType=left(@SelectedLeaveType, len(@SelectedLeaveType)-1)
			exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0 and leavetype not in ('' + @SelectedLeaveType + '' )  order by leavetype'')
		end
	else
		begin
			exec (''INSERT INTO ##pivot select LeaveType as '' + @pivot + '' from ta_tbl_leavetype where isdeleted=0  order by leavetype'')
		end
	--delete  from ##pivot
	declare @othSql as varchar(5000)
	select @othSql=''''
	--SELECT @othSql=@othSql + '''''''' + convert(varchar(100), [pivot]) + '''''' = '' 
	/*		
	SELECT @othSql=@othSql + '' '' 
	+ stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot + '' WHEN '' 
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' THEN (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5''''  when null then 0 Else ''   )+  '' else 0 End )+ '' +   stuff(@sumfunc,charindex( ''('', @sumfunc )+1, 0, '' CASE '' + @pivot1 + '' WHEN  ''
	+ @delim + convert(varchar(100), [pivot]) + @delim + '' Then (Case TotalDays When ''''0.5'''' Then ''''0.5''''  When ''''1.0'''' Then ''''0.5'''' when null then 0 Else ''   ) + '' else 0 End )'' + '', '' 
	FROM ##pivot order by [pivot]
	*/
	if (len(@othSql)>0) 
		begin
			SELECT @othSql=left(@othSql, len(@othSql)-1) + ''+''
		end
	set @query = @query + '' ''''Others'''' =  '' + @othSql + '' sum( CASE FNAttendanceCode WHEN ''''RH'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)''
	set @query = @query + '' + sum( CASE ANAttendanceCode WHEN ''''RH'''' THEN Case TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END),''
	set @query = @query + '' ''''CL'''' =   sum( CASE FNAttendanceCode WHEN ''''CL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''CL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END), ''
	set @query = @query + '' ''''SL'''' =   sum( CASE FNAttendanceCode WHEN ''''SL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) +sum( CASE ANAttendanceCode WHEN ''''SL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END)''
--For satoff
	--set @query=  @query + '' ,SUM(case when upper(DATENAME(dw,Date)) = ''''Saturday'''' then 
	--                                                       case when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode =''''Absent'''' and 
	--                                              ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')
	--                                              then 1 else 0 end
	--                                                else 0 end ) as ''''Saturday Off''''''
	set @query=  @query + '' ,     SUM(case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
	                                                       CASE  when FNAttendanceCode = ''''Absent'''' or ANAttendanceCode =''''Absent'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN  1
	                                                         when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode=''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN 1
	                                                         when FNAttendanceCode= ''''Weekly Off'''' and ANAttendanceCode =''''Absent''''  and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')THEN 1
	                                                         when FNAttendanceCode = ''''Weekly Off'''' and ANAttendanceCode =''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') then 1 
	  													   end 
														   else 
														      0		
														   end 
							 )   as ''''Saturday Off''''''                                                
	              --             set @query=  @query + '' , SUM(case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
															--Case when (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Weekly Off'''') then 1 
															--	 else case when ( (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Present'''') or (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Weekly Off'''') ) then 0.5  
               --                                                            else case when ( (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Present'''')  ) then 0  
															--						 else case when (ANAttendanceCode=''''Weekly Off'''' or FNAttendanceCode=''''Weekly Off'''') then 0.5
															--end 
			            --                                    end  
															--end
															--end 
								       --                    	end
               --                                                           ) as [Intimation] ''                         
	 set @query=  @query + '' , SUM(
				case when upper(DATENAME(dw,Date)) = ''''SATURDAY'''' THEN 
							Case	when (ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Weekly Off'''') then 1 
									else	case	when ((ANAttendanceCode=''''Weekly Off'''' and FNAttendanceCode=''''Present'''') 
													  or (ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Weekly Off'''') ) then 0.5  
													else 0
													--case	when ((ANAttendanceCode=''''Present'''' and FNAttendanceCode=''''Present'''')  ) then 0  
													--			else	case	when (ANAttendanceCode=''''Weekly Off'''' or FNAttendanceCode=''''Weekly Off'''') then 0.5
													--					end 
													--	 end  
											end
									end 
					end
                                                                          ) as [Intimation] ''                                  
	--end of other leave type
	--if len(@sql)=0
	--SELECT @query=left(@query, len(@query)-1)
	--set @query  = @query + @sql
	declare @query1 as varchar(8000) 
	set @query1=''''
	set @query1 = @query1 + '' from ta_tbl_employee inner join ta_tbl_processedData on ta_tbl_processedData.Employee_code_id = ta_tbl_employee.SwipeCardNo''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeLevel on Ta_tbl_employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @query1 = @query1 + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id ''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeCategory EC on ta_tbl_employee.Employee_Id=EC.EmployeeId''
	set @query1 = @query1 + '' inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId''
	set @query1 = @query1 + '' inner join TA_Tbl_EmployeeDesignation ON Ta_tbl_employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId''
	set @query1 = @query1 + '' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' inner join TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID ''
		end
	set @query1 = @query1 + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @query1 = @query1 + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @query1 = @query1 + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId ''
	set @query1 = @query1 + '' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId ''
	set @query1 = @query1 + '' where TA_Tbl_Employee.Report_Exclude=0 and TA_Tbl_Employee.Isdeleted=0  and TA_Tbl_Employee.Employee_status=1''
	set @query1 = @query1 + '' And     (ta_tbl_processedData.date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''
	set @query1 = @query1 + '' AND (ta_tbl_processedData.date <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @query1 = @query1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel 
			--+  '' AND (ta_tbl_employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or ta_tbl_employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''') ''
		end
	if not(@EmployeeName='''')
		begin
		--	set @query1 = @query1 + '' and ta_tbl_employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		Declare @Tempname nvarchar(200)
    set @Tempname= ''(ta_tbl_employee.Employee_FirstName + '''' '''' + isnull(ta_tbl_employee.Employee_LastName,'''''''')''
	set @query1 = @query1 + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 	
		end
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @query1 = @query1 + ''And ta_tbl_employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End
	if not (@empId='''')
		begin
			set @query1 = @query1 + '' and ta_tbl_employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end
	if(@DesignationID<>0)  
		 begin  
			set @query1 = @query1 + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))  
		end  
	if(@Gender<>''Both'')  
		begin  
			 set @query1 = @query1 + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		 end  
	--if(@EmpAutoId = 0)
	--	BEGIN
	--		if not(@LevelID='''' or @LevelID=''0'')
	--			begin
	--				set @query1 = @query1 + '' and #EmpLevel.LevelId IN ( '' + @LevelId + '') '' 
	--			end	
	--	END
	if(@EmpAutoId > 0)
		BEGIN
			set @query1 = @query1 + '' and (ta_tbl_employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	set @query1 = @query1 + '' group by  ta_tbl_employee.employee_code_id,employee_firstname,employee_middlename,employee_lastname, ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  ta_tbl_employee.employee_code_id,ta_tbl_employee.employee_firstname''
	create table #TempFinal ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] int,[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,Others decimal(18,1),CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,Intimation DECIMAL(18,2))
	DROP TABLE ##pivot
	--exec  (@query + '' '' + @query1)
	insert into #TempFinal 
	exec  (@query + '' '' + @query1)
	--select TF.*,C.CategoryName as [Employee Category]from #TempFinal TF
	--Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	--inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	--inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId order by TF.[Employee Id] 
	--select * from #TempFinal 
    create table #TempFinal2 ([Employee Name] nvarchar(500),[Employee Id] nvarchar(50),Present decimal(18,1),Absent decimal(18,1),[Weekly Off] decimal(18,1),
	Holiday decimal(18,1),CompOff decimal(18,1),Lop decimal(18,1),[Total Late Days] int,[Total Late Hours] varchar(50),[Total Early Out Days] int,[Total Early Out Hours] int,
	[Total OT Days] int,[Total Ot Hours] int,[Norm Ot Hrs] int,[WeekOff OT Hrs] int,[Holiday OT Hrs] int,CL decimal(18,1),SL decimal(18,1),[Saturday Off] int,[Employee Category] nvarchar(500),Others decimal(18,1),CategoryId int,Intimation DECIMAL(18,2))
	Insert into #TempFinal2 
	select [Employee Name] ,[Employee Id] ,Present ,Absent ,[Weekly Off] ,
	Holiday ,CompOff ,Lop ,[Total Late Days] ,
	case when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
				+ ''0'' +convert(varchar(20),[Total Late Hours]/60) + '':0'' + CONVERT(varchar(20),[Total Late Hours]%60)  
	     when len(convert(varchar(20),[Total Late Hours]/60))=1 and len(CONVERT(varchar(20),[Total Late Hours]%60))=2 then 
	     + ''0'' +convert(varchar(20),[Total Late Hours]/60) + '':'' + CONVERT(varchar(20),[Total Late Hours]%60)
	     when len(convert(varchar(20),[Total Late Hours]/60))=2 and len(CONVERT(varchar(20),[Total Late Hours]%60))=1 then 
	     convert(varchar(20),[Total Late Hours]/60) + '':0'' + CONVERT(varchar(20),[Total Late Hours]%60)
	else convert(varchar(20),[Total Late Hours]/60) + '':'' +CONVERT(varchar(20),[Total Late Hours]%60)  
	end 
	,[Total Early Out Days] ,[Total Early Out Hours] ,
	[Total OT Days] ,[Total Ot Hours] ,[Norm Ot Hrs] ,[WeekOff OT Hrs] ,[Holiday OT Hrs] ,CL,SL,[Saturday Off]
	,C.CategoryName as [Employee Category],Others,C.CategoryId ,Intimation from #TempFinal TF
	Inner join TA_Tbl_Employee E On TF.[Employee Id]=E.Employee_Code_Id 
	inner join TA_Tbl_EmployeeCategory EC on E.Employee_Id=EC.EmployeeId
	inner join TA_Tbl_Category C on EC.CategoryId=C.CategoryId
	Inner join #EmpCategory on #EmpCategory.EffectiveDate=EC.EffectiveDate and #EmpCategory.employeeid=EC.EmployeeId 
	order by [Employee Id]	
		declare @BelowCategoryId as int
	set @BelowCategoryId=(select top 1 CategoryId from TA_Tbl_Category  order by MonToSat_WorkHrs desc,Sat_WorkHrs desc)
	update #TempFinal2 set [Saturday Off]=0 where CategoryId=@BelowCategoryId 
	update #TempFinal2 set [Intimation]=0 where CategoryId=@BelowCategoryId 
	--update #TempFinal2 set Present=Present+[Saturday Off] where [Employee Id]
	--Update #TempFinal2 Set Present =1 Where upper(DATENAME(dw,Date)) = ''''Saturday'''' THEN 
	--                                                       CASE  when FNAttendanceCode = ''''Absent'''' and ANAttendanceCode =''''Absent'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN  1
	--                                                         when FNAttendanceCode = ''''Absent'''' and FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') THEN 1
	--                                                         when FNAttendanceCode= ''''Weekly Off'''' and FNAttendanceCode =''''Absent''''  and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''')THEN 1
	--                                                         when FNAttendanceCode = ''''Weekly Off'''' and FNAttendanceCode =''''Weekly Off'''' and ANAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') and  FNAttendanceCode not in(''''CL'''',''''Holiday'''',''''CompOff'''',''''LOP'''',''''SL'''') then 1 
	select [Employee Id],[Employee Name],Present+isnull (Intimation,0)as Present,Absent ,[Weekly Off] ,[Saturday Off],
	Holiday ,CompOff ,Lop ,CL,SL,isnull([Total Late Hours],''00:00'')[Total Late Hours]  ,[Total Late Days] from #TempFinal2
	drop table #tempFinal
	drop table #TempFinal2
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyAttendance]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
PROC_TA_RPTDAILYATTENDANCE @MINWORKHOURS=N'''',@FROMDAT=''2019-04-01 00:00:00'',
@EMPLOYEENAME=N'''',@EMPLOYEEID=N''787'',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N''SUPERADMIN'',
@GRADELEVEL=N''0'',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N''BOTH'',@SHIFT=0,@EMPAUTOID=0,@LOCATIONID=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyAttendance]
(   
--Passing filter values from Application

	@MINWORKHOURS AS NVARCHAR(10)=null,-- From Applic		
	@FROMDAT DATETIME=null,-- From Applic
	@EMPLOYEENAME NVARCHAR(MAX)=null, -- From Applic	
	@EMPLOYEEID NVARCHAR(MAX)=null,-- From Applic
	@EMPLOYEECATEGORY INT=null,-- From Applic
	@EMPLOYEETYPE INT=0,-- From Applic		
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,-- From Applic
	@GENDER NVARCHAR(10)=null,-- From Applic	
	@SHIFT INT=0,-- From Applic	
	@EMPAUTOID BIGINT=0,
	@LOCATIONID INT
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	
	--Declare local variables to increase execution efficiency
	
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT	
	DECLARE @local_EMPAUTOID BIGINT
    DECLARE @local_LOCATIONID INT
	
	--Assign values to local varibles
	
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))  
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))     
    SET @local_LOCATIONID		= LTRIM(RTRIM(@LOCATIONID))

	
	
	--Temp query construction and execution	
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)	
	
	
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10)
	)
	
	DECLARE @ISREPORTINGTO AS INT	
	DECLARE @ISINDIVIDUAL AS INT
	
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
	
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF not(@local_GENDER=''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@local_GENDER AS NVARCHAR(8)) + '''''' ''  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@local_TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@local_EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	IF NOT (@local_EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			vp.INTIME,
			vp.OUTTIME,
			vp.SHIFT_ID,
			vp.HRSWORK,
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			vp.ActOTMins,
			vp.ActNormOT,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	
	--UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	--INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE=''CL'' 	
	--------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	--(
	--	SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
	--	(
	--		SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
	--		FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
	--	)
	--	AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
	--	WHERE
	--	(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
	--	AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	--)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	----------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	--(
	--	SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
	--	(
	--		SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
	--		FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
	--	)
	--	AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
	--	WHERE
	--	(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
	--	AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	--)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	--UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''PM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''AM'' THEN 1 
	--												WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''AM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''PM'' AND PD.OUTTIME>''00:00 AM'' THEN 1
	--												ELSE 0 END 
	--FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	DECLARE @POS AS INT  
	SET @POS = CHARINDEX('':'',@local_MINWORKHOURS)  
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = SUBSTRING(@local_MINWORKHOURS,0,@POS)*60 + SUBSTRING(@local_MINWORKHOURS,@POS+1,2)  
	CREATE TABLE #TEMPDAILYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(5)
		,		
		PHOTO image,
		LocationName varchar(225)
	
	)
	--CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_INNOTATION_OUTNOTATION] ON [DBO].#TEMPDAILYATTENDANCE(FIRSTSESSION,SECONDSESSION,INNOTATION,OUTNOTATION) ON [PRIMARY]  
	--CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_DATE] ON [DBO].#TEMPDAILYATTENDANCE(FIRSTSESSION,SECONDSESSION,DATE) ON [PRIMARY]  
	IF (@local_MINWORKHOURS<>'''') 

		BEGIN  
			DECLARE @SQLQUERYTEMP AS VARCHAR(MAX)    
			SET @SQLQUERYTEMP=''''   
			SET @SQLQUERYTEMP =  ''SELECT PD.EMPLOYEE_CODE_ID AS SWIPECARDNO,PD.DATE AS DATE,((SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),0,CHARINDEX('''':'''',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),(LEN(PD.HRSWORK)-1),2))) AS TOTALWORKMINS FROM TA_TBL_EMPLOYEE E ''
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPDESIGNATION EDESIG ON E.EMPLOYEE_ID = EDESIG.EMPLOYEEID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' LEFT JOIN TA_TBL_SHIFT SH ON SH.SHIFT_ID = PD.SHIFT_ID ''
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' WHERE  (	(E.EMPLOYEE_STATUS = 1) OR 	
			(E.EMPLOYEE_STATUS = 0 AND  CONVERT(NVARCHAR(11), E.INACTIVEDATE,102) >= CONVERT(NVARCHAR(11),PD.DATE,102)
			)) AND (E.ISDELETED = 0) AND (E.REPORT_EXCLUDE = 0)''
			INSERT INTO #EMPPROCESSEDDATA EXEC(@SQLQUERYTEMP)  
		END

	DECLARE @SQLQUERY AS VARCHAR(MAX)    

	SET @SQLQUERY=''''    	

	SET @SQLQUERY = ''SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''''PRESENT'''' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''FN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END 
			ELSE PD.FNATTENDANCECODE
	END
	AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''''PRESENT'''' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''AN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END  
			ELSE PD.ANATTENDANCECODE
	END
	AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''''''')   +  SPACE(1) + ''''#'''' + ISNULL(E.Mobile_Number,'''''''')   AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&'''') AS BRANCHNAME,REPLACE(T.TITLENAME,''''&AMP;'''',''''&'''') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''''WEEKLY OFF'''' AND ANATTENDANCECODE=''''WEEKLY OFF'''' THEN	''''-'''' 
	WHEN PD.FNATTENDANCECODE=''''HOLIDAY''''OR ANATTENDANCECODE=''''HOLIDAY'''' THEN ''''-''''
	ELSE PD.SUPPOSEDWORKHOURS END ''''SUPPOSEDWORKHOURS'''',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + ISNULL(PD.STATUS,'''''''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),0,CHARINDEX('''':'''',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED''  
	SET @SQLQUERY = @SQLQUERY + '' ,(CASE PD.SHIFT_ID WHEN ''''-1'''' THEN ''''WEEKLY OFF'''' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN ''''-'''' 
						 WHEN PD.SHIFT_ID=-1 THEN ''''-''''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''''00:00''''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.OFFOT IS NOT NULL	THEN
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 ELSE 0
	END OVERTIME,
	
	CASE WHEN ISNULL(NORMOT,''''00:00'''')=''''00:00''''	THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''NORMOTMINS'''',
	CASE WHEN ISNULL(OFFOT,''''00:00'''')=''''00:00''''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''WEEKOFFOTMINS'''',
	CASE WHEN ISNULL(HOLOT,''''00:00'''')=''''00:00''''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''HOLIDAYOTMINS'''',
	CASE WHEN ISNULL(NORMOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(NORMOT AS VARCHAR(50)) 
																		END 
		 END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(OFFOT AS VARCHAR(50)) 
																		END
		 END,
	CASE WHEN ISNULL(HOLOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																			ELSE CAST(HOLOT AS VARCHAR(50)) 
																	END
		 END,
	LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''''-'''' ELSE OVERTIMESTATUS END,NIGHTORMORN,''''00:00'''',''''00:00'''',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CATEGORYNAME,WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),FNATTENDANCECODE,ANATTENDANCECODE,
	Case when FNATTENDANCECODE=ANATTENDANCECODE then 
					case	when ANATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(ANATTENDANCECODE,1,1)
							else ANATTENDANCECODE
					end
		 else 
				case	when FNATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(FNATTENDANCECODE,1,1)
						else FNATTENDANCECODE
				end
				+''''/''''+
				case	when ANATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(ANATTENDANCECODE,1,1)
						else ANATTENDANCECODE
				end
		end''
		 
	SET @SQLQUERY = @SQLQUERY  + '', isnull(E.PHOTO,''''''''),  isnull(LVL.name,'''''''')'' 
	
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN  TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     
	SET @SQLQUERY = @SQLQUERY + '' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID''  
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN  #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID ''

	--two tables for showing location name
    SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN TA_tbl_ShiftAdd_Location LOC ON (convert(nvarchar,LOC.EmployeeId) = E.Employee_Id) and (PD.Date = LOC.ShiftDate) ''
	SET @SQLQUERY = @SQLQUERY + '' LEFT OUTER JOIN TA_TBL_LEVELDETAILS LVL on (LVL.Id = LOC.LocationId) ''
	
	
	IF (@local_MINWORKHOURS<>'''')  
		 
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID''  
		END   
		SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0  and (''+ CAST(@local_LOCATIONID AS NVARCHAR(11)) +''= 0 or CAST(LOC.LocationId AS NVARCHAR(11)) =''+CAST(@local_LOCATIONID AS NVARCHAR(11))+'') and ((E.EMPLOYEE_STATUS=1) 
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, '''''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + '''''', 102) AND PD.DATE <= CONVERT(DATETIME, '''''' + CAST(@local_TODAT AS NVARCHAR(11)) + '''''', 102)))''    
	IF(@local_USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @local_GRADELEVEL + ''''  
		END	
	IF (@local_MINWORKHOURS<>'''')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ''AND #EMPPROCESSEDDATA.TOTALWORKMINS >= '' + CAST(@TOTALMIN AS NVARCHAR(8))    
		END

    
	INSERT INTO #TEMPDAILYATTENDANCE EXEC(@SQLQUERY)	
	
	--select * from #TEMPDAILYATTENDANCE
	--UPDATE #TEMPDAILYATTENDANCE SET 
	--FIRSTSESSION=
	--	CASE	WHEN FIRSTSESSION IN(''PRESENT'',''*PRESENT'',''HOLIDAY'',''*HOLIDAY'',''WEEKLY OFF'',''*WEEKLY OFF'') AND INNOTATION=''M'' THEN  FIRSTSESSION+'' #''	
	--			ELSE #TEMPDAILYATTENDANCE.FIRSTSESSION 
	--	END,
	--SECONDSESSION=
	--	CASE	WHEN SECONDSESSION IN(''PRESENT'',''*PRESENT'',''HOLIDAY'',''*HOLIDAY'',''WEEKLY OFF'',''*WEEKLY OFF'') AND OUTNOTATION=''M'' THEN  SECONDSESSION+'' #''
	--			ELSE #TEMPDAILYATTENDANCE.SECONDSESSION 
	--	END
	--FROM #TEMPDAILYATTENDANCE
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()	

	DECLARE @CaseDecider AS INT

		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPDAILYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		PHOTO,
		LocationName,
		
		CASE		
		WHEN (FIRSTSESSION=''Present'' or SECONDSESSION=''Present'') THEN 1 
		WHEN (FIRSTSESSION=''Absent'' and SECONDSESSION=''Absent'') THEN   2 
		WHEN (FIRSTSESSION=''WEEKLY OFF'' or SECONDSESSION=''WEEKLY OFF'') THEN  3
		WHEN (FIRSTSESSION=''HOLIDAY'' or SECONDSESSION=''HOLIDAY'')  THEN 4
		ELSE 5 
		END as CaseDecider

		FROM #TEMPDAILYATTENDANCE ORDER BY CaseDecider
		

		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	

	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPDAILYATTENDANCE	
	
	  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptCanteenReport]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptCanteenReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
	created By		:	Velumani
	Created Date	:	02-Dec-2019
	Description		:	Display of punch type based report
*/
---- Proc_TA_RptCanteenReport '''','''',''01/Jan/2019'',''30/Nov/2019'','''',0,0,0,''SuperAdmin'',''0'',0,0,''Both'',''all'',0,0
-- Proc_TA_RptCanteenReport '''',''0,1'',''01/Dec/2019'',''30/Dec/2019'','''',0,0,0,''SuperAdmin'',''0'',0,0,''Both'',''Shift In'',0,0
-- select * from ta_tbl_clockdetails where clk_date='''' and clk_Empid in (1,2)
CREATE PROCEDURE [dbo].[Proc_TA_RptCanteenReport]      
(
	@EmployeeID varchar(50), 
	@LevelID varchar(8000),  
	@FromDate varchar(50), 
	@ToDate varchar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@punchTypeValue varchar(50),
	@EmpAutoId bigint,
	@ExportType int
)      
AS      
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID varchar(50)
	DECLARE @local_LevelID varchar(8000)
	DECLARE @local_FromDate varchar(50) 
	DECLARE @local_ToDate varchar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_punchTypeValue=@punchTypeValue
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE TABLE #TempCanteenClockDetails
	(
		[Clk_EmpId] nvarchar(20) ,
		[Clk_PunchType] nvarchar(20) ,
		[Clk_Punchdatetime] datetime,
		[Clk_Date] datetime
	)
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End	
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @CanteenData1 varchar(8000)
	set @CanteenData1 = '' insert into  #TempCanteenClockDetails 
		select  [Clk_EmpId],[clk_Inpunchtype] ,	Clk_InDate + Clk_InTime as Punchdatetime,[Clk_Date]  from ta_tbl_clockdetails
		UNION
		select  [Clk_EmpId] ,[Clk_OutPunchType] , Clk_OutDate+Clk_OutTime as Punchdatetime,[Clk_Date]  from ta_tbl_clockdetails
		where ta_tbl_clockdetails.IsVoid=0 and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,''''''+cast(@local_FromDate as nvarchar(20))+'''''', 102) 
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(20))+'''''', 102) 
		and (Clk_InDate + Clk_InTime is not null or Clk_OutDate+Clk_OutTime is not null) order by Punchdatetime
		''
	Execute(@CanteenData1);	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime
	)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date
	from TA_Tbl_ProcessedData 
	inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	Declare @SelectSQL As varchar(max)
	Set @SelectSQL = '' ''        
	create table #TempFinal(employee_Code_Id varchar(50),Employee_FirstName varchar(250)
	,[Level Name] varchar(250),Clk_Punchdatetime datetime,Clk_PunchType varchar(100),shift_shortname varchar(25),
	clk_date datetime)
	    Set @SelectSQL = @SelectSQL + ''insert into #TempFinal select isnull(ED.employee_Code_Id,'''''''') as employee_Code_Id, 
	    isnull(ED.Employee_FirstName,'''''''')+  SPACE(1) + ISNULL(ED.EMPLOYEE_LASTNAME,'''''''') as Employee_FirstName,
	    isnull(replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&''''),'''''''') AS ''''Level Name'''',
	    isnull(CD.Clk_Punchdatetime,'''''''') as Clk_Punchdatetime,
	    isnull(CD.Clk_PunchType,'''''''') as Clk_PunchType,
	    isnull(SH.shift_shortname,'''''''') + SPACE(1) + ''''('''' + ISNULL(SH.Shift_StartTime,'''''''') + SPACE(1) + ISNULL(SH.Shift_EndTime,'''''''') + '''')'''' as shift_shortname,
	    isnull(convert(varchar,CD.Clk_Date,101),'''''''') as Clk_Date
		FROM TA_Tbl_Employee ED ''  
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempCanteenClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date''   
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID ''  
	Set @SelectSQL = @SelectSQL + ''''       
	Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and CD.Clk_Punchdatetime is not null and  ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) ''
	if(@local_Gender<>''Both'')
		begin
			set @SelectSQL = @SelectSQL + '' and ED.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  PD.Shift_Id = '' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@punchTypeValue<>''all'')
		Begin
			set @SelectSQL = @SelectSQL +  '' And  CD.Clk_PunchType = '''''' +  cast(@punchTypeValue  as nvarchar(50)) +''''''''  
		End
		Set @SelectSQL = @SelectSQL + '' order by CD.Clk_Punchdatetime''  
	Exec (@SelectSQL)
	select employee_Code_Id,Employee_FirstName,[Level Name],Clk_Punchdatetime,
	case when shift_shortname='' ( )'' then '''' else shift_shortname end as shift_shortname, convert(varchar,clk_date,110) as clk_date,Clk_PunchType from #TempFinal
	--select * from #TempFinal
	select isnull(convert(varchar,clk_date,110),'''') as Punchdate
	,isnull(Clk_PunchType,'''') as punchtypename
	,isnull([Level Name],'''') as LevelName
	,case when shift_shortname='' ( )'' then '''' else shift_shortname end  as shift_shortname
	,isnull(count(Clk_PunchType),'''') as DeptwisePunchCount
	from #TempFinal
	group by [Level Name], clk_date,Clk_PunchType,shift_shortname order by Punchdate
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempCanteenClockDetails 
	drop table #TempProcessedData
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptAuditTrail]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptAuditTrail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : 
Proc_TA_RptAuditTrail ''07/07/2008'',''07/08/2015'',''Manual Time Entry'',''''  
Description : Audit Trail Report - get operation(insert,update,delete) details with required information   
Tables Included : TA_Tbl_AuditTable,TA_Tbl_AuditField,TA_Tbl_AuditOperation,TA_Tbl_Employee    
Created By : Christoper S, Senthil Kumar NP    
Created On : 11-Jan-08    
Modified By :
Modified On :*/  
CREATE   PROCEDURE [dbo].[Proc_TA_RptAuditTrail]
(	
	@fromDate as dateTime,
	@toDate as dateTime,
	@TableDescription as nvarchar(100),
	@opr as nvarchar(10)
)	
AS
BEGIN
	set nocount on
	Create table #TempStarting(id int,TableID int,RecordID int,FieldID int)
	Insert into #TempStarting 
	select AO.ID,AO.TableID,AO.RecordID,AO.FieldID from TA_Tbl_AuditOperation AO
	inner join TA_Tbl_AuditTable AT on AO.TableID=AT.TableID
	inner join TA_Tbl_AuditField AF on AO.TableID =AF.TableID and AO.FieldID=AO.FieldID
	where 	
	(AO.OldValue<>isnull(AO.NewValue,'''') or AO.OldValue is null) And AT.Status = 1 AND AF.Status = 1 AND 
	(datediff(dd, cast (@fromDate as nvarchar(11)),AO.OprDate)>=0 and datediff(dd, cast(@toDate as nvarchar(11)),AO.OprDate)<=0 )
	declare @sql as varchar(max)
	set @sql=''''
	set @sql = @sql + ''SELECT TA_Tbl_AuditTable.TableDescription AS TableName, 
						TA_Tbl_AuditField.FieldDescription AS FieldName, 
						TA_Tbl_AuditOperation.Opr AS Operation,''
	set @sql = @sql + '' 
	case	when TA_Tbl_AuditTable.TableDescription=''''Leave Application'''' and TA_Tbl_AuditField.FieldName=''''Employee_Id''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''Permission'''' and TA_Tbl_AuditField.FieldName=''''Employee_Id''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''Terminal Master'''' and TA_Tbl_AuditField.FieldName=''''TerminalDatatype_ID''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select Raw_Data_Format from TA_Tbl_Terminaldatatype where terminaldatatype_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee1_Id''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee2_Id''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee1_ActualShift''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select case when shift_shortName is null then ''''off'''' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee2_ActualShift''''
				and TA_Tbl_AuditOperation.OldValue is not null then (select case when shift_shortName is null then ''''off'''' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.OldValue is null then ''''''''
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.OldValue=0 then ''''Manual Time Entry''''
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.OldValue=1 then ''''Manual Time Entry Import''''				
			else TA_Tbl_AuditOperation.OldValue end,
	case	when TA_Tbl_AuditTable.TableDescription=''''Leave Application'''' and TA_Tbl_AuditField.FieldName=''''Employee_Id''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''''Permission'''' and TA_Tbl_AuditField.FieldName=''''Employee_Id''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=NewValue)
			when TA_Tbl_AuditTable.TableDescription=''''Terminal Master'''' and TA_Tbl_AuditField.FieldName=''''TerminalDatatype_ID''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select Raw_Data_Format from TA_Tbl_Terminaldatatype where terminaldatatype_id=OldValue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee1_Id''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee2_Id''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select employee_code_id from ta_tbl_employee where isdeleted=0 and employee_id=newvalue)	
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee1_ActualShift''''
				and TA_Tbl_AuditOperation.NewValue is not null then 
				(select case when NewValue=-1 then ''''off'''' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''''ShiftExchange'''' and TA_Tbl_AuditField.FieldName=''''Employee2_ActualShift''''
				and TA_Tbl_AuditOperation.NewValue is not null then (select case when NewValue=-1 then ''''off'''' else shift_shortName end from ta_tbl_shift where isdeleted=0 and shift_id=newvalue)
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.NewValue is null then ''''''''
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.NewValue=0 then ''''Manual Time Entry''''
			when TA_Tbl_AuditTable.TableDescription=''''Manual Time Entry'''' and TA_Tbl_AuditField.FieldName=''''IsImported''''
				and TA_Tbl_AuditOperation.NewValue=1 then ''''Manual Time Entry Import''''	
			else TA_Tbl_AuditOperation.NewValue end , 
						TA_Tbl_AuditOperation.EmployeeID,TA_Tbl_AuditOperation.OprDate,''
	set @sql = @sql + '' TA_Tbl_Employee.Employee_Code_Id, isnull(TA_Tbl_Employee.Employee_FirstName,'''''''')+ '' 
	set @sql = @sql + '' '''' '''' +isnull(TA_Tbl_Employee.Employee_LastName,'''''''') as EmployeeName,
		case when  Datatype=''''datetime'''' then convert(datetime,TA_Tbl_AuditOperation.NewValue) 
						end as Newvaluedatetime,Datatype,TA_Tbl_AuditOperation.RecordID,
		case when  Datatype=''''datetime'''' then convert(datetime,TA_Tbl_AuditOperation.OldValue) 
						end as Oldvaluedatetime,TA_Tbl_AuditOperation.ID
		FROM TA_Tbl_AuditTable''	
	set @sql = @sql + '' INNER JOIN TA_Tbl_AuditField ON TA_Tbl_AuditTable.TableID = TA_Tbl_AuditField.TableID''
	set @sql = @sql + '' INNER JOIN TA_Tbl_AuditOperation  ON TA_Tbl_AuditField.FieldID = TA_Tbl_AuditOperation.FieldID''
	set @sql = @sql + '' Left JOIN  #TempStarting TS ON TA_Tbl_AuditOperation.RecordID = TS.RecordID
	and TS.TableID=TA_Tbl_AuditOperation.FieldID and TA_Tbl_AuditTable.TableID=ts.TableID
	''
	set @sql = @sql + '' Left JOIN TA_Tbl_Employee ON TA_Tbl_AuditOperation.EmployeeID = TA_Tbl_Employee.Employee_Id''
	set @sql = @sql + '' WHERE TA_Tbl_AuditTable.Status = 1 AND TA_Tbl_AuditField.Status = 1 AND (TA_Tbl_AuditOperation.OprDate >= CONVERT(DATETIME,'''''' + convert(nvarchar(20),@fromDate,101) + '' 00:00:000'''', 102) and TA_Tbl_AuditOperation.OprDate <=  CONVERT(DATETIME,'''''' + convert(nvarchar(20),@toDate,101) +'' 23:59:000'''', 102)) ''
	--set @sql = @sql + '' WHERE TA_Tbl_AuditTable.Status = 1 AND TA_Tbl_AuditField.Status = 1 AND (TA_Tbl_AuditOperation.OprDate >= CONVERT(char(11),'''''' + cast (@fromDate as nvarchar(11)) + '''''', 101) and TA_Tbl_AuditOperation.OprDate <=  CONVERT(char(11),'''''' + cast(@toDate as nvarchar(11)) +'''''', 101)) ''
	--set @sql = @sql + '' WHERE 1=1 ''
	--		set @sql = @sql + '' TA_Tbl_AuditOperation.OprDate Between '''''' + cast (@fromDate as nvarchar(11)) + '''''' and  '''''' + cast(@toDate as nvarchar(11)) +'''''') ''
	if Not (@opr='''' or @opr=''All'')		
		Begin
			set @sql = @sql + '' And TA_Tbl_AuditOperation.Opr='''''' +@opr + '''''' ''
		End
	if Not(@TableDescription='''' or @TableDescription=''All'')
		Begin
			set @sql = @sql + '' And TA_Tbl_AuditTable.TableDescription='''''' +@TableDescription + '''''' ''
		End		
	set @sql = @sql + '' ORDER BY TA_Tbl_AuditOperation.OprDate, TA_Tbl_AuditOperation.RecordID''
	Create table #TempFinal(TableName nvarchar(max),fieldName nvarchar(max),Operation nvarchar(max),Oldvalue varchar(max),NewValue nvarchar(max),
	EmployeeID varchar(max),oprDate datetime,Employee_Code_Id varchar(max),EmployeeName varchar(max),Newvaluedatetime datetime,DataType nvarchar(max)
	,RecordID int,Oldvaluedatetime datetime,Orderby int
	)
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)	
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	insert into #TempFinal exec (@sql)	
	select 
	TableName,fieldName,Operation,
	case when DataType=''datetime'' then 
	case when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Oldvaluedatetime,106),'' '',''-'')
		 when cast(@dateFormat as varchar(100))=103 then CONVERT(VARCHAR, Oldvaluedatetime, 103) 
		 else CONVERT(VARCHAR, Oldvaluedatetime, 101) 
	end 
	else Oldvalue end Oldvalue,
	EmployeeID ,oprDate ,Employee_Code_Id ,EmployeeName	,
	case when DataType=''datetime'' then 
	case when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Newvaluedatetime,106),'' '',''-'')
		 when cast(@dateFormat as varchar(100))=103 then CONVERT(VARCHAR, Newvaluedatetime, 103) 
		 else CONVERT(VARCHAR, Newvaluedatetime, 101) 
	end 
	else NewValue end NewValue,RecordID 
	from #TempFinal order by orderby,oprdate
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeaveAnalysis]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeaveAnalysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author	: Kumuthini. L
-- Create Date	: 09-Apr-09
-- Description	: Leave Analysis Report
-- =============================================
--select * from ta_tbl_leveldetails
-- exec [Proc_TA_RptLeaveAnalysis] ''01/Feb/2013'', ''28/feb/2013'', '''', '''', ''107'',''SuperAdmin'', 0, ''Planned'', ''WI'', ''WOI'',0
-- Proc_TA_RptLeaveAnalysis ''01/Jan/2014'',''31/Jan/2014'','''','''',''3'',''SuperAdmin'',''0'',''Planned'',''WI'',''WOI'',0
-- Proc_TA_RptLeaveAnalysis ''01/Feb/2014'',''28/Feb/2014'','''','''',''107'',''EIT-PMs'',''8'',''Planned'',''WI'',''WOI'',361
-- Proc_TA_RptLeaveAnalysis ''01/Feb/2014'',''28/Feb/2014'','''','''',''107'',''EIT-PMs'',''8'',''Planned'',''WI'',''WOI'',361
--  Proc_TA_RptLeaveAnalysis ''01/Jan/2014'',''31/Jan/2014'','''','''',''3'',''SuperAdmin'',''0'',''Planned'',''WI'',''WOI'',0
CREATE PROCEDURE [dbo].[Proc_TA_RptLeaveAnalysis] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),	
	@EmployeeName varchar(50),
	@LevelID varchar(1000),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@strLeavePlanned varchar(20), 
	@strLeaveWI varchar(20),
	@strLeaveWOI varchar(20),
	@EmpAutoId bigint
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@LevelID) as LevelId
	DECLARE @query AS VARCHAR(8000)
	SET @query = ''''
	DECLARE @query1 AS VARCHAR(8000)
	SET @query1 = ''''
	CREATE TABLE #Temp(LeaveType nVarchar(10))   
	INSERT INTO #Temp SELECT LeaveType FROM TA_Tbl_LeaveType WHERE IsDeleted = 0
	INSERT INTO #Temp VALUES(''LOP'')
	INSERT INTO #Temp VALUES(''CompOff'')
	INSERT INTO #Temp VALUES(''ESI'')
	INSERT INTO #Temp VALUES(''RH'')
	CREATE TABLE #TempProcessedData (
		[Employee_Code_Id] [nvarchar](20) NULL,
		[Date] [datetime] NULL,
		[Shift_Id] [int] NULL,
		[InTime] [nvarchar](25) NULL,
		[OutTime] [nvarchar](25) NULL,
		[HrsWork] [nvarchar](10) NULL,
		[HrsOT] [nvarchar](10) NULL,
		[NormOT] [nvarchar](10) NULL,
		[OffOT] [nvarchar](10) NULL,
		[HolOT] [nvarchar](10) NULL,
		[EarlyOut] [nvarchar](10) NULL,
		[LateIn] [nvarchar](10) NULL,
		[Attendance] [nvarchar](20) NULL,
		[WorkHrs] [nvarchar](10) NULL,
		[HrsLess] [nvarchar](10) NULL,
		[HrsExtra] [nvarchar](10) NULL,
		[LateInMins] [float] NULL,
		[EarlyOutMins] [float] NULL,
		[ExtraMins] [float] NULL,
		[OtMins] [float] NULL,
		[OvertimeStatus] [nvarchar](50) NULL,
		[TotalDays] [numeric](18, 1) NULL,
		[LeaveCode] [nvarchar](20) NULL,
		[LateEntryReason] [nvarchar](260) NULL,
		[EarlyOutReason] [nvarchar](260) NULL,
		[BreakOut] [nvarchar](25) NULL,
		[BreakIn] [nvarchar](25) NULL,
		[BreakHours] [nvarchar](10) NULL,
		[BreakLate] [nvarchar](10) NULL,
		[BreakLateMins] [float] NULL,
		[TotalLate] [nvarchar](10) NULL,
		[TotalLateMins] [float] NULL,
		[ProcessFlag] [int] NULL,
		[Status] [nvarchar](50) NULL,
		[FNAttendanceCode] [nvarchar](15) NULL,
		[ANAttendanceCode] [nvarchar](15) NULL,
		[DinnerOut] [nvarchar](15) NULL,
		[DinnerIn] [nvarchar](15) NULL,
		[DinnerHours] [nvarchar](10) NULL,
		[DinnerLate] [nvarchar](10) NULL,
		[DinnerLateMins] [float] NULL,
	[LateExit] [bit] NULL,
		[EarlyEntry] [bit] NULL
	)
	insert into #TempProcessedData 
	select  Employee_Code_Id, Date, Shift_Id, InTime, OutTime, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, Attendance, WorkHrs, HrsLess, HrsExtra, LateInMins, EarlyOutMins, ExtraMins, OtMins, OvertimeStatus, TotalDays, LeaveCode, LateEntryReason, EarlyOutReason, BreakOut, BreakIn, BreakHours, BreakLate, BreakLateMins, TotalLate, TotalLateMins, ProcessFlag, Status, FNAttendanceCode, ANAttendanceCode, DinnerOut, DinnerIn, DinnerHours, DinnerLate, DinnerLateMins, LateExit, EarlyEntry from TA_Tbl_ProcessedData where 
	(ta_tbl_processedData.date >= CONVERT(DATETIME, cast( @fromDat as nvarchar(50)), 102)) 
	AND (ta_tbl_processedData.date <= CONVERT(DATETIME, cast(@todat as nvarchar(50)), 102)) 
	SET @query = ''SELECT replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as Level,(dbo.Func_TA_AbsentDate(''''''+ cast(@fromDat as varchar(20)) + '''''', '''''' + cast(@toDat as varchar(20)) + '''''', emp.employee_Code_id ) + '''' '''' + dbo.Func_TA_PendingLeaveDate(''''''+ cast(@fromDat as varchar(20)) + '''''', '''''' + cast(@toDat as varchar(20)) + '''''', emp.employee_id )) as AbsentDate,dbo.Func_TA_LeaveDate(''''''+ cast(@fromDat as varchar(20)) + '''''', '''''' + cast(@toDat as varchar(20)) + '''''', emp.employee_id ) as LeaveDate,dbo.Func_TA_PermissionDate(''''''+ cast(@fromDat as varchar(20)) + '''''', '''''' + cast(@toDat as varchar(20)) + '''''', emp.employee_id ) as PermiDate, emp.employee_code_id as [Employee Id],isnull(emp.Employee_FirstName,'''''''') + SPACE(1) + isnull(emp.Employee_MiddleName,'''''''')+ SPACE(1) + isnull(emp.Employee_LastName,'''''''') AS [Employee Name],''
	SET @query = @query + '' ''''Total Late Days'''' =  ISNULL(count(CASE lateinmins WHEN 0 THEN NULL ELSE CASE FNAttendanceCode WHEN ''''Present'''' THEN lateinmins ELSE CASE ANAttendanceCode WHEN ''''Present'''' THEN lateinmins END END END),0)  , ''
	SET @query = @query + '' ''''Total Late Hours'''' =  ISNULL(sum(CASE lateinmins WHEN NULL THEN 0 ELSE CASE FNAttendanceCode WHEN ''''Present'''' THEN lateinmins ELSE CASE ANAttendanceCode WHEN ''''Present'''' THEN lateinmins ELSE 0 END END END),0) ''	
	SET @query = @query + '' ,ISNULL(Per.PermissionHours,0) AS PermissionHours, isnull(Leave.LeaveType,''''CL'''') as LeaveType, isnull(Leave.LeaveTypeTotalDays,0) as LeaveTypeTotalDays,isnull(Leave.IntimationType,''''P'''') as IntimationType FROM ''	
	SET @query = @query + '' (SELECT E.Leave_Sanc_Authority,E.Reporting_To,E.Employee_Id,E.SwipeCardNo,E.employee_code_id,E.Employee_FirstName,E.Employee_MiddleName,E.Employee_LastName,E.Employee_Status,E.Report_Exclude,E.IsDeleted from TA_Tbl_Employee E ) emp''
	SET @query = @query + '' inner join #TempProcessedData on #TempProcessedData.Employee_code_id = emp.SwipeCardNo''
	SET @query = @query + '' inner join TA_Tbl_EmployeeLevel on emp.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	SET @query = @query + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id ''
	SET @query = @query + '' inner join TA_Tbl_EmployeeDesignation ON emp.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId''
	SET @query = @query + '' inner join TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @query = @query + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @query = @query + '' inner join #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId ''
    SET @query = @query + '' LEFT OUTER JOIN ( SELECT Per.Employee_Id,SUM(DateDiff(n,Per.Permission_FromTime,Per.Permission_ToTime)) AS PermissionHours ''
	SET @query = @query + '' FROM TA_Tbl_Permission Per LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Id = Per.Employee_Id ''
	SET @query = @query + '' where (Per.permission_date >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''	
	SET @query = @query + '' and (Per.permission_date <= CONVERT(DATETIME, '''''' +cast( @todat as nvarchar(50))   + '''''', 102))  and per.permission_status=''''Approved'''' and per.IsDeleted=''''0''''	''
	SET @query = @query + '' GROUP BY Per.Employee_Id ) Per ON Per.Employee_Id = emp.Employee_Id ''
	SET @query = @query + '' LEFT OUTER JOIN (SELECT L.Employee_Id,LeaveType = CASE L.Type WHEN ''''Leave'''' THEN ''
	SET @query = @query + '' (SELECT LeaveType FROM TA_Tbl_LeaveType WHERE LeaveType_Id = L.LeaveType_id) ''
	SET @query = @query + '' ELSE L.Type END, sum(NumberOfDays) AS "LeaveTypeTotalDays" ,L.IntimationType''
	SET @query = @query + '' FROM TA_Tbl_LeaveApplication L ''
	SET @query = @query + '' LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Id = L.Employee_Id ''
	set @query = @query + '' where L.Status=''''Approved'''' and L.isdeleted=0 and (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between L.Leave_FromDate and L.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between L.Leave_FromDate and L.Leave_ToDate) )''
	set @query = @query + '' or (L.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (L.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if(@strLeavePlanned!='''' and @strLeaveWI!='''' and @strLeaveWOI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''P'''' or L.Intimationtype=''''UP-WI'''' or L.Intimationtype=''''UP-WOI'''')''
		end
	else if(@strLeavePlanned!='''' and @strLeaveWI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''P'''' or L.Intimationtype=''''UP-WI'''') ''
		end
	else if(@strLeaveWI!='''' and @strLeaveWOI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''UP-WI'''' or L.Intimationtype=''''UP-WOI'''') ''
		end
	else if(@strLeavePlanned!='''' and @strLeaveWOI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''P'''' or L.Intimationtype=''''UP-WOI'''') ''
		end
	else if (@strLeavePlanned!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''P'''') ''
		end
	else if(@strLeaveWOI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''UP-WOI'''') ''
		end
	else if(@strLeaveWI!='''')
		begin
			set @query = @query + '' and (L.Intimationtype=''''UP-WI'''') ''
		end
	SET @query = @query + '' GROUP BY L.Employee_Id,E.Employee_Id,E.SwipeCardNo,E.employee_code_id,E.Employee_FirstName,E.Employee_MiddleName,E.Employee_LastName,E.Employee_Status,E.Report_Exclude,E.IsDeleted,L.LeaveType_id,L.Type,L.IntimationType) Leave ON Leave.Employee_Id=emp.Employee_Id ''        	SET @query1 = @query1 + '' where  emp.IsDeleted = 0 AND emp.report_exclude = 0 AND emp.employee_status = 1 AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  TA_Tbl_EmployeeLevel.EmployeeId = emp.Employee_Id AND TA_Tbl_EmployeeLevel.EffectiveDate <=CONVERT(DATETIME,'''''' + cast( @toDat as nvarchar(50))  + '''''', 102) order by TA_Tbl_EmployeeLevel.EffectiveDate desc) ''
	SET @query1 = @query1 + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = emp.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @query1 = @query1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' 
			AND (Emp.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or Emp.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''') ''
		END 
	IF NOT(@EmployeeName = '''' OR @EmployeeName = ''0'')
		BEGIN
			Declare @Tempname nvarchar(200)
			set @Tempname= ''(emp.Employee_FirstName + '''' '''' + isnull(emp.Employee_LastName,'''''''')''
			set @query1 = @query1 + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		END
	IF NOT (@empId = '''' OR @empId = ''0'')
		BEGIN
			SET @query1 = @query1 + '' and emp.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		END
	 if(@isReportingto > 0)
		BEGIN
			set @query1 = @query1 + '' and (emp.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	SET @query1 = @query1 + '' group by emp.employee_code_id,emp.employee_id,emp.employee_firstname,emp.employee_middlename,emp.employee_lastname, Per.PermissionHours, Leave.LeaveType, Leave.LeaveTypeTotalDays,Leave.IntimationType,ta_tbl_leveldetails.name,TA_Tbl_Title.TitleName order by  emp.employee_firstname''
	EXEC  (@query + @query1)
	DROP TABLE #Temp
	drop table #TempProcessedData
	drop table #EmployeeIds
	drop table #LevelRights
END
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave_Angler]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan
-- Added  date: 28-Jul-2016
-- Description:	Leave Report Angler
-- Proc_TA_RptLeave ''01/may/2014'',''16/May/2014'',''id1'',0,'''',''107'',''All'',"Approved'',''Pending'',''Resend'',''Forwarded'',''Rejected'',''Reply'',''Canceled",0,0,''SuperAdmin'',''0'','''',0,0,107,0,''Both''
-- =============================================
CREATE     PROCEDURE [dbo].[Proc_TA_RptLeave_Angler]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@Unplanned int,
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10)		
AS
BEGIN
	SET NOCOUNT ON;
	declare @SQLQueryLeaveStatus as nvarchar(max)
	set @SQLQueryLeaveStatus='''';
	if (lower(@LeaveStatus)<>''all'' and isnull(@LeaveStatus,'''')<>'''' )
		begin
			if CHARINDEX(''Canceled'',@LeaveStatus) = 0
				begin				
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + '' and (TA_Tbl_LeaveApplication.Status IN ('''''' + @LeaveStatus  + ''''''))
					and (TA_Tbl_LeaveApplication.IsDeleted=0)''					
				end
			else
				begin
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + '' and ((TA_Tbl_LeaveApplication.Status IN ('''''' + @LeaveStatus  + ''''''))''
				end
		End
	else if(@LeaveStatus=''All'')
		begin		
			if CHARINDEX(''Canceled'',@LeaveStatus) = 0
				begin				
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + '' and (TA_Tbl_LeaveApplication.Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected'''',''''Resend'''',''''Reply'''')) and (TA_Tbl_LeaveApplication.IsDeleted=0)''
				end
			else
				begin
					set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + '' and ((TA_Tbl_LeaveApplication.Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected'''',''''Resend'''',''''Reply'''')) ''
				end
		end
	if CHARINDEX(''Canceled'',@LeaveStatus) > 0
		begin			
			set @SQLQueryLeaveStatus = @SQLQueryLeaveStatus + '' or (TA_Tbl_LeaveApplication.IsDeleted=1))''
		end
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' +
	 cast(@EmpSwipeCard as nvarchar(100)) + '''''')''
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(8)) + '''''')''
	Execute(@sqlEmpDesi)
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
	Execute(@sqlEmpType)
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
	Execute(@sqlEmpCategory)
	declare @sqlQuery as varchar(8000)
	declare @sqlResHoliday as varchar(8000)
	declare @sqlESIDays as varchar(8000)
	declare @sqlCompDays as varchar(8000)
	declare @sqlLOPDays as varchar(8000)
	declare @sqlMonthlyLOP as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end , ''	
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''	
	set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_Employee.Gender,TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo ''
	set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' where dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' 
	and 
	((dbo.TA_Tbl_Employee.Employee_Status = 1)
	or
	(dbo.TA_Tbl_Employee.Employee_Status = 0 and 
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_FromDate
	or
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_ToDate)
	)
	)
	) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlQuery = @sqlQuery + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlQuery=@sqlQuery+@SQLQueryLeaveStatus
	if not(@EmployeeName='''')
		begin
			Declare @Tempname nvarchar(200)
			set @Tempname= '' (TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
			set @sqlQuery = @sqlQuery + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not (@empId='''')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end	
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@Unplanned!=0)
		begin
			set @SQLQuery = @SQLQuery + '' And (TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
	set @sqlResHoliday=''''
	if (@LeaveType=''All'')
	begin
	set @sqlResHoliday='' UNION ''
	end
	set @sqlResHoliday = @sqlResHoliday + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
	set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,dbo.ta_tbl_Holiday.Holiday_Description as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end , ''
	set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
	set @sqlResHoliday = @sqlResHoliday + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo ''
	set @sqlResHoliday = @sqlResHoliday + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlResHoliday = @sqlResHoliday + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlResHoliday = @sqlResHoliday + '' And dbo.ta_tbl_Holiday.Holiday_Type=''''Y'''' ''
	set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.Type=''''Restricted Holiday'''')''
	set @sqlResHoliday = @sqlResHoliday + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlResHoliday = @sqlResHoliday + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if (@LeaveType=''Restricted Holiday'')
	begin
	set @sqlResHoliday = @sqlResHoliday + '' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  ''
	end
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlResHoliday=@sqlResHoliday+@SQLQueryLeaveStatus
	if not(@EmployeeName='''')
		begin
			Declare @TempnameRes nvarchar(200)
			set @TempnameRes= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
			set @sqlResHoliday = @sqlResHoliday + '' and ''+ @TempnameRes +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not (@empId='''')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end		
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@Unplanned!=0)
		begin
			set @sqlResHoliday = @sqlResHoliday + '' And (TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
	set @sqlESIDays=''''
		if (@LeaveType=''All'')
			begin
				set @sqlESIDays='' UNION ''
			end
	set @sqlESIDays = @sqlESIDays + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
	set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''''ESI'''' as leavetype, dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end , ''
	set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
	set @sqlESIDays = @sqlESIDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo ''
	set @sqlESIDays = @sqlESIDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlESIDays = @sqlESIDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''set @sqlESIDays = @sqlESIDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlESIDays = @sqlESIDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlESIDays = @sqlESIDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	begin
	set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''ESI''''''
	end
	set @sqlESIDays=@sqlESIDays+@SQLQueryLeaveStatus
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	if not(@EmployeeName='''')
		begin
			Declare @TempnameESI nvarchar(200)
			set @TempnameESI= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
			set @sqlESIDays = @sqlESIDays + '' and ''+ @TempnameESI +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not (@empId='''')
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end		
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@Unplanned!=0)
		begin
			set @sqlESIDays = @sqlESIDays + '' And (TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
	set @sqlCompDays=''''
	if (@LeaveType=''All'')
		begin
			set @sqlCompDays='' UNION ''
		end
	set @sqlCompDays = @sqlCompDays + '' SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
	set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,''''Comp Off'''' as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
	set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
	set @sqlCompDays = @sqlCompDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo ''
	set @sqlCompDays = @sqlCompDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlCompDays = @sqlCompDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlCompDays = @sqlCompDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlCompDays = @sqlCompDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlCompDays = @sqlCompDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	begin
	set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''Comp Off''''''
	end
	set @sqlCompDays=@sqlCompDays+@SQLQueryLeaveStatus
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	if not(@EmployeeName='''')
		begin
			Declare @TempnameCompDays nvarchar(200)
			set @TempnameCompDays= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
			set @sqlCompDays = @sqlCompDays + '' and ''+ @TempnameCompDays +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not (@empId='''')
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end		
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
			set @SQLQuery = @SQLQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@Unplanned!=0)
		begin
			set @sqlCompDays = @sqlCompDays + '' And (TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
	set @sqlLOPDays = ''''
	if (@LeaveType=''All'')
	begin
	set @sqlLOPDays='' UNION ''
	end
	set @sqlLOPDays = @sqlLOPDays + ''SELECT   dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ApplicationDate,101) as applicationDate, convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_FromDate,101) as fromDate , convert(nvarchar(20),dbo.TA_Tbl_LeaveApplication.Leave_ToDate,101) as todate, ''
	set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_LeaveApplication.NumberOfDays,(dbo.ta_tbl_leavetype.leavetype + ''''-'''' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,dbo.TA_Tbl_LeaveApplication.Leave_SessionFrom,dbo.TA_Tbl_LeaveApplication.Leave_SessionTo, dbo.TA_Tbl_LeaveApplication.Reason, Case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''''Canceled'''' else TA_Tbl_LeaveApplication.Status end ,''
	set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_LeaveApplication.Remarks, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname , ''
	set @sqlLOPDays = @sqlLOPDays + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,TA_Tbl_Employee.Gender, TA_Tbl_LeaveApplication.IntimationType, TA_Tbl_LeaveApplication.InformTo ''
	set @sqlLOPDays = @sqlLOPDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlLOPDays = @sqlLOPDays + '' where (dbo.TA_Tbl_LeaveApplication.Type=''''LOP'''' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlLOPDays = @sqlLOPDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlLOPDays = @sqlLOPDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	set @sqlLOPDays=@sqlLOPDays+@SQLQueryLeaveStatus
	if not(@EmployeeName='''')
		begin
			Declare @TempnameLopDays nvarchar(200)
			set @TempnameLopDays= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
			set @sqlLOPDays = @sqlLOPDays + '' and ''+ @TempnameLopDays +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not (@empId='''')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
		end		
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end		
	if(@EmpAutoId > 0)
		BEGIN
		  SET @SQLQuery = @SQLQuery +  '' AND (TA_Tbl_Employee.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or TA_Tbl_Employee.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''' or TA_Tbl_Employee.Employee_Id='''''' + cast(@EmpAutoId as varchar(30)) +'''''') '' 
			set @SQLQuery = @SQLQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@Unplanned!=0)
		begin
			set @sqlLOPDays = @sqlLOPDays + '' And (TA_Tbl_LeaveApplication.IntimationType!=''''P'''') ''
		end
	create table #EmpLeave(Employee_Id varchar(15),applicationDate datetime,		fromDate datetime,		todate datetime,
		NumberOfDays decimal(18,1),		leavetype varchar(100),		Leave_SessionFrom varchar(100),		Leave_SessionTo varchar(100),
		Reason varchar(1050),		status varchar(50),		Remarks varchar(1050),		TitleName varchar(500),
		empname varchar(500),		[name] varchar(500),Gender nvarchar(10),IntimationType varchar(200),		InformTo VARCHAR(MAX)		)
	if (@LeaveType=''All'')
		begin
			insert into #EmpLeave exec(@SQLQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
		end
	if (@LeaveType=''Restricted Holiday'')
		begin
			insert into #EmpLeave exec(@sqlResHoliday)
		end
	if (@LeaveType=''Comp Off'')
		begin
			insert into #EmpLeave exec(@sqlCompDays)
		end
	if (@LeaveType=''ESI'')
		begin
			insert into #EmpLeave exec(@sqlESIDays)
		end
	if (@LeaveType=''LOP'')
		begin
			insert into #EmpLeave exec(@sqlLOPDays)
		end
	else if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''Comp Off'' or @LeaveType=''ESI'' or @LeaveType=''LOP'')
		begin
			insert into #EmpLeave exec(@sqlQuery)
		end
	DECLARE @FromDate DATE, @DisplayName VARCHAR(MAX) = '''', @ColumnName VARCHAR(MAX) = '''';
	SELECT @FromDate = FromDate FROM TA_Tbl_YearSetting WHERE IsActive = 1;
	WITH [MonthName] AS(
		SELECT Mon = 0
		UNION ALL
		SELECT Mon+1 FROM [MonthName] WHERE Mon < 11)
	SELECT 
		@DisplayName = @DisplayName + (CASE WHEN @DisplayName = '''' THEN ''['' ELSE '', ['' END) + REPLACE(SUBSTRING(CONVERT(VARCHAR(11), DATEADD(M, Mon, @FromDate), 6), 4, 11), '' '', '''''''') + '']'',
		@ColumnName = @ColumnName + (CASE WHEN @ColumnName = '''' THEN ''CREATE TABLE TmpLeavedetail (EmployeeId VARCHAR(30), [Month'' ELSE '', [Month'' END) + CAST((Mon + 1) AS VARCHAR(5)) + ''] VARCHAR(50) DEFAULT '''''' + SUBSTRING(CONVERT(VARCHAR(11), DATEADD(M, Mon, @FromDate), 6), 4, 11) + ''''''''
	FROM [MonthName]
	EXEC(@ColumnName + '')'')
	IF (@Unplanned=1) 
	BEGIN
		SET @SQLQuery = ''INSERT INTO TmpLeavedetail SELECT Employee_Code_Id, '' + @DisplayName + '' FROM (''		
		SET @SQLQuery = @SQLQuery + ''SELECT LA.NumberOfDays, Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_ToDate, 6), 4, 11), '''' '''', '''''''''''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA ''
		SET @SQLQuery = @SQLQuery + ''INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id ''
		SET @SQLQuery = @SQLQuery + ''WHERE LA.IntimationType != ''''P'''' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) = DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''''Rejected'''' UNION ALL ''
		SET @SQLQuery = @SQLQuery + ''SELECT (CASE WHEN (((DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) = 1) AND (LA.NumberOfDays = 1)) THEN 0.5 ELSE (DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) END) NumberOfDays, ''
		SET @SQLQuery = @SQLQuery + ''Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_FromDate, 6), 4, 11), '''' '''', '''''''''''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA ''
		SET @SQLQuery = @SQLQuery + ''INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id ''
		SET @SQLQuery = @SQLQuery + ''WHERE LA.IntimationType != ''''P'''' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) != DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''''Rejected'''' UNION ALL ''
		SET @SQLQuery = @SQLQuery + ''SELECT (CASE WHEN (((DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) = 1) AND (LA.NumberOfDays = 1)) THEN 0.5 ELSE LA.NumberOfDays - (DATEDIFF(D, LA.Leave_FromDate, DATEADD(S, -1, DATEADD(MM, DATEDIFF(M, 0, LA.Leave_FromDate)+1, 0))) + 1) END) NumberOfDays,''
		SET @SQLQuery = @SQLQuery + ''Emp.Employee_Code_Id, REPLACE(SUBSTRING(CONVERT(VARCHAR(11), LA.Leave_ToDate, 6), 4, 11), '''' '''', '''''''''''''''') LeaveMonth FROM TA_Tbl_LeaveApplication LA ''
		SET @SQLQuery = @SQLQuery + ''INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id ''
		SET @SQLQuery = @SQLQuery + ''WHERE LA.IntimationType != ''''P'''' AND YS.IsActive = 1 AND LA.IsDeleted = 0 AND DATEPART(M,LA.Leave_FromDate) != DATEPART(M,LA.Leave_ToDate) AND LA.[Status] != ''''Rejected'''' ) Tbl ''
		SET @SQLQuery = @SQLQuery + ''PIVOT (SUM(NumberOfDays) FOR LeaveMonth IN ('' + @DisplayName + '')) AS Pvt''
		EXEC (@SQLQuery)
	END
	SELECT EL.*,
		LD.EmployeeId, 
		ISNULL(LD.Month1, 0.0) Month1,
		ISNULL(LD.Month2, 0.0) Month2,
		ISNULL(LD.Month3, 0.0) Month3,
		ISNULL(LD.Month4, 0.0) Month4,
		ISNULL(LD.Month5, 0.0) Month5,
		ISNULL(LD.Month6, 0.0) Month6,
		ISNULL(LD.Month7, 0.0) Month7,
		ISNULL(LD.Month8, 0.0) Month8,
		ISNULL(LD.Month9, 0.0) Month9,
		ISNULL(LD.Month10, 0.0) Month10,
		ISNULL(LD.Month11, 0.0) Month11,
		ISNULL(LD.Month12, 0.0) Month12
	FROM #EmpLeave EL
		LEFT JOIN TmpLeavedetail LD ON LD.EmployeeId = EL.Employee_Id
	order by Employee_Id,fromDate asc	
	SELECT [2] M1, [3] M2, [4] M3, [5] M4, [6] M5, [7] M6, [8] M7, [9] M8, [10] M9, [11] M10, [12] M11, [13] M12 FROM 
	(SELECT REPLACE(REPLACE(REPLACE(COLUMN_DEFAULT, ''('''''', ''''), '''''')'', ''''), '' '', '''''''') COLUMN_DEFAULT, ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE ''TmpLeavedetail'' AND COLUMN_NAME != ''EmployeeId'' ) Tbl 
	PIVOT (MAX(COLUMN_DEFAULT) FOR ORDINAL_POSITION IN([2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13])) Pvt
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights		
	DROP TABLE TmpLeavedetail
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeave]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Proc_TA_RptLeave ''2020/01/01'',''2020/09/24'','''',''0'','''',''0,24'',''All'',''All'',1,1,''superadmin'',''0'','''',0,3,''Both'',1
-- =============================================
CREATE     PROCEDURE [dbo].[Proc_TA_RptLeave]
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	--Get the Current date time format
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!=''Superadmin'' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)
	declare @sqlResHoliday as varchar(8000)
	declare @sqlESIDays as varchar(8000)
	declare @sqlCompDays as varchar(8000)
	declare @sqlLOPDays as varchar(8000)
	declare @sqlMonthlyLOP as varchar(8000)
	
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''SELECT 
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,
	replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')
			else CONVERT(VARCHAR, Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as applicationDate, 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as fromDate , 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.TA_Tbl_LeaveType.LeaveType) as leavetype,	
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''''''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''''  (''''+rtrim(Intervening)+'''')''''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks
	FROM dbo.TA_Tbl_LeaveApplication INNER JOIN
	dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id
	INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id 
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id
	INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId
	INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where dbo.TA_Tbl_LeaveApplication.Type=''''Leave'''' 
	and 
	((dbo.TA_Tbl_Employee.Employee_Status = 1)
	or
	(dbo.TA_Tbl_Employee.Employee_Status = 0 and 
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_FromDate
	or
	(dbo.TA_Tbl_Employee.InActiveDate>= dbo.TA_Tbl_LeaveApplication.Leave_ToDate)
	)
	)
	) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
	set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlQuery = @sqlQuery + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	if not(@LeaveStatus=''All'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end	
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end			
	set @sqlResHoliday=''''
	if (@LeaveType=''All'')
		begin
			set @sqlResHoliday='' UNION ''
		end
	set @sqlResHoliday = @sqlResHoliday + '' SELECT  
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,
	replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')
			else CONVERT(VARCHAR, Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as applicationDate, 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as fromDate , 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	ta_tbl_Holiday.Holiday_Description as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''''''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''''  (''''+rtrim(Intervening)+'''')''''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,	
	TA_Tbl_LeaveApplication.Remarks''
	set @sqlResHoliday = @sqlResHoliday + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlResHoliday = @sqlResHoliday + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN dbo.ta_tbl_Holiday ON dbo.ta_tbl_Holiday.Holiday_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlResHoliday = @sqlResHoliday + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlResHoliday = @sqlResHoliday + '' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlResHoliday = @sqlResHoliday + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	set @sqlResHoliday = @sqlResHoliday + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlResHoliday = @sqlResHoliday + '' And dbo.ta_tbl_Holiday.Holiday_Type=''''Y'''' ''
	set @sqlResHoliday = @sqlResHoliday + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) And (dbo.TA_Tbl_LeaveApplication.Type=''''Restricted Holiday'''')''
	set @sqlResHoliday = @sqlResHoliday + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlResHoliday = @sqlResHoliday + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if (@LeaveType=''Restricted Holiday'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and dbo.ta_tbl_Holiday.Holiday_Id=dbo.TA_Tbl_LeaveApplication.LeaveType_Id  ''
		end
	if not(@LeaveStatus=''All'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end	
	if(@Gender<>''Both'')
		begin
			set @sqlResHoliday = @sqlResHoliday + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlResHoliday = @sqlResHoliday + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlResHoliday = @sqlResHoliday + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end	
	-- ESI Leaves
	set @sqlESIDays=''''
	if (@LeaveType=''All'')
		begin
			set @sqlESIDays='' UNION ''
		end
	set @sqlESIDays = @sqlESIDays + '' SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,
	replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')
			else CONVERT(VARCHAR, Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as applicationDate, 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as fromDate , 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	''''ESI'''' as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''''''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''''  (''''+rtrim(Intervening)+'''')''''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks''
	set @sqlESIDays = @sqlESIDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlESIDays = @sqlESIDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlESIDays = @sqlESIDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlESIDays = @sqlESIDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlESIDays = @sqlESIDays + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	set @sqlESIDays = @sqlESIDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlESIDays = @sqlESIDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
	set @sqlESIDays = @sqlESIDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlESIDays = @sqlESIDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''ESI''''''
	if not(@LeaveStatus=''All'')
		begin
			set @sqlESIDays = @sqlESIDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end	
	if(@Gender<>''Both'')
		begin
			set @sqlESIDays = @sqlESIDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlESIDays = @sqlESIDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlESIDays = @sqlESIDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end	
	-- Comp Off Leaves
	set @sqlCompDays=''''
	if (@LeaveType=''All'')
		begin
			set @sqlCompDays='' UNION ''
		end
	set @sqlCompDays = @sqlCompDays + '' SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,
	replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')
			else CONVERT(VARCHAR, Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as applicationDate, 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as fromDate , 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	''''Comp Off'''' as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''''''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''''  (''''+rtrim(Intervening)+'''')''''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks''
	set @sqlCompDays = @sqlCompDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlCompDays = @sqlCompDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlCompDays = @sqlCompDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlCompDays = @sqlCompDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlCompDays = @sqlCompDays + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	set @sqlCompDays = @sqlCompDays + '' where (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlCompDays = @sqlCompDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) '' 		
	set @sqlCompDays = @sqlCompDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlCompDays = @sqlCompDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.Type= ''''Comp Off''''''
	if not(@LeaveStatus=''All'')
		begin
			set @sqlCompDays = @sqlCompDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlCompDays = @sqlCompDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlCompDays = @sqlCompDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlCompDays = @sqlCompDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
	--LOP Days
	set @sqlLOPDays = ''''
	if (@LeaveType=''All'')
		begin
			set @sqlLOPDays='' UNION ''
		end
	set @sqlLOPDays = @sqlLOPDays + ''SELECT   
	dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Id, 
	isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + space(1) + isnull(dbo.TA_Tbl_Employee.Employee_lastName,'''''''') as empname, 
	replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,
	replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
	TA_Tbl_Employee.Gender,
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''')
			else CONVERT(VARCHAR, Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as applicationDate, 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as fromDate , 
	case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
			else CONVERT(VARCHAR, Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') 
	end as todate,
	TA_Tbl_LeaveApplication.Leave_SessionFrom,
	TA_Tbl_LeaveApplication.Leave_SessionTo, 
	TA_Tbl_LeaveApplication.NumberOfDays,	
	(dbo.ta_tbl_leavetype.leavetype + ''''-'''' + dbo.TA_Tbl_LeaveApplication.Type) as leavetype,
	TA_Tbl_LeaveApplication.Status,
	TA_Tbl_LeaveApplication.Reason,
	case	when Intervening is not null and Intervening!='''''''' then convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays)+''''  (''''+rtrim(Intervening)+'''')''''
			else convert(varchar(10),TA_Tbl_LeaveApplication.NumberOfDays) 
	end as display,
	TA_Tbl_LeaveApplication.Remarks''
	set @sqlLOPDays = @sqlLOPDays + '' FROM dbo.TA_Tbl_LeaveApplication INNER JOIN''
	set @sqlLOPDays = @sqlLOPDays + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_LeaveApplication.Employee_Id = dbo.TA_Tbl_Employee.Employee_Id''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN dbo.ta_tbl_leavetype ON dbo.ta_tbl_leavetype.LeaveType_Id = dbo.TA_Tbl_LeaveApplication.LeaveType_Id''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlLOPDays = @sqlLOPDays + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlLOPDays = @sqlLOPDays + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	if not(@LeaveStatus=''All'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end
	set @sqlLOPDays = @sqlLOPDays + '' where (dbo.TA_Tbl_LeaveApplication.Type=''''LOP'''' and dbo.TA_Tbl_LeaveApplication.LeaveType_Id<>0) and (dbo.TA_Tbl_Employee.Employee_Status = 1) AND (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Report_Exclude = 0) ''
	set @sqlLOPDays = @sqlLOPDays + '' And (dbo.TA_Tbl_LeaveApplication.IsDeleted=0) ''
	set @sqlLOPDays = @sqlLOPDays + '' AND (((CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) or (CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102) between dbo.TA_Tbl_LeaveApplication.Leave_FromDate and dbo.TA_Tbl_LeaveApplication.Leave_ToDate) )''
	set @sqlLOPDays = @sqlLOPDays + '' or (dbo.TA_Tbl_LeaveApplication.Leave_FromDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)) or (dbo.TA_Tbl_LeaveApplication.Leave_ToDate between CONVERT(DATETIME, '''''' +cast(@fromDat as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@todat as nvarchar(50))   + '''''', 102)))''
	if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''ESI'' or @LeaveType=''Comp Off'' or @LeaveType=''LOP'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.LeaveType_id= '' + cast(@LeaveType as nvarchar(100))
		end
	if not(@LeaveStatus=''All'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and dbo.TA_Tbl_LeaveApplication.Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end
	if(@Gender<>''Both'')
		begin
			set @sqlLOPDays = @sqlLOPDays + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlLOPDays = @sqlLOPDays + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlLOPDays = @sqlLOPDays + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end	
	if (@LeaveType=''All'')
		begin
			exec(@sqlQuery+@sqlResHoliday+@sqlESIDays+@sqlCompDays+@sqlLOPDays)
		end
	if (@LeaveType=''Restricted Holiday'')
		begin
			exec(@sqlResHoliday)
		end
	if (@LeaveType=''Comp Off'')
		begin
			exec(@sqlCompDays)
		end
	if (@LeaveType=''ESI'')
		begin
			exec(@sqlESIDays)
		end
	if (@LeaveType=''LOP'')
		begin
			exec(@sqlLOPDays)
		end
	else if not(@LeaveType=''All'' or @LeaveType=''Restricted Holiday'' or @LeaveType=''Comp Off'' or @LeaveType=''ESI'' or @LeaveType=''LOP'')
		begin
			exec(@sqlQuery)
		end
	--print(@sqlQuery)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateIn]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateIn]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_RptLateIn '''',''0'',''2020/01/01'',''2020/07/30'',''Sathishkumar ,Manikandan ,'',0,0,0,''SuperAdmin'',''1'','''',0,0,''Both'',0,1,'' ''
CREATE  PROCEDURE [dbo].[Proc_TA_RptLateIn]  
(  
	@EmployeeID VarChar(max),   
	@LevelID VarChar(8000),  
	@FromDate VarChar(50),   
	@ToDate VarChar(50),   
	@EmployeeName varchar(max),  
	@shift int,  
	@EmployeeCategory int,  
	@EmployeeType int,  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int,
	@MINExceptionHOURS AS VARCHAR(6)
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	DECLARE @local_MINExceptionHOURS AS VARCHAR(6)
    SET @local_FROMDAT			= LTRIM(RTRIM(@FromDate))
    SET @local_TODAT			= LTRIM(RTRIM(@ToDate))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))    
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@ExportType))  
    SET @local_MINExceptionHOURS= LTRIM(RTRIM(@MINExceptionHOURS))  
	Declare @sqlTempProcessedData varchar(max) 
	Declare @sqlTempProcessedData2 varchar(max)
	DECLARE @dateFormat as int
	Declare @SelectSQL As Varchar(max)
	DECLARE @TimeFormat as nvarchar(25)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_USERGROUPNAME
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!=''Superadmin'' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EMPAUTOID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EMPAUTOID) as EmpAutoId
	end
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX('':'',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX('':'',@local_MINExceptionHOURS)+1,2)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		Process_Rec_ID bigint,
		LateIn nvarchar(10),
		LateInMins float,
		LateEntryReason nvarchar(260),
		Shift_StartTime nvarchar(10)
	)	
	insert into #LevelRights	select * from [dbo].[fn_TA_GetParentChild](@local_USERGROUPNAME,@local_PARENTID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID	
	insert into #EmpType		exec [Proc_TA_EmpType] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE	
	insert into #EmpCategory	exec [Proc_TA_EmpCategory] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY	
	insert into #EmpLevel		exec  [Proc_TA_EmpLevel] @local_TODAT,@local_EMPLOYEEID	
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@local_EMPLOYEEID is not null and @local_EMPLOYEEID <> '''')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EMPLOYEEID)
		end
	if(@local_EMPLOYEENAME is not null and @local_EMPLOYEENAME <> '''')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EMPLOYEENAME,'','')
		end
	insert into #TempEmployee 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee emp
	inner join #EmpLevel on #EmpLevel.EmployeeId=emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId 
	left join #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id 
	left join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id
	where SwipeCardNo is not null and emp.Isdeleted=0  and emp.report_exclude=0
	and (isnull(@EmployeeID,'''')='''' or emp.Employee_Code_Id in (select * from #EmployeeID))
	and (isnull(@EmployeeName,'''')='''' or emp.Employee_Code_Id in (select * from #EmployeeName))
	and (isnull(@Gender,''Both'')=''Both'' or emp.Gender=@Gender)
	insert into #TempProcessedData select	TE.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.Process_Rec_ID,
											PD.LateIn,
											PD.LateInMins,
											PD.LateEntryReason,
											(select Shift_StartTime from ta_tbl_shift where shift_id=PD.Shift_Id)
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee TE on TE.EmpSwipeCardNo=PD.Employee_Code_Id	
	where (PD.Date >= CONVERT(DATETIME,@local_FROMDAT, 102)) 
	AND (PD.Date <= CONVERT(DATETIME,@local_TODAT, 102)) and PD.LateIn <> ''00:00:00'' And PD.LateIn <> ''00:00'' And PD.LateIn <> ''0'' 
	AND LateInMins > 0 AND InTime is not null AND InTime <> ''0'' AND InTime <> ''00:00'' and processflag=1
	and(isnull(@shift,0)=0 or PD.shift_id=@shift)
	and (isnull(@TOTALExceptionMIN,0)=0 or PD.LateInMins >=@TOTALExceptionMIN)
	Set @EmployeeName = @local_EMPLOYEENAME 
	--Got error in grid control internally 28-07-2020 change the name to Process_Rec_ID instead of Peocess_Rec_ID
	Create table #TempLate(Process_Rec_ID int, CardNo nVarchar(30), [Employee Name] nvarchar(100),designation nvarchar(100),[Level Name] nvarchar(200),Shift_StartTime nvarchar(20),shift_shortName nvarchar(10),Date nvarchar(30),InTime nvarchar(30),LateBy nvarchar(30),Reason nvarchar(Max),Gender nvarchar(10),LateInMins decimal(18,2),format datetime)
	insert into #TempLate
	SELECT PD.Process_Rec_ID,
	ED.Employee_Code_Id AS CardNo,ED.Employee_FirstName + 
	'' '' + isnull(ED.Employee_LastName,'''') AS ''Employee Name'', 
	replace(T.TitleName,''&amp;'',''&'')  AS Designation, 
	replace(L.name,''&amp;'',''&'')  AS [Level Name],
	PD.Shift_StartTime,replace(sh.shift_shortName,''&amp;'',''&'') as shift_shortName,
	case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, Date,@dateFormat) 
	end AS Date,
	CASE	WHEN @TIMEFORMAT=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
			ELSE InTime
	END InTime,
	LateIn as LateBy,
	PD.LateEntryReason as Reason,
	ED.Gender,
	LateInMins,
	Date as format
	FROM TA_Tbl_Employee ED
	Inner join #EmpLevel Lev on Lev.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id
	Inner join #EmpDesignation  EDesig on EDesig.employeeid=ED.Employee_Id
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON T.GradeId = TA_Tbl_Grade.Grade_ID
	Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id
	Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id
	INNER JOIN #TempProcessedData PD ON ED.Employee_ID = PD.EmpAutoId
	INNER JOIN dbo.ta_tbl_shift sh ON sh.shift_id = PD.shift_id
	Where 1=1 
	AND 
	(
		(ED.employee_status=1) or 
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),Date,102))
	)	
	if(@local_EXPORT=1)
	begin
		select CardNo,[Employee Name],[Level Name],designation,date,shift_shortName,Shift_StartTime, InTime,LateBy,
		Reason,Process_Rec_ID,Gender,LateInMins,format from #TempLate 
		order by CardNo,CONVERT(datetime,format)
	end
	else
	begin		
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(30))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempLate
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempLate order by format
		declare @couLevel int
		select @couLevel=COUNT(*) from #TempLevelName
		declare @couDate int
		select @couDate=COUNT(*) from #TempDate
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + ''@''
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempLate where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + ''#''
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
		drop table #TempDate
		drop table #TempLevelName
		drop table #TempLate
	end
	drop table #EmpCategory
	drop table #EmpDesignation
	drop table #EmpLevel
	drop table #EmployeeIds	
	drop table #EmpType
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee
 End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLateExit]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLateExit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  senthilkumar.np  
-- ALTER  date: 02-August-07  
-- Modified By : sashma
-- Modified Date : 12-May-2011
-- Description: Getting Late Exit - report  
-- Modified By : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description: Sql Query Optimization 
--	Proc_TA_RptLateExit ''2016/01/04'',''2016/12/04'','''',0,'''','''',0,0,''SuperAdmin'',''0'','''',0,0,''Both''
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_RptLateExit]  
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeId varchar(max),  
	 @shift int,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @MINExceptionHOURS AS VARCHAR(6),
	 @EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;  
	DECLARE @dateFormat as int
	Declare @sqlTempProcessedData varchar(max)
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)
	declare @sqlQuery as varchar(max)
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@MINExceptionHOURS,0,CHARINDEX('':'',@MINExceptionHOURS))*60 + SUBSTRING(@MINExceptionHOURS,CHARINDEX('':'',@MINExceptionHOURS)+1,2)
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsExtra nvarchar(10),
		ExtraMins int
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([EmpAutoId],[Date],[Employee_Code_Id],[Shift_Id],[HrsExtra],[ExtraMins] ASC) ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end 
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	--Employee Level insert in Temporary table
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where SwipeCardNo is not null and emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End		
	Execute(@sqlEmpLevel)
	set @sqlTempProcessedData=
	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	if(@Gender<>''Both'')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	''insert into #TempProcessedData select	#TempEmployee.EmpAutoId,
											PD.Date,
											PD.Employee_Code_Id,
											PD.InTime,
											PD.OutTime,
											PD.Shift_Id,
											PD.LateExitHours,
											PD.lateExitMins 
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id
	where lateexit=1 and  (PD.Date >= CONVERT(DATETIME,''''''+cast( @fromDat as nvarchar(50))+'''''', 102))   
	AND (PD.Date <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102))
	and PD.OutTime <> ''''0'''' and PD.OutTime <> ''''00:00:00'''' and PD.OutTime <> ''''00:00'''' 
	and PD.OutTime is not null and PD.OutTime <>'''''''' and PD.lateExitMins > 0
	''
	if(@shift<>0)
		begin
			set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' And PD.Shift_Id = '' +  cast(@shift  as nvarchar(20))  
		end
	IF (@MINExceptionHOURS<>'''')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND PD.lateExitMins >= '' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	set @sqlQuery = ''''   
	set @sqlQuery = @sqlQuery + '' select	#EmpLevel.LevelId,
											replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],
											right(dbo.ta_tbl_shift.Shift_EndTime,8)  as shiftOut,
											ta_tbl_shift.shift_shortName ,
											dbo.TA_Tbl_Employee.Employee_Code_Id as Employee_Code_Id,											
											case	when ''+cast(@dateFormat as varchar(100))+''=106 then
													REPLACE(CONVERT(VARCHAR, Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
											else CONVERT(VARCHAR, Date, ''+cast(@dateFormat as varchar(100))+'') 
											end AS Date,
											#TempProcessedData.OutTime,
											#TempProcessedData.shift_id,
											#TempProcessedData.hrsExtra,'' 
	set @sqlQuery = @sqlQuery + ''			dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''''''') as empname,
											replace(Ta_tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
											TA_Tbl_Employee.Gender,
											ExtraMins 
								  FROM  #TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.Employee_ID=#TempProcessedData.EmpAutoId ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' where 
	(
		(
			(TA_Tbl_Employee.Employee_Status=1)
			OR
			(TA_Tbl_Employee.Employee_Status=0 and convert(nvarchar(11),TA_Tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))
		)and ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 
	)'' 			
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
	set @sqlQuery = @sqlQuery + '' order by #TempProcessedData.Employee_Code_Id,#TempProcessedData.Date'' 
	Exec(@sqlQuery)  
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
	drop table #TempProcessedData
	drop table #TempEmployee
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountSummary]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptHeadCountSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_RptHeadCountSummary ''14/Sep/2016'',''SuperAdmin'',0,2,0
CREATE PROCEDURE [dbo].[Proc_TA_RptHeadCountSummary]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int,
 @ShiftId int,
 @ExportType int,
 @EmpAutoID int
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
--select * from #tempProcessSecSummary
CREATE TABLE #TempProcessedData(
	[Employee_Code_Id] [nvarchar](20) NULL,
	[Date] [datetime] NULL,
	[Shift_Id] [int] NULL,
	[InTime] [nvarchar](25) NULL,
	[OutTime] [nvarchar](25) NULL,
	[HrsWork] [nvarchar](10) NULL,
	[HrsOT] [nvarchar](10) NULL,
	[NormOT] [nvarchar](10) NULL,
	[OffOT] [nvarchar](10) NULL,
	[HolOT] [nvarchar](10) NULL,
	[EarlyOut] [nvarchar](10) NULL,
	[LateIn] [nvarchar](10) NULL,
	[Attendance] [nvarchar](20) NULL,
	[WorkHrs] [nvarchar](10) NULL,
	[HrsLess] [nvarchar](10) NULL,
	[HrsExtra] [nvarchar](10) NULL,
	[LateInMins] [float] NULL,
	[EarlyOutMins] [float] NULL,
	[ExtraMins] [float] NULL,
	[OtMins] [float] NULL,
	[OvertimeStatus] [nvarchar](50) NULL,
	[TotalDays] [numeric](18, 1) NULL,
	[LeaveCode] [nvarchar](20) NULL,
	[LateEntryReason] [nvarchar](260) NULL,
	[EarlyOutReason] [nvarchar](260) NULL,
	[ProcessFlag] [bit] NULL,
	[Status] [nvarchar](50) NULL,
	[FNAttendanceCode] [nvarchar](15) NULL,
	[ANAttendanceCode] [nvarchar](15) NULL)
	declare @SQL varchar(4000)
	set @SQL =''''
	set @SQL = @SQL + ''insert into #TempProcessedData select Employee_Code_Id,Date,Shift_Id,InTime,OutTime,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut, ''
	set @SQL = @SQL + ''LateIn,Attendance,WorkHrs,HrsLess,HrsExtra,LateInMins,EarlyOutMins,ExtraMins,OtMins,OvertimeStatus,TotalDays,LeaveCode, ''
	set @SQL = @SQL + ''LateEntryReason,EarlyOutReason,ProcessFlag,Status,FNAttendanceCode,ANAttendanceCode from TA_tbl_ProcessedData ''
	set @SQL = @SQL + ''where Date = '''''' + @Date + '''''' ''
	if(@ShiftId<>0)  
		begin  
				Set @SQL = @SQL + '' AND Ta_Tbl_ProcessedData.shift_id= ''+  cast (@ShiftId as nvarchar(50))  + ''''  
	 end  
	 exec (@SQL)
 --select * from #TempProcessedData   
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempHeadCountSummary ''    
set @SelectSQL = @SelectSQL + '' select replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,Ta_tbl_Employee.SwipeCardNo  ''
set @SelectSQL = @SelectSQL + '' as PEmployee_Code_Id,#TempProcessedData.Date as PDate,#TempProcessedData.FNAttendanceCode as FNAttendanceCode,#TempProcessedData.ANAttendanceCode as ANAttendanceCode,''
set @SelectSQL = @SelectSQL + '' '''''''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''''''' as FS_Status,'''''''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees''
set @SelectSQL = @SelectSQL + '' From #TempProcessedData inner join Ta_tbl_Employee on #TempProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo''    
set @SelectSQL = @SelectSQL + '' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId ''    
set @SelectSQL = @SelectSQL + '' where 
((Ta_tbl_Employee.Employee_Status=1)
or
(Ta_tbl_Employee.Employee_Status=0 and convert(nvarchar(11),Ta_tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))) 
and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
--if(@ShiftId<>0)  
--		begin  
--				Set @SelectSQL = @SelectSQL + '' AND Ta_Tbl_ProcessedData.shift_id= ''+  cast (@ShiftId as nvarchar(50))  + ''''  
--	 end  
exec (@SelectSQL)     
--select * from  #tempHeadCountSummary
--create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
--LateInMins bigint,intime varchar(10),outtime varchar(10)     
--,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
create table #tempHeadCountSummaryFinal (levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)    
set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempHeadCountSummaryFinal (levelID,Dept,level,Parent,ParentName) select distinct levelID,Dept,level,Parent,ParentName from #tempHeadCountSummary ''    
--set @SelectSQL = @SelectSQL + '' select distinct replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,'''''''' as  ''
--set @SelectSQL = @SelectSQL + ''PEmployee_Code_Id,'''''' + @Date +  '''''' as PDate,'''''''' as FNAttendanceCode,'''''''' as ANAttendanceCode, ''
----,0 as EarlyOutMins,0 as LateInMins,'''''''' as  intime,'''''''' as outtime ''    
----set @SelectSQL = @SelectSQL + '' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 ''    
--set @SelectSQL = @SelectSQL + '' '''''''' as OrgLevel,0 as PresentFS,0 as PresentSS,'''''''' as FS_Status,'''''''' as SS_Status, 0 as AbsentFS,0 as  AbsentSS,0 as LeaveFS,0 as  LeaveSS,0 as  LOPFS,0 as LOPSS,0 as TotalEmployees''
--set @SelectSQL = @SelectSQL + '' From Ta_tbl_Employee''    
--set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
--set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
--set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
--set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId ''    
--set @SelectSQL = @SelectSQL + '' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
exec (@SelectSQL)     
--select * from #tempHeadCountSummaryFinal
update #tempHeadCountSummaryFinal set PresentFS=PresentCount.PresentFS    
from (select count(*) as PresentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = ''Present''
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
--select * from #tempHeadCountSummaryFinal  
update #tempHeadCountSummaryFinal set PresentSS=PresentCount.PresentSS    
from (select count(*) as PresentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = ''Present''
Group by levelID) PresentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=PresentCount.levelID  
update #tempHeadCountSummaryFinal set AbsentFS=AbsentCount.AbsentFS    
from (select count(*) as AbsentFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = ''Absent''
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID    
update #tempHeadCountSummaryFinal set AbsentSS=AbsentCount.AbsentSS    
from (select count(*) as AbsentSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = ''Absent''
Group by levelID) AbsentCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=AbsentCount.levelID  
update #tempHeadCountSummaryFinal set LeaveFS=LeaveCount.LeaveFS    
from (select count(*) as LeaveFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode != ''LOP'' and FNAttendanceCode != ''Present'' and FNAttendanceCode != ''Absent''
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID    
update #tempHeadCountSummaryFinal set LeaveSS=LeaveCount.LeaveSS    
from (select count(*) as LeaveSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode != ''LOP'' and ANAttendanceCode != ''Present'' and ANAttendanceCode != ''Absent''
Group by levelID) LeaveCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LeaveCount.levelID 
update #tempHeadCountSummaryFinal set LOPFS=LOPCount.LOPFS    
from (select count(*) as LOPFS,levelID from #tempHeadCountSummary where    
FNAttendanceCode = ''LOP''
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID    
update #tempHeadCountSummaryFinal set LOPSS=LOPCount.LOPSS    
from (select count(*) as LOPSS,levelID from #tempHeadCountSummary where    
ANAttendanceCode = ''LOP''
Group by levelID) LOPCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=LOPCount.levelID  
update #tempHeadCountSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees 
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID    
inner join  #TempProcessedData on #TempProcessedData.employee_Code_id=TA_Tbl_Employee.SwipeCardNo
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0 
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempHeadCountSummaryFinal on #tempHeadCountSummaryFinal.levelID=TotalEmployeesCount.levelID    
update #tempHeadCountSummaryFinal set OrgLevel=Dept
update #tempHeadCountSummaryFinal set LOPFS=0 where LOPFS is null
update #tempHeadCountSummaryFinal set LOPSS=0 where LOPSS is null
update #tempHeadCountSummaryFinal set LeaveSS=0 where LeaveSS is null
update #tempHeadCountSummaryFinal set LeaveFS=0 where LeaveFS is null
update #tempHeadCountSummaryFinal set AbsentFS=0 where AbsentFS is null
update #tempHeadCountSummaryFinal set AbsentSS=0 where AbsentSS is null
update #tempHeadCountSummaryFinal set PresentSS=0 where PresentSS is null
update #tempHeadCountSummaryFinal set PresentFS=0 where PresentFS is null
update #tempHeadCountSummaryFinal set FS_Status=0 where FS_Status is null
update #tempHeadCountSummaryFinal set SS_Status=0 where SS_Status is null
--select * from #tempHeadCountSummaryFinal
--Status update
declare @Shift_FirstHalf_StartTime as varchar(50)
	declare @Shift_SecondHalf_StartTime as varchar(50)
	declare @FirstHalf_StartTime as varchar(50)
	declare @SecondHalf_StartTime as varchar(50)
	select @Shift_FirstHalf_StartTime=substring(Shift_FirstHalf_StartTime,7,2),@FirstHalf_StartTime=Shift_FirstHalf_StartTime,
	@Shift_SecondHalf_StartTime=substring(Shift_SecondHalf_StartTime,7,2),@SecondHalf_StartTime=Shift_SecondHalf_StartTime from ta_tbl_shift where shift_id=@ShiftId
	if(@Shift_FirstHalf_StartTime=''PM'' and @Shift_SecondHalf_StartTime=''AM'')
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,dateadd(d,1,@Date) , 101) + space(1) + @SecondHalf_StartTime		
		end
	else
		begin
		set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
		set @Shift_SecondHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @SecondHalf_StartTime		
	end
   --select getdate()
   --select @Shift_SecondHalf_StartTime
   --select @Shift_FirstHalf_StartTime
   if (getdate()<cast(@Shift_SecondHalf_StartTime as datetime))
	   begin
			update #tempHeadCountSummaryFinal set SS_Status=18000000,PresentSS=0,AbsentSS=0
	   end
   if (getdate()<cast(@Shift_FirstHalf_StartTime as datetime))
	   begin
			update #tempHeadCountSummaryFinal set FS_Status=18000000,PresentFS=0,AbsentFS=0
	   end
----To Load Details  Summary Report   
if(@ExportType=1)
	begin	 
		select * from #tempHeadCountSummaryFinal order by level  
	end
else
	begin
		create table #tempHeadCount (Sl int identity(1,1), levelID bigint,Dept varchar(250),[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(20),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),OrgLevel nvarchar(255),PresentFS bigint,PresentSS bigint,FS_Status int,SS_Status int
	,AbsentFS bigint,AbsentSS bigint,LeaveFS bigint,LeaveSS bigint,LOPFS bigint,LOPSS bigint,TotalEmployees bigint)
	insert into #tempHeadCount select * from #tempHeadCountSummaryFinal order by level  
	declare @couLevel int
	set @couLevel=(select COUNT(*) from #tempHeadCount)
	declare @i int
	set @i=1
	declare @SQLString1 nvarchar(Max)
	set @SQLString1=''''
	while @i<=@couLevel
		begin
			set @SQLString1 = @SQLString1 + cast((select OrgLevel from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''$'' + cast((select TotalEmployees from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +cast((select PresentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select PresentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select AbsentFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select AbsentSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select LeaveFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select LeaveSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select LOPFS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''~'' +  cast((select LOPSS from #tempHeadCount where Sl=@i) as nvarchar(Max)) + ''#''
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
	end
--To Load Shift Name in Summary Report    
if not exists (select Shift_Name + '' ('' + Shift_StartTime + '' - '' + Shift_EndTime + '')''  as ShiftName from ta_tbl_shift where shift_id=@ShiftId)
begin
select ''All Shifts'' as ShiftName
end
else
begin
select Shift_Name + '' ('' + Shift_StartTime + '' - '' + Shift_EndTime + '')''  as ShiftName from ta_tbl_shift where shift_id=@ShiftId
end
drop table #tempHeadCountSummary 
drop table #tempHeadCountSummaryFinal   
drop table #TempProcessedData
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END   
--select * from ta_tbl_processeddata where date=''06/21/2011''' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptHeadCountDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptHeadCountDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_RptHeadCountDetails] ''22-Jun-11'',''SuperAdmin'',''0'',1
CREATE PROCEDURE [dbo].[Proc_TA_RptHeadCountDetails]          
	@Date datetime,      
	@UserGroupName varchar(250),      
	@ParentId int,
	@ShiftId int,
	@EmpAutoID int 
AS    
BEGIN    
	-- SET NOCOUNT ON added to prevent extra result sets from    
	-- interfering with SELECT statements.    
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
	create table #LevelRights(LevelId int)    
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id nvarchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,HrsWork nvarchar(10),Status nvarchar(50),Attendance nvarchar(20),anAttendanceCode nvarchar(15),fnAttendanceCode nvarchar(15))  
	create table #TempHeadCountDetails(EmployeeId nvarchar(50),EmpName nvarchar(150),OrgLevel nvarchar(255),FirstSession nvarchar(20),SecondSession nvarchar(20),ShiftName nvarchar(100))  
	--#TempProcessedData Indexes  	
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId        
	--Employee Level insert in Temporary table  
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId  
	where emp.Isdeleted=0 group by EmployeeId) ELevel  
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102) and EL.LevelId is not null  
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id  
	where SwipeCardNo is not null  
	--select * from #TempEmployee  
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork,
	TA_Tbl_ProcessedData.Status,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.anAttendanceCode,TA_Tbl_ProcessedData.fnAttendanceCode   
	from TA_Tbl_ProcessedData   
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id  
	where dbo.TA_Tbl_ProcessedData.Date = CONVERT(DATETIME,cast(@Date as nvarchar(50)), 102)    
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''''    
	set @sqlQuery = ''insert into #TempHeadCountDetails select e.Employee_Code_Id as EmployeeId,isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as EmpName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as OrgLevel,''
	set @sqlQuery = @sqlQuery + ''pd.fnAttendanceCode as FirstSession,''  
	set @sqlQuery = @sqlQuery + '' pd.anAttendanceCode as SecondSession ''
	set @sqlQuery = @sqlQuery + '',shf.Shift_Name + '''' ('''' + shf.Shift_StartTime + '''' - '''' + shf.Shift_EndTime + '''')''''  as ShiftName ''  
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id''
	Set @sqlQuery = @sqlQuery + '' INNER JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id ''
	set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and pd.date = CONVERT(DATETIME, '''''' + cast(@Date as nvarchar(11)) + '''''', 102) ''    
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@ShiftId<>0)  
		begin  
			Set @sqlQuery = @sqlQuery + '' AND pd.shift_id= ''+  cast (@ShiftId as nvarchar(50))  + ''''  
		end  
	exec(@sqlQuery)  
	declare @Shift_FirstHalf_StartTime as varchar(50)
	declare @Shift_SecondHalf_StartTime as varchar(50)
	declare @FirstHalf_StartTime as varchar(50)
	declare @SecondHalf_StartTime as varchar(50)
	select @Shift_FirstHalf_StartTime=substring(Shift_FirstHalf_StartTime,7,2),@FirstHalf_StartTime=Shift_FirstHalf_StartTime,
	@Shift_SecondHalf_StartTime=substring(Shift_SecondHalf_StartTime,7,2),@SecondHalf_StartTime=Shift_SecondHalf_StartTime from ta_tbl_shift where shift_id=@ShiftId
	if(@Shift_FirstHalf_StartTime=''PM'' and @Shift_SecondHalf_StartTime=''AM'')
		begin
			set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
			set @Shift_SecondHalf_StartTime=CONVERT(varchar,dateadd(d,1,@Date) , 101) + space(1) + @SecondHalf_StartTime	
		end
	else
		begin
			set @Shift_FirstHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @FirstHalf_StartTime
			set @Shift_SecondHalf_StartTime=CONVERT(varchar,@Date, 101) + space(1) + @SecondHalf_StartTime		
		end
	if (getdate()<cast(@Shift_SecondHalf_StartTime as datetime))
		begin
			update #TempHeadCountDetails set SecondSession=''Not Started'' where SecondSession=''Absent''
		end
	if (getdate()<cast(@Shift_FirstHalf_StartTime as datetime))
		begin
			update #TempHeadCountDetails set FirstSession=''Not Started'' where FirstSession=''Absent''
		end
	select * from #TempHeadCountDetails
	--Remove the temporary tables here 
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #TempEmployee
	drop table #TempHeadCountDetails        
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_TA_RptGettingNearShiftDetailsUsingInpunch ''2017/03/01'','''','''',0,0,''superadmin'',0,0,0,''both'',0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptGettingNearShiftDetailsUsingInpunch]
	-- Add the parameters for the stored procedure here
	@FROMDAT DATETIME,	
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@SHIFT INT,	
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		CompanyId int,
		AllocatedShiftStartTime varchar(10)		
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_EMPLOYEE_CODE_ID] ON [DBO].[#TEMPPROCESSEDDATA]([DATE],[EMPLOYEE_CODE_ID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @FROMDAT,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @FROMDAT,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @FROMDAT,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@FROMDAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	''INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID '' 
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id ''
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0''
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	SET @SQLTEMPPROCESSEDDATA1=
	''INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	TE.EMPAUTOID,
			PD.DATE,
			PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			[dbo].[Func_TA_GetParentIds](TE.LEVELID),
			S.SHIFT_STARTTIME
	FROM TA_TBL_PROCESSEDDATA PD INNER JOIN #TEMPEMPLOYEE TE ON TE.EMPSWIPECARDNO=PD.EMPLOYEE_CODE_ID  	
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=PD.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (PD.DATE= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102))and intime is not null and intime<>''''00:00'''' '' 
	IF(@SHIFT<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + '' AND PD.SHIFT_ID= ''+  CAST (@SHIFT AS NVARCHAR(50))
		END
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	--select * from #TEMPPROCESSEDDATA
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		AllocatedShiftStartTime varchar(10),
		CloseShifts varchar(max),
		CompanyId int,
		Gender varchar(10),
		ClosestShiftID int,
		EmployeeAutoID bigint
	)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	E.EMPLOYEE_CODE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&''''),
	REPLACE(T.TITLENAME,''''&AMP;'''',''''&''''),
	CONVERT(VARCHAR(20),PD.DATE,101),
	PD.INTIME,PD.AllocatedShiftStartTime,
	[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,1,DATE),
	CompanyId,E.Gender,
	(select top 1 ShiftID from [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime](CompanyId,DATE+intime,1,DATE))
	,E.Employee_ID''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     	
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId ''
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)
		AND(PD.DATE = CONVERT(DATETIME, '''''' + CAST(@FROMDAT AS NVARCHAR(11)) + '''''', 102))''    
	IF(@GENDER<>''BOTH'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND E.GENDER = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' ''  
		END	
	if(@EmpAutoId > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	IF(@USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @GRADELEVEL + ''''  
		END	
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)''     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	 --Get current date time format.
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(20)
	DECLARE @TimeFormat as nvarchar(10)
	SELECT @date=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat() --TimeFormat FROM TA_Tbl_DateandTimeFormat
      IF(@date=''dd/MM/yyyy'')
            BEGIN
                  SET @dateFormat = 103
            END
      ELSE IF(@date=''MM/dd/yyyy'')
            BEGIN
                  SET @dateFormat = 101
            END
      ELSE
            BEGIN
                  SET @dateFormat = 106
            END 
	update TM set CloseShifts=
	case	when	([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)='''') or 
					([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE) is null)then 
					CloseShifts
			else CloseShifts+'';''+[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)
	end from #TEMPMONTHLYATTENDANCE TM
	select
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,
		BRANCHNAME Level,
		DESIGNATION Title,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		case when Intime<>''00:00'' then
					CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
							ELSE SUBSTRING(InTime,13,5)+'' '' + SUBSTRING(InTime,18,2)
					END
			else '''' 
		end
		ActualShiftIn,		
		case	when (@TimeFormat)=''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,AllocatedShiftStartTime,0)), 114)
				else	SUBSTRING(InTime,13,5)+'' '' + SUBSTRING(AllocatedShiftStartTime,18,2) 
		end AllocatedShift,
		CloseShifts NearestShift,Gender,CompanyId,DATE as Format,ClosestShiftID ShiftID,EmployeeAutoID
	from #TEMPMONTHLYATTENDANCE order by EMPLOYEE_ID 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*		
-- Proc_TA_RptEmployeeInOutSummary_saradhambika '''','''',0,0,0,''SuperAdmin'',''0'','''',1,''2018-10-01'',''2018-10-01'',0,''Both'',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary_saradhambika] 
	@EmployeeId nvarchar(50),
	@EmployeeName nvarchar(50),  
	@LevelID nvarchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName nvarchar(250),
	@GradeLevel nvarchar(20)	,
	@EmpSwipeCard nvarchar(20),
	@ParentId int,
	@Fromdate1 nvarchar(50),
    @Todate1 nvarchar(50),
	@DesignationID int,
	@Gender nvarchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	if(@EmployeeId is not null and @EmployeeId <> '''')
            BEGIN
                  CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
                  INSERT INTO #EmployeeID
                  SELECT * from SplitupEmployeeCode(@EmployeeId)
            end
      if(@EmployeeName is not null and @EmployeeName <> '''')
            BEGIN
                  CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
                  INSERT INTO #EmployeeName
                  SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
            end
            --select * from #EmployeeID
	Declare @Fromdate2 datetime
	set @Fromdate2 = @Fromdate1
	Declare @Count int
	declare @Diff int
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	Declare @SQL2 nvarchar(max)
	set @SQL2=''''
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	create table #TempHeader(id int,Day1 varchar(20),Day2 varchar(20),Day3 varchar(20),Day4 varchar(20),Day5 varchar(20),Day6 varchar(20),Day7 varchar(20),Day8 varchar(20),Day9 varchar(20),Day10 varchar(20),Day11 varchar(20),Day12 varchar(20),Day13 varchar(20),Day14 varchar(20),Day15 varchar(20),Day16 varchar(20),Day17 varchar(20),Day18 varchar(20),Day19 varchar(20),Day20 varchar(20),Day21 varchar(20),Day22 varchar(20),Day23 varchar(20),Day24 varchar(20),Day25 varchar(20),Day26 varchar(20),Day27 varchar(20),Day28 varchar(20),Day29 varchar(20),Day30 varchar(20),Day31 varchar(20))
	--create table #TempTotal(id int,Day1 varchar(10),Day2 varchar(10),Day3 varchar(10),Day4 varchar(10),Day5 varchar(10),Day6 varchar(10),Day7 varchar(10),Day8 varchar(10),Day9 varchar(10),Day10 varchar(10),Day11 varchar(10),Day12 varchar(10),Day13 varchar(10),Day14 varchar(10),Day15 varchar(10),Day16 varchar(10),Day17 varchar(10),Day18 varchar(10),Day19 varchar(10),Day20 varchar(10),Day21 varchar(10),Day22 varchar(10),Day23 varchar(10),Day24 varchar(10),Day25 varchar(10),Day26 varchar(10),Day27 varchar(10),Day28 varchar(10),Day29 varchar(10),Day30 varchar(10),Day31 varchar(10))
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50),FatherName nvarchar(50),Designation nvarchar(250),Employee_Code_Id nvarchar(15),Present numeric(18,1),
		Absent numeric(18,1),Leave numeric(18,1) default(0),Holiday numeric(18,1),TotalOT numeric(18,1),DesignationID int,Grade_Level int,OrderBy int,CLAvailed decimal(18,2),
		F_Day1 nvarchar(100) DEFAULT ''-'',F_Day2 nvarchar(100) DEFAULT ''-'',F_Day3 nvarchar(100) DEFAULT ''-'',F_Day4 nvarchar(100) DEFAULT ''-'',F_Day5 nvarchar(100) DEFAULT ''-'',F_Day6 nvarchar(100) DEFAULT ''-'',F_Day7 nvarchar(100) DEFAULT ''-'',F_Day8 nvarchar(100) DEFAULT ''-'',F_Day9 nvarchar(100) DEFAULT ''-'',F_Day10 nvarchar(100) DEFAULT ''-'',F_Day11 nvarchar(100) DEFAULT ''-'',F_Day12 nvarchar(100) DEFAULT ''-'',F_Day13 nvarchar(100) DEFAULT ''-'',F_Day14 nvarchar(100) DEFAULT ''-'',F_Day15 nvarchar(100) DEFAULT ''-'',F_Day16 nvarchar(100) DEFAULT ''-'',F_Day17 nvarchar(100) DEFAULT ''-'',F_Day18 nvarchar(100) DEFAULT ''-'',F_Day19 nvarchar(100) DEFAULT ''-'',F_Day20 nvarchar(100) DEFAULT ''-'',F_Day21 nvarchar(100) DEFAULT ''-'',F_Day22 nvarchar(100) DEFAULT ''-'',F_Day23 nvarchar(100) DEFAULT ''-'',F_Day24 nvarchar(100) DEFAULT ''-'',F_Day25 nvarchar(100) DEFAULT ''-'',F_Day26 nvarchar(100) DEFAULT ''-'',F_Day27 nvarchar(100) DEFAULT ''-'',F_Day28 nvarchar(100) DEFAULT ''-'',F_Day29 nvarchar(100) DEFAULT ''-'',F_Day30 nvarchar(100) DEFAULT ''-'',F_Day31 nvarchar(100) DEFAULT ''-'',
		OffDays numeric(18,1),TotalDays as Present+Absent+Leave+Holiday+OffDays		
	)
	create table #EmpInOutDetails(Employee_code_id nvarchar(15),LevelId int,date datetime,Otmins numeric(18,1),TotalDays numeric(18, 1),
	AttendanceFN nvarchar(25),AttendanceAN nvarchar(25),employee_code_id1 nvarchar(15),Designation nvarchar(250),empname nvarchar(150),
	Father_Name nvarchar(50),DesignationId int,Grade_Level int,OrderBy int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20)
	,NightOrMorn int,InNotation char(1),OutNotation char(1),DayPresent decimal(18,1) default(0),DayAbsent decimal(18,1) default(0),DayLeave decimal(18,1) default(0))	
	create table #LeaveCount(Employee_code_Id nvarchar(15),LeaveCount numeric(18,1),LeaveCountFraction nvarchar(10))
	create table #OTMins(Employee_code_Id nvarchar(15),OTMins numeric(18,1))
	create table #Holiday(Employee_code_Id nvarchar(15),NFHolidays numeric(18,1))
	create table #Leave(Employee_code_Id nvarchar(15),Leave numeric(18,1))
	create table #Present(Employee_code_Id nvarchar(15),FNPresent numeric(18,1),ANPresent numeric(18,1),Present numeric(18,1))
	create table #Absent(Employee_code_Id nvarchar(15),FNAbsent numeric(18,1),ANAbsent numeric(18,1),Absent numeric(18,1))
	create table #BonusLeave(Employee_code_Id nvarchar(15),FNBL numeric(18,1),ANBL numeric(18,1),BL numeric(18,1))
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id nvarchar(20),InTime nvarchar(25),OutTime nvarchar(25),Attendance nvarchar(20),fnattendanceCode nvarchar(20),
	anattendanceCode nvarchar(20),Shift_Id int,LevelId bigint,OtMins float,TotalDays numeric(18,1),earlyoutmins float,LateInmins float,HrsWork nvarchar(10),ShiftId int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20),NightOrMorn int,InNotation char(1),OutNotation char(1))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo nvarchar(20))
	set @Diff = datediff(d,@Fromdate1,@Todate1) +1
	set @Count=1
	insert into #TempHeader(id) values(1)
	--insert into #TempTotal(id) values(1)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@Todate1 as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End	
	Execute(@sqlEmpLevel)
		--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @ToDate1,@EmpSwipeCard,@DesignationID  
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @ToDate1,@EmpSwipeCard,@employeeType 
    INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @ToDate1,@EmpSwipeCard,@employeeCategory
	Declare @sqlTempProcess nvarchar(max)
	Declare @sqlTempProcess1 nvarchar(max)
	Declare @sqlCommonSwipeCard nvarchar(max)
	set @sqlCommonSwipeCard=''''
	select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0
	Declare @sqlTempProcessedData nvarchar(max)
	Declare @sqlTempProcessedData1 nvarchar(max)
	Declare @sqlCommonEmpId nvarchar(max)
	Declare @sqlCommon1 nvarchar(max)
      set @sqlCommon1=''''
	set @sqlTempProcessedData=		
	''insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''''''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins
		,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		inner join #InActiveDatas IA on (#EmpLevel.SwipeCard=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id ''
	set @sqlTempProcessedData=@sqlTempProcessedData+@sqlCommon1
	set @sqlTempProcessedData=@sqlTempProcessedData+'' where pd.processflag=1 and PD.Date >='''''' + @Fromdate1 + '''''' and PD.Date <= '''''' + @Todate1 + '''''' ''
		Execute(@sqlTempProcessedData)
		set @sqlTempProcessedData1=		
	'' insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''''''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,
	InNotation,OutNotation
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id  ''
	set @sqlTempProcessedData1=@sqlTempProcessedData1+@sqlCommon1
	set @sqlTempProcessedData1=@sqlTempProcessedData1+'' where pd.processflag=1 and PD.Date >='''''' + @Fromdate1 + '''''' and PD.Date <= '''''' + @Todate1 + '''''' and #EmpLevel.SwipeCard not in(select distinct swipecardno from #InActiveDatas)''
	--print(@sqlTempProcessedData1)
	Execute(@sqlTempProcessedData1)
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)=''AM'' then 1 
													--when SUBSTRING(S.Shift_StartTime,7,8)=''AM'' and SUBSTRING(S.Shift_Endtime,7,8)=''PM'' and PD.OutTime>''00:00 AM'' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	Insert into #EmpInOutDetails 
	select E.Employee_code_id,'''',date,OtMins,TotalDays,
	AttendanceFN=
	case	when FNAttendanceCode=''Present'' and (LateInmins <> ''0'') then ''*P''
			when FNAttendanceCode=''Present'' and (LateInmins = ''0'')  then ''P''
			when FNAttendanceCode=''Absent''  then ''A''
			when FNAttendanceCode=''Holiday'' and (Intime<> ''00:00'') then ''*H''
			when FNAttendanceCode=''Holiday'' and (Intime= ''00:00'' or intime is null)  then ''H''
			when FNAttendanceCode=''RH'' and (Intime<> ''00:00'') then ''*RH''
			when FNAttendanceCode=''RH'' and (Intime= ''00:00'' or intime is null) then ''RH''
			when FNAttendanceCode=''Weekly Off'' and (Intime<>''00:00'') then ''*WH'' 
			when FNAttendanceCode=''Weekly Off'' and (Intime=''00:00'' or intime is null) then ''WH'' 
			when FNAttendanceCode=''Comp Off'' then ''C''
			Else Upper(FNAttendanceCode)
	end+ case when InNotation=''M'' then ''#'' else '''' end,
	AttendanceAN= 
	case	when ANAttendanceCode=''Present'' and (earlyoutmins <> ''0'') then ''P'' 
			when ANAttendanceCode=''Present'' and (earlyoutmins = ''0'')  then ''P'' 
			when ANAttendanceCode=''Absent'' then ''A''
			when ANAttendanceCode=''Holiday'' and (OutTime<>''00:00'') then ''*H'' 
			when ANAttendanceCode=''Holiday'' and (OutTime=''00:00'' or outtime is null) then ''H'' 
			when ANAttendanceCode=''RH'' and (OutTime<>''00:00'') then ''*RH'' 
			when ANAttendanceCode=''RH'' and (OutTime=''00:00'' or outtime is null) then ''RH''
			when ANAttendanceCode=''Weekly Off'' and Outtime<> ''00:00'' then ''*WH'' 
			when ANAttendanceCode=''Weekly Off'' and (Outtime=''00:00'' or outtime is null) then ''WH''
			when ANAttendanceCode=''Comp Off'' then ''C''
			Else upper(ANAttendanceCode)
	end+ case when OutNotation=''M'' then ''#'' else '''' end,
	TPD.employee_code_id, 
	Replace(T.TitleName,''&amp;'',''&'') as Designation,
	E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'''') as empname, 
	Father_Name,
	TitleId,G.Grade_Level,0,TPD.Shift_FirstHalf_StartTime,TPD.Shift_FirstHalf_EndTime,TPD.Shift_SecondHalf_StartTime,
	TPD.Shift_SecondHalf_EndTime,TPD.NightOrMorn,InNotation,OutNotation,
	case when fnattendanceCode=''Present'' and anattendanceCode=''Present''	then 1
		 when fnattendanceCode=''Present'' and anattendanceCode!=''Present''then 0.5
		 when fnattendanceCode!=''Present''and anattendanceCode=''Present'' then 0.5
	End,
	case when fnattendanceCode=''Absent''  and anattendanceCode=''Absent''	then 1
		 when fnattendanceCode=''Absent''  and anattendanceCode!=''Absent'' then 0.5
		 when fnattendanceCode!=''Absent'' and anattendanceCode=''Absent''	then 0.5
	End,
	case when fnattendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') and anattendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') then 1
		 when fnattendanceCode in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') and anattendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') then 0.5
		 when fnattendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') and anattendanceCode in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') then 0.5
	End
	FROM  #TempProcessedData TPD INNER JOIN TA_Tbl_Employee E ON E.SwipeCardNo=TPD.Employee_Code_Id
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id    
	INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id  
	INNER JOIN TA_Tbl_Title T ON  T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID
	inner join #EmpCategory on E.Employee_Id = #EmpCategory.EmployeeId
	inner join #EmpType on E.Employee_Id = #EmpType.EmployeeId
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId
	inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId
	inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId
	where 1=1 And (E.Isdeleted=0 and E.report_exclude=0 )
	--select * from #EmpInOutDetails 
    UPDATE #EmpInOutDetails SET AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,''FN'', PD.Shift_Id, AttendanceFN),
								AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id,''AN'', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails 	
	--select * from #EmpInOutDetails order by date
	set @Count=1
	Declare @SQLFN nvarchar(max)	
	Declare @SQLFN1 nvarchar(max)	
	Declare @SQLTemp nvarchar(max)
	set @SQLFN=''''
	set @SQLFN1=''''
	set @SQLTemp=''''
	Declare @FromDate3 nvarchar(50)
	set @FromDate3=@Fromdate1
	while(@Count <=31)
		begin
			if(@Count <=@Diff)
			Begin
				set @SQLFN=''''
				set @SQLFN1=''''
				set @SQLFN = @SQLFN + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as nvarchar(10)) + '' = 
				case when AttendanceFN=''''P''''	and AttendanceAN =''''P''''		then ''''P''''
					 when AttendanceFN=''''*P''''	and AttendanceAN =''''*P''''	then ''''*P''''
					 when AttendanceFN=''''P''''	and AttendanceAN =''''*P''''	then ''''P''''
					 when AttendanceFN=''''*P''''	and AttendanceAN =''''P''''		then ''''*P''''
					 when AttendanceFN=''''P''''	and AttendanceAN !=''''P''''	then ''''HP''''
					 when AttendanceFN=''''*P''''	and AttendanceAN !=''''P''''	then ''''*HP''''
					 when AttendanceFN!=''''P''''	and AttendanceAN =''''P''''		then ''''HP''''
					 when AttendanceFN!=''''P''''	and AttendanceAN =''''*P''''	then ''''HP''''
					 when AttendanceFN=''''P#''''	and AttendanceAN !=''''P#''''	then ''''HP''''
					 when AttendanceFN=''''*P#''''	and AttendanceAN !=''''P#''''	then ''''*HP''''
					 when AttendanceFN!=''''P#''''	and AttendanceAN =''''P#''''		then ''''HP''''
					 when AttendanceFN!=''''P#''''	and AttendanceAN =''''*P#''''	then ''''HP''''
					 else AttendanceFN
				End,
				Present=isnull(Present,0)+case	when AttendanceFN=''''P''''	and AttendanceAN =''''P''''		then 1
												when AttendanceFN=''''P#''''and AttendanceAN =''''P#''''	then 1
												when AttendanceFN=''''*P''''and AttendanceAN =''''*P''''	then 1
												when AttendanceFN=''''*P#''''and AttendanceAN =''''*P#''''	then 1
												when AttendanceFN=''''P''''	and AttendanceAN =''''*P''''	then 1
												when AttendanceFN=''''P#''''and AttendanceAN =''''*P#''''	then 1
												when AttendanceFN=''''*P''''and AttendanceAN =''''P''''		then 1
												when AttendanceFN=''''*P#''''and AttendanceAN =''''P#''''	then 1
												when AttendanceFN=''''P''''	and AttendanceAN !=''''P''''	then 0.5
												when AttendanceFN=''''P#''''and AttendanceAN !=''''P#''''	then 0.5
												when AttendanceFN=''''*P''''and AttendanceAN !=''''P''''	then 0.5
												when AttendanceFN=''''*P#''''and AttendanceAN !=''''P#''''	then 0.5
												when AttendanceFN!=''''P''''and AttendanceAN =''''P''''		then 0.5
												when AttendanceFN!=''''P#''''and AttendanceAN =''''P#''''	then 0.5
												when AttendanceFN!=''''P''''and AttendanceAN =''''*P''''	then 0.5
												when AttendanceFN!=''''P#''''and AttendanceAN =''''*P#''''	then 0.5
												else 0
										 End,
				Absent=isnull(Absent,0)+case	when AttendanceFN=''''A'''' and AttendanceAN =''''A'''' then 1
												when AttendanceFN=''''A#'''' and AttendanceAN =''''A#'''' then 1
												when (AttendanceFN=''''A'''' and AttendanceAN !=''''A'''') or (AttendanceFN!=''''A'''' and AttendanceAN =''''A'''') then 0.5
												when (AttendanceFN=''''A#'''' and AttendanceAN !=''''A#'''') or (AttendanceFN!=''''A#'''' and AttendanceAN =''''A#'''') then 0.5
												else 0
										  END,''
				set @SQLFN1 = @SQLFN1 + '' OffDays=isnull(OffDays,0)+case	when AttendanceFN=''''WH'''' and AttendanceAN =''''WH'''' then 1
												when AttendanceFN=''''*WH'''' and AttendanceAN =''''*WH'''' then 1
												when AttendanceFN=''''*WH#'''' and AttendanceAN =''''*WH#'''' then 1
												else 0
										  END,
				Holiday=isnull(Holiday,0)+case	when AttendanceFN=''''H'''' and AttendanceAN =''''H'''' then 1
												when AttendanceFN=''''H#'''' and AttendanceAN =''''H#'''' then 1
												when AttendanceFN=''''RH'''' and AttendanceAN =''''RH'''' then 1
												when AttendanceFN=''''RH#'''' and AttendanceAN =''''RH#'''' then 1
												when AttendanceFN=''''*H'''' and AttendanceAN =''''*H'''' then 1
												when AttendanceFN=''''*H#'''' and AttendanceAN =''''*H#'''' then 1
												when AttendanceFN=''''*RH'''' and AttendanceAN =''''*RH'''' then 1
												when AttendanceFN=''''*RH#'''' and AttendanceAN =''''*RH#'''' then 1
												else 0
										  END,
				Leave=isnull(Leave,0)+case	when AttendanceFN not in(''''P'''',''''*P'''',''''P#'''',''''*P#'''',''''A'''',''''WH'''',''''*WH'''',''''*WH#'''',''''H'''',''''H#'''',''''RH#'''',''''RH'''',''''*H'''',''''*H#'''',''''*RH'''',''''*RH#'''') and AttendanceAN not in(''''P'''',''''*P'''',''''P#'''',''''*P#'''',''''A'''',''''WH'''',''''*WH'''',''''*WH#'''',''''H'''',''''H#'''',''''RH'''',''''RH#'''',''''*H'''',''''*RH'''',''''*H#'''',''''*RH#'''') then 1
											when AttendanceFN in(''''P'''',''''*P'''',''''A'''',''''WH'''',''''*WH'''',''''H'''',''''RH'''',''''*H'''',''''*RH'''') and AttendanceAN not in(''''P'''',''''*P'''',''''A'''',''''WH'''',''''*WH'''',''''H'''',''''RH'''',''''*H'''',''''*RH'''') then 0.5
											when AttendanceFN not in(''''P'''',''''*P'''',''''A'''',''''WH'''',''''*WH'''',''''H'''',''''RH'''',''''*H'''',''''*RH'''') and AttendanceAN in(''''P'''',''''*P'''',''''A'''',''''WH'''',''''*WH'''',''''H'''',''''RH'''',''''*H'''',''''*RH'''') then 0.5
											when AttendanceFN=''''*RH'''' and AttendanceAN =''''*RH'''' then 1
											else 0
										  END
				from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	
				#EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date =   CONVERT(DATETIME, '''''' + @Fromdate1 + '''''' , 102)''
				exec(@SQLFN+@SQLFN1)				
			End
			set @SQLTemp=''''
			set @SQLTemp = @SQLTemp + '' update #TempHeader set Day''+cast(@Count as nvarchar(10)) + ''=(select ''''''+cast(@Count as nvarchar(10)) + ''''''+''''#''''+isnull(convert(varchar,SUM(isnull(DayPresent,0))),'''''''')+''''#''''+isnull(convert(varchar,SUM(isnull(DayAbsent,0))),'''''''')+''''#''''+
										isnull(convert(varchar,SUM(isnull(DayLeave,0))),'''''''')
				from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	
				#EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date =   CONVERT(DATETIME, '''''' + @Fromdate1 + '''''' , 102))''
			print(@SQLTemp)
			exec(@SQLTemp)
			set @Fromdate1=dateadd(d,1,@Fromdate1)
			set @Count=@Count +1
		end	
	select SlNo=ROW_NUMBER()over(order by Employee_Code_Id), Employee_Code_Id,Name,Designation,
		   F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
		   Present,Absent,Leave,Holiday,OffDays
		   --,TotalDays
	from #AllEmpInOutDetails A
	--select *from #TempTotal
	select * from #TempHeader
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpGrade
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #LeaveCount
	drop table #OTMins
	drop table #Holiday
	drop table #Leave
	drop table #Present
	drop table #Absent
	drop table #BonusLeave
	drop table #TempProcessedData
END
' 
END

GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptEmployeeInOutSummary]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptEmployeeInOutSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*	
exec Proc_TA_RptEmployeeInOutSummary @EmployeeId=''787'',@EmployeeName='''',@LevelID=''0,1'',@employeeCategory=N''0'',@employeeType=N''0'',
@UserGroupName=''superadmin'',@GradeLevel=''1'',@EmpSwipeCard='''',@ParentId=0,@Fromdate1=''2019/01/01'',@Todate1=''2019/01/31'',@DesignationID=0,@Gender=''Both'',@EmpAutoID=1
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptEmployeeInOutSummary] 
	@EmployeeId nvarchar(50),
	@EmployeeName nvarchar(50),  
	@LevelID nvarchar(1000), 	 
	@employeeCategory nvarchar(50),
	@employeeType nvarchar(50)	,
	@UserGroupName nvarchar(250),
	@GradeLevel nvarchar(20)	,
	@EmpSwipeCard nvarchar(20),
	@ParentId int,
	@Fromdate1 nvarchar(50),
    @Todate1 nvarchar(50),
	@DesignationID int,
	@Gender nvarchar(10),
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @loca_EmployeeId nvarchar(50)
	DECLARE @loca_EmployeeName nvarchar(50)
	DECLARE @loca_LevelID nvarchar(1000)
	DECLARE @loca_employeeCategory nvarchar(50)
	DECLARE @loca_employeeType nvarchar(50)
	DECLARE @loca_UserGroupName nvarchar(250)
	DECLARE @loca_GradeLevel nvarchar(20)
	DECLARE @loca_EmpSwipeCard nvarchar(20)
	DECLARE @loca_ParentId int
	DECLARE @loca_Fromdate1 nvarchar(50)
    DECLARE @loca_Todate1 nvarchar(50)
	DECLARE @loca_DesignationID int
	DECLARE @loca_Gender nvarchar(10)
	DECLARE @loca_EmpAutoID int
	
	set @loca_EmployeeId=@EmployeeId
	set @loca_EmployeeName=@EmployeeName
	set @loca_LevelID=@LevelID
	set @loca_employeeCategory=@employeeCategory
	set @loca_employeeType=@employeeType
	set @loca_UserGroupName=@UserGroupName
	set @loca_GradeLevel=@GradeLevel
	set @loca_EmpSwipeCard=@EmpSwipeCard
	set @loca_ParentId=@ParentId
	set @loca_Fromdate1=@Fromdate1
	set @loca_Todate1=@Todate1
	set @loca_DesignationID=@DesignationID
	set @loca_Gender=@Gender
	set @loca_EmpAutoID=@EmpAutoID	
	
	if(@loca_EmployeeId is not null and @loca_EmployeeId <> '''')
        BEGIN
              CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
              INSERT INTO #EmployeeID
              SELECT * from SplitupEmployeeCode(@loca_EmployeeId)
        end
	if(@loca_EmployeeName is not null and @loca_EmployeeName <> '''')
		BEGIN
			  CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			  INSERT INTO #EmployeeName
			  SELECT [Value] from dbo.[SplitUpEmployeeName](@loca_EmployeeName,'','')
		end
            
	Declare @Fromdate2 datetime
	set @Fromdate2 = @loca_Fromdate1
	Declare @Count int
	declare @Diff int
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	declare @sqlQuery2 as nvarchar(max)
	Declare @SQL2 nvarchar(max)
	set @SQL2=''''
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@loca_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@loca_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@loca_EmpAutoID) as EmpAutoId
	create table #EmpGrade(Grade_Id int)
	create table #LevelRights(LevelId int)
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	create table #AllEmpInOutDetails
	(
		Name nvarchar(50),FatherName nvarchar(50),Designation nvarchar(250),Employee_Code_Id nvarchar(15),Present numeric(18,1),
		Absent numeric(18,1),Leave nvarchar(10) default(0),Holiday numeric(18,1),TotalOT numeric(18,1),DesignationID int,Grade_Level int,OrderBy int,CLAvailed decimal(18,2) default(0),
		F_Day1 nvarchar(100) DEFAULT ''-'',F_Day2 nvarchar(100) DEFAULT ''-'',F_Day3 nvarchar(100) DEFAULT ''-'',F_Day4 nvarchar(100) DEFAULT ''-'',F_Day5 nvarchar(100) DEFAULT ''-'',F_Day6 nvarchar(100) DEFAULT ''-'',F_Day7 nvarchar(100) DEFAULT ''-'',F_Day8 nvarchar(100) DEFAULT ''-'',F_Day9 nvarchar(100) DEFAULT ''-'',F_Day10 nvarchar(100) DEFAULT ''-'',F_Day11 nvarchar(100) DEFAULT ''-'',F_Day12 nvarchar(100) DEFAULT ''-'',F_Day13 nvarchar(100) DEFAULT ''-'',F_Day14 nvarchar(100) DEFAULT ''-'',F_Day15 nvarchar(100) DEFAULT ''-'',F_Day16 nvarchar(100) DEFAULT ''-'',F_Day17 nvarchar(100) DEFAULT ''-'',F_Day18 nvarchar(100) DEFAULT ''-'',F_Day19 nvarchar(100) DEFAULT ''-'',F_Day20 nvarchar(100) DEFAULT ''-'',F_Day21 nvarchar(100) DEFAULT ''-'',F_Day22 nvarchar(100) DEFAULT ''-'',F_Day23 nvarchar(100) DEFAULT ''-'',F_Day24 nvarchar(100) DEFAULT ''-'',F_Day25 nvarchar(100) DEFAULT ''-'',F_Day26 nvarchar(100) DEFAULT ''-'',F_Day27 nvarchar(100) DEFAULT ''-'',F_Day28 nvarchar(100) DEFAULT ''-'',F_Day29 nvarchar(100) DEFAULT ''-'',F_Day30 nvarchar(100) DEFAULT ''-'',F_Day31 nvarchar(100) DEFAULT ''-'',
	    A_Day1 nvarchar(100) DEFAULT ''-'',A_Day2 nvarchar(100) DEFAULT ''-'',A_Day3 nvarchar(100) DEFAULT ''-'',A_Day4 nvarchar(100) DEFAULT ''-'',A_Day5 nvarchar(100) DEFAULT ''-'',A_Day6 nvarchar(100) DEFAULT ''-'',A_Day7 nvarchar(100) DEFAULT ''-'',A_Day8 nvarchar(100) DEFAULT ''-'',A_Day9 nvarchar(100) DEFAULT ''-'',A_Day10 nvarchar(100) DEFAULT ''-'',A_Day11 nvarchar(100) DEFAULT ''-'',A_Day12 nvarchar(100) DEFAULT ''-'',A_Day13 nvarchar(100) DEFAULT ''-'',A_Day14 nvarchar(100) DEFAULT ''-'',A_Day15 nvarchar(100) DEFAULT ''-'',A_Day16 nvarchar(100) DEFAULT ''-'',A_Day17 nvarchar(100) DEFAULT ''-'',A_Day18 nvarchar(100) DEFAULT ''-'',A_Day19 nvarchar(100) DEFAULT ''-'',A_Day20 nvarchar(100) DEFAULT ''-'',A_Day21 nvarchar(100) DEFAULT ''-'',A_Day22 nvarchar(100) DEFAULT ''-'',A_Day23 nvarchar(100) DEFAULT ''-'',A_Day24 nvarchar(100) DEFAULT ''-'',A_Day25 nvarchar(100) DEFAULT ''-'',A_Day26 nvarchar(100) DEFAULT ''-'',A_Day27 nvarchar(100) DEFAULT ''-'',A_Day28 nvarchar(100) DEFAULT ''-'',A_Day29 nvarchar(100) DEFAULT ''-'',A_Day30 nvarchar(100) DEFAULT ''-'',A_Day31 nvarchar(100) DEFAULT ''-'',	
	)
	create table #EmpInOutDetails(Employee_code_id nvarchar(15),LevelId int,date datetime,Otmins numeric(18,1),TotalDays numeric(18, 1),
	AttendanceFN nvarchar(25),AttendanceAN nvarchar(25),employee_code_id1 nvarchar(15),Designation nvarchar(250),empname nvarchar(150),
	Father_Name nvarchar(50),DesignationId int,Grade_Level int,OrderBy int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20)
	,NightOrMorn int,InNotation char(1),OutNotation char(1))	
	
	
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id nvarchar(20),InTime nvarchar(25),OutTime nvarchar(25),Attendance nvarchar(20),fnattendanceCode nvarchar(20),
	anattendanceCode nvarchar(20),Shift_Id int,LevelId bigint,OtMins float,TotalDays numeric(18,1),earlyoutmins float,LateInmins float,HrsWork nvarchar(10),ShiftId int,Shift_FirstHalf_StartTime nvarchar(20),Shift_FirstHalf_EndTime nvarchar(20),Shift_SecondHalf_StartTime nvarchar(20),Shift_SecondHalf_EndTime nvarchar(20),NightOrMorn int,InNotation char(1),OutNotation char(1))
	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo nvarchar(20))
	
	set @Diff = datediff(d,@loca_Fromdate1,@loca_Todate1) +1
	set @Count=1
	insert into #TempHeader(id) values(1)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@loca_UserGroupName,@loca_ParentId) as LevelId
	--Employee Grade Indexes
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@loca_GradeLevel
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@loca_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@loca_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@loca_Todate1 as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@loca_EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@loca_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End	
	Execute(@sqlEmpLevel)
		--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @loca_Todate1,@loca_EmployeeId,@loca_DesignationID 
	
	if(@loca_employeeType!=0)
	begin 
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))	
		INSERT INTO #EmpType exec [Proc_TA_EmpType] @loca_Todate1,@loca_EmployeeId,@loca_employeeType 
	end
	if(@loca_employeeCategory!=0)
	BEGIN
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
		INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @loca_Todate1,@loca_EmployeeId,@loca_employeeCategory
	END
	Declare @sqlTempProcess nvarchar(max)
	Declare @sqlTempProcess1 nvarchar(max)
	Declare @sqlCommonSwipeCard nvarchar(max)
	Declare @sqlTempProcessedData nvarchar(max)
	Declare @sqlTempProcessedData1 nvarchar(max)
	Declare @sqlCommonEmpId nvarchar(max)
	Declare @sqlCommon1 nvarchar(max)
	set @sqlCommon1=''''
	set @sqlCommonSwipeCard=''''
	select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0
      
	set @sqlTempProcessedData=		
	''insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''''''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins
		,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,InNotation,OutNotation 
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		inner join #InActiveDatas IA on (#EmpLevel.SwipeCard=IA.SwipeCardNo and pd.Date<=IA.inactivedate)
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id ''
	set @sqlTempProcessedData=@sqlTempProcessedData+@sqlCommon1
	set @sqlTempProcessedData=@sqlTempProcessedData+'' where PD.Date >='''''' + @loca_Fromdate1 + '''''' and PD.Date <= '''''' + @loca_Todate1 + '''''' ''
	Execute(@sqlTempProcessedData)
	
	set @sqlTempProcessedData1=		
	'' insert into #TempProcessedData
		select #EmpLevel.EmployeeId,pd.Date,pd.Employee_Code_Id,pd.InTime,pd.OutTime,pd.Attendance,pd.fnattendanceCode,pd.anattendanceCode,pd.Shift_Id,'''''''',
		pd.OtMins,pd.TotalDays,pd.earlyoutmins,pd.LateInmins,pd.HrsWork,pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,0,
	InNotation,OutNotation
		from TA_Tbl_ProcessedData PD
		inner join #EmpLevel on #EmpLevel.SwipeCard=PD.Employee_Code_Id 
		Left Outer join TA_Tbl_Shift S on S.Shift_Id=PD.Shift_Id ''
	set @sqlTempProcessedData1=@sqlTempProcessedData1+@sqlCommon1
	set @sqlTempProcessedData1=@sqlTempProcessedData1+'' where PD.Date >='''''' + @loca_Fromdate1 + '''''' and PD.Date <= '''''' + @loca_Todate1 + '''''' and #EmpLevel.SwipeCard not in(select distinct swipecardno from #InActiveDatas)''
	Execute(@sqlTempProcessedData1)
	
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)!=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)!=''AM'' then 0 
													else 1 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.Shift_Id=S.Shift_Id
	
	set @sqlQuery =''''
	set @sqlQuery1 =''''
	set @sqlQuery2=''''
	set @sqlQuery =''Insert into #EmpInOutDetails 
	select	TA_Tbl_Employee.Employee_code_id,
			'''''''',
			TPD.date, 
			TPD.OtMins, 
			TPD.TotalDays,
			AttendanceFN=	case when TPD.FNAttendanceCode not in(''''Absent'''',''''Present'''',''''Weekly Off'''',''''Comp Off'''',''''Holiday'''',''''RH'''',''''CL'''',''''EL'''') then '''''''' + lower(FNAttendanceCode) + ''''''''
								when TPD.FNAttendanceCode=''''Absent'''' then ''''A''''
								when TPD.FNAttendanceCode=''''Present'''' then case	when (TPD.LateInmins <> ''''0'''' ) then ''''*P''''
																				else ''''P'''' 
																			end
								when TPD.FNAttendanceCode=''''Weekly Off'''' then case when (InTime is not null and Intime<> ''''00:00'''')then ''''**o'''' else ''''Off'''' end 																
								when TPD.FNAttendanceCode=''''Comp Off'''' then ''''C''''
								when TPD.FNAttendanceCode=''''Holiday'''' then case	when (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''**H''''
															else ''''H'''' 
													  end
								when TPD.FNAttendanceCode=''''RH'''' then case	when (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''**R''''
														else ''''RH'''' 
												 end
								when TPD.FNAttendanceCode=''''CL'''' then ''''CL''''
								when TPD.FNAttendanceCode=''''EL'''' then ''''EL''''
							end,
			AttendanceAN = case when TPD.ANAttendanceCode not in(''''Absent'''',''''Present'''',''''Weekly Off'''',''''Comp Off'''',''''Holiday'''',''''RH'''',''''CL'''',''''EL'''') then '''''''' + lower(ANAttendanceCode) + ''''''''
								when TPD.ANAttendanceCode=''''Absent'''' then ''''A''''
								when TPD.ANAttendanceCode=''''Present''''  then case when (TPD.earlyoutmins <> ''''0'''' ) then ''''*P'''' 
																				else ''''P'''' 
																			end
								when TPD.ANAttendanceCode=''''Weekly Off'''' then case when (Outtime is not null and Outtime<> ''''00:00'''') then ''''**o'''' else ''''Off'''' end
								when TPD.ANAttendanceCode=''''Comp Off'''' then ''''C''''
								when TPD.ANAttendanceCode=''''Holiday'''' then case	when (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''**H'''' 
															else ''''H'''' 
													  end
								when TPD.ANAttendanceCode=''''RH'''' then case	when (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''**R'''' 
														else ''''RH'''' 
												 end
								when TPD.ANAttendanceCode=''''CL'''' then ''''CL''''
								when TPD.ANAttendanceCode=''''EL'''' then ''''EL''''
							end,
			TPD.employee_code_id, 
			Replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as Designation,
			TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.employee_lastname,'''''''') as empname, 
			ta_tbl_employee.Father_Name,
			TA_Tbl_Title.TitleId,
			TA_Tbl_Grade.Grade_Level,
			0,
			TPD.Shift_FirstHalf_StartTime,
			TPD.Shift_FirstHalf_EndTime,
			TPD.Shift_SecondHalf_StartTime,
			TPD.Shift_SecondHalf_EndTime,
			TPD.NightOrMorn,
			InNotation,
			OutNotation
	FROM  dbo.#TempProcessedData TPD INNER JOIN dbo.TA_Tbl_Employee ON dbo.TA_Tbl_Employee.SwipeCardNo=TPD.Employee_Code_Id ''
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_LevelDetails L ON  #EmpLevel.LevelId = L.Id ''    
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= TA_Tbl_Employee.Employee_Id ''  
	Set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Title ON  TA_Tbl_Title.TitleId=EDesig.DesignationId ''  
	SET @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''  
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''	
	if(@loca_employeeCategory!=0)
	begin
		set @sqlQuery1 = @sqlQuery1 + '' inner join #EmpCategory tec on TA_Tbl_Employee.Employee_Id = tec.EmployeeId''
		set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_Category c on tec.CategoryId = c.CategoryId''
	end
	if(@loca_employeeType!=0)
	begin
		set @sqlQuery1 = @sqlQuery1 + '' inner join #EmpType tet on TA_Tbl_Employee.Employee_Id = tet.EmployeeId''  	
		set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_Type on tet.TypeId = TA_Tbl_Type.TypeId''	
	end
	set @sqlQuery1 = @sqlQuery1 + '' where 1=1 And (ta_tbl_employee.Isdeleted=0 and ta_tbl_employee.report_exclude=0 )''
	If Not (@loca_EmpSwipeCard = '''')  
		Begin  
			Set @sqlQuery2 = @sqlQuery2 + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @loca_EmpSwipeCard + '''''' ''  
		End 
	if(@loca_Gender<>''Both'')
	begin
		set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_Employee.Gender = '''''' + cast(@loca_Gender as nvarchar(8)) + '''''' ''
	end
	if(@isReportingto > 0)
        BEGIN
           set @sqlQuery2 = @sqlQuery2 + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
        END
	Exec(@sqlQuery+@sqlQuery1+@sqlQuery2) 
	--select * from #EmpInOutDetails 
    UPDATE #EmpInOutDetails SET
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id,  ''FN'', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, ''AN'', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD
	INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
    
    UPDATE #EmpInOutDetails SET 
		AttendanceFN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.FNAttendanceCode, PD.Employee_Code_Id, ''FN'', PD.Shift_Id, AttendanceFN),
		AttendanceAN = [dbo].Func_TA_MusterRoll_OD_Notation(PD.[Date], PD.ANAttendanceCode, PD.Employee_Code_Id, ''AN'', PD.Shift_Id, AttendanceAN)
	FROM #EmpInOutDetails IOD INNER JOIN TA_Tbl_ProcessedData PD ON IOD.Employee_code_id = PD.Employee_Code_Id AND PD.[Date] = IOD.[date]
	WHERE PD.ProcessFlag = 1
	
    update #EmpInOutDetails set AttendanceFN= case	WHEN  I.AttendanceFN = ''A'' THEN I.AttendanceFN
													When (I.AttendanceFN =''P'' OR I.AttendanceFN =''*P'' OR I.AttendanceFN =''H'' OR I.AttendanceFN =''**H'' OR I.AttendanceFN =''Off'' OR I.AttendanceFN =''**O'') and InNotation=''M'' then AttendanceFN+''#'' 
													else AttendanceFN 
											  end,
	AttendanceAN= 
	    case	WHEN  I.AttendanceAN = ''A'' THEN I.AttendanceAN
				WHEN (I.AttendanceAN=''P'' OR I.AttendanceAN=''*P'' OR I.AttendanceAN=''H'' OR I.AttendanceAN=''**H'' OR I.AttendanceAN=''Off'' OR I.AttendanceAN=''**O'') and OutNotation=''M'' then AttendanceAN+''#'' else AttendanceAN end
	from #EmpInOutDetails I where (InNotation=''M'' or OutNotation=''M'')
	
	insert into #AllEmpInOutDetails (Employee_Code_Id,Name,Designation,FatherName,DesignationID,Grade_Level,OrderBy)
	select distinct Employee_code_id,empname,Designation,Father_Name,DesignationID,Grade_Level,OrderBy from #EmpInOutDetails 
	
	declare @LeaveTypeID int
	select @LeaveTypeID =LeaveType_Id from TA_tbl_LeaveType where LeaveType=''CL''
	
	--Inserts the Leave Count of employee in the temporary table
	if(@LeaveTypeID<>'''')
	begin
		create table #LeaveCount(Employee_code_Id nvarchar(15),LeaveCount numeric(18,1),LeaveCountFraction nvarchar(10))
		
		insert into #LeaveCount 
		select e.employee_code_id,isnull(sum(convert(decimal(18,1),NumberOfDays)),0) as LeaveCount,'''' as LeaveCountFraction 
		from ta_tbl_leaveapplication la inner join ta_tbl_employee e on e.Employee_Id = la.Employee_Id
		where ((la.Leave_FromDate between @loca_Fromdate1 and @loca_Todate1)or (la.Leave_ToDate between @loca_Fromdate1 and @loca_Todate1))
		and la.Status = ''Approved'' and la.LeaveType_Id=@LeaveTypeID and la.IsDeleted=0 	
		group by e.employee_code_id
		
		update #LeaveCount set LeaveCountFraction=isnull(LeaveCount,0)- Floor(isnull(LeaveCount,0))	
		update #LeaveCount set LeaveCountFraction=ltrim(cast((case cast(Floor(LeaveCount) as nvarchar(10)) when ''0'' then '''' else cast(Floor(LeaveCount) as nvarchar(10)) end) as nvarchar(10)) + '' '' +
				case LeaveCountFraction when ''0.5'' then ''1/2'' else ''''end )	
		update #AllEmpInOutDetails set Leave =isnull(#LeaveCount.LeaveCountFraction,0) from #LeaveCount
		inner join #AllEmpInOutDetails on #LeaveCount.Employee_code_Id = #AllEmpInOutDetails.Employee_Code_Id
	end
	
	set @Count=1
	Declare @SQLFN nvarchar(max)
	set @SQLFN=''''
	Declare @SQLAN1 nvarchar(max)
	set @SQLAN1=''''
	Declare @SQLTemp nvarchar(max)
	set @SQLTemp=''''
	Declare @FromDate3 nvarchar(50)
	set @FromDate3=@loca_Fromdate1
	while(@Count <=31)
		begin
			if(@Count <=@Diff)
			Begin
			set @SQLFN = @SQLFN + '' update #AllEmpInOutDetails set F_Day''+ cast(@Count as nvarchar(10)) + '' = #EmpInOutDetails.AttendanceFN,A_Day''+ cast(@Count as nvarchar(10)) + '' = #EmpInOutDetails.AttendanceAN''
			set @SQLFN = @SQLFN + '' from  #EmpInOutDetails inner join #AllEmpInOutDetails on #AllEmpInOutDetails.Employee_code_id=	''
			set @SQLFN = @SQLFN + ''	#EmpInOutDetails.Employee_code_id and #EmpInOutDetails.date =   CONVERT(DATETIME, '''''' + @loca_Fromdate1 + '''''' , 102)''
			exec(@SQLFN)
			set @SQLFN=''''
			End
			set @SQLTemp = @SQLTemp + '' update #TempHeader set Day''+cast(@Count as nvarchar(10)) + ''='' + cast(datepart(d,@loca_Fromdate1)as nvarchar(10)) + ''where id=1''	
			exec(@SQLTemp)
			set @SQLTemp=''''
			set @loca_Fromdate1=dateadd(d,1,@loca_Fromdate1)
			set @Count=@Count +1
		end
    --for CLAvailed 
	update #AllEmpInOutDetails set  CLAvailed= isnull(A.LeaveAvailed,''0.0'')
	from #AllEmpInOutDetails TDA inner join 
	(
			select (sum(CASE fnattendanceCode When ''CL'' then 0.5 Else 0 END) + sum(CASE anattendanceCode When ''CL'' Then 0.5 Else 0 END)) as LeaveAvailed,
					PD.Employee_Code_Id 
			from TA_tbl_ProcessedData pd inner join TA_tbl_YearSetting on TA_tbl_YearSetting.ISActive=1
			Inner join #AllEmpInOutDetails TA on TA.Employee_Code_Id=pd.Employee_Code_Id
			where (Date between TA_tbl_YearSetting.FromDate and @loca_Todate1) and (FNAttendanceCode=''CL'' or ANAttendanceCode=''CL'')
			group by pd.Employee_Code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	
	--update #AllEmpInOutDetails set CLAvailed=''0.0'' where isnull(CLAvailed,0)=0
	
	select	
			Employee_Code_Id,
			Name,
			Designation,			
			CLAvailed,
			F_Day1,F_Day2,F_Day3,F_Day4,F_Day5,F_Day6,F_Day7,F_Day8,F_Day9,F_Day10,F_Day11,F_Day12,F_Day13,F_Day14,F_Day15,
			F_Day16,F_Day17,F_Day18,F_Day19,F_Day20,F_Day21,F_Day22,F_Day23,F_Day24,F_Day25,F_Day26,F_Day27,F_Day28,F_Day29,F_Day30,F_Day31,
			A_Day1,A_Day2,A_Day3,A_Day4,A_Day5,A_Day6,A_Day7,A_Day8,A_Day9,A_Day10,A_Day11,A_Day12,A_Day13,A_Day14,A_Day15,
			A_Day16,A_Day17,A_Day18,A_Day19,A_Day20,A_Day21,A_Day22,A_Day23,A_Day24,A_Day25,A_Day26,A_Day27,A_Day28,A_Day29,A_Day30,A_Day31,
			AFDay1=replace(F_Day1,''#'','''')+'' / ''+replace(A_Day1,''#'',''''),
			AFDay2=replace(F_Day2,''#'','''')+'' / ''+replace(A_Day2,''#'',''''),
			AFDay3=replace(F_Day3,''#'','''')+'' / ''+replace(A_Day3,''#'',''''),
			AFDay4=replace(F_Day4,''#'','''')+'' / ''+replace(A_Day4,''#'',''''),
			AFDay5=replace(F_Day5,''#'','''')+'' / ''+replace(A_Day5,''#'',''''),
			AFDay6=replace(F_Day6,''#'','''')+'' / ''+replace(A_Day6,''#'',''''),
			AFDay7=replace(F_Day7,''#'','''')+'' / ''+replace(A_Day7,''#'',''''),
			AFDay8=replace(F_Day8,''#'','''')+'' / ''+replace(A_Day8,''#'',''''),
			AFDay9=replace(F_Day9,''#'','''')+'' / ''+replace(A_Day9,''#'',''''),
			AFDay10=replace(F_Day10,''#'','''')+'' / ''+replace(A_Day10,''#'',''''),
			AFDay11=replace(F_Day11,''#'','''')+'' / ''+replace(A_Day11,''#'',''''),
			AFDay12=replace(F_Day12,''#'','''')+'' / ''+replace(A_Day12,''#'',''''),
			AFDay13=replace(F_Day13,''#'','''')+'' / ''+replace(A_Day13,''#'',''''),
			AFDay14=replace(F_Day14,''#'','''')+'' / ''+replace(A_Day14,''#'',''''),
			AFDay15=replace(F_Day15,''#'','''')+'' / ''+replace(A_Day15,''#'',''''),
			AFDay16=replace(F_Day16,''#'','''')+'' / ''+replace(A_Day16,''#'',''''),
			AFDay17=replace(F_Day17,''#'','''')+'' / ''+replace(A_Day17,''#'',''''),
			AFDay18=replace(F_Day18,''#'','''')+'' / ''+replace(A_Day18,''#'',''''),
			AFDay19=replace(F_Day19,''#'','''')+'' / ''+replace(A_Day19,''#'',''''),
			AFDay20=replace(F_Day20,''#'','''')+'' / ''+replace(A_Day20,''#'',''''),
			AFDay21=replace(F_Day21,''#'','''')+'' / ''+replace(A_Day21,''#'',''''),
			AFDay22=replace(F_Day22,''#'','''')+'' / ''+replace(A_Day22,''#'',''''),
			AFDay23=replace(F_Day23,''#'','''')+'' / ''+replace(A_Day23,''#'',''''),
			AFDay24=replace(F_Day24,''#'','''')+'' / ''+replace(A_Day24,''#'',''''),
			AFDay25=replace(F_Day25,''#'','''')+'' / ''+replace(A_Day25,''#'',''''),
			AFDay26=replace(F_Day26,''#'','''')+'' / ''+replace(A_Day26,''#'',''''),
			AFDay27=replace(F_Day27,''#'','''')+'' / ''+replace(A_Day27,''#'',''''),
			AFDay28=replace(F_Day28,''#'','''')+'' / ''+replace(A_Day28,''#'',''''),
			AFDay29=replace(F_Day29,''#'','''')+'' / ''+replace(A_Day29,''#'',''''),
			AFDay30=replace(F_Day30,''#'','''')+'' / ''+replace(A_Day30,''#'',''''),
			AFDay31=replace(F_Day31,''#'','''')+'' / ''+replace(A_Day31,''#'',''''),
			FatherName,Present,Absent,Leave,Holiday,TotalOT,DesignationID,Grade_Level,OrderBy
	from #AllEmpInOutDetails A order by A.Grade_Level,cast(isnull(A.Orderby,100000)as int),Name
	
	select * from #TempHeader
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpGrade
	drop table #EmpInOutDetails
	drop table #AllEmpInOutDetails
	drop table #TempProcessedData
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptGeneralMonthlyAttendance]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptGeneralMonthlyAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Proc_TA_RptGeneralMonthlyAttendance ''787'',''2020/06/01'',''2020/07/01'','''',''0'',0,0,''superadmin'',''0'',0,0,''Both'',0,0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptGeneralMonthlyAttendance]
(   
	@EmployeeId varchar(max),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),	
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@ShiftId int,
	@EmpAutoID int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@fromDat
	set @local_ToDate=@ToDat
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@ShiftId
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_EmpAutoId=@EmpAutoId
	
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),
		HrsWork nvarchar(10),LateInmin nvarchar(10),EarlyOutMin nvarchar(10),
		Inpunch varchar(20),Outpunch varchar(20),Indate datetime,Outdate datetime,
		Excess varchar(10),Remarks nvarchar(max)
		,FNAttendanceCode nvarchar(30),ANAttendanceCode nvarchar(30),ExcessMins varchar(10),HrsLess varchar(10),
		BreakHours int default(0),LunchHours int default(0),BreakHoursMins int,LunchHoursMins int,isNightShift bit default(0),
		ShftShrtName varchar(100)
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId  
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	if(@local_Gender<>''Both'')  
		begin  
			set @sqlCommon = @sqlCommon + '' and Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''  
		end	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 ''
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@local_EmployeeID = '''')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
			End
	If Not (@local_EmployeeName = '''')  
			BEGIN  
				SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
			End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_ToDate,@local_EmployeeID,@local_DesignationID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_ToDate,@local_EmployeeID,@local_employeeType
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	Declare @sqlTempProcessedData1 varchar(max)
	insert into #TempProcessedData 
	select	EmployeeId,
			P.Date,
			P.Employee_Code_Id,
			P.InTime,
			P.OutTime,
			P.HrsWork,
			LateInMins,
			case when charindex(''.'',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex(''.'',convert(varchar(20),EarlyOutmins))))
				 else EarlyOutmins 
			end,
			Inpunch,
			Outpunch,
			Indate,
			Outdate,
			HrsExtra,'''',
			FNAttendanceCode,
			ANAttendanceCode,
			ExtraMins,
			HrsLess,
			isnull(BreakHrsInmins,0),
			isnull(LunchHrsInmins,0),
			BreakHrsInmins,
			LunchHrsInmins,
			case	when SUBSTRING(S.Shift_StartTime,7,8)=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)=''AM'' then 1 			
					else 0 
			end,
			case when P.Shift_Id!=-1 then S.Shift_Shortname+'' (''+S.Shift_StartTime+''-''+S.Shift_EndTime+'')''
			else ''-''
			end
	from TA_Tbl_ProcessedData P inner join 
	#EmpLevel on #EmpLevel.SwipeCard=P.Employee_Code_Id  
	left outer join ta_tbl_shift S on S.Shift_Id=P.Shift_Id	
	where ProcessFlag=1 and (P.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102))
	and (@local_shift=0 or (@local_shift!=0 and P.Shift_id=CONVERT(varchar(5),@local_shift)))
	
	create table #TempMonthlyAttendance
	(
		Employee_Id varchar(25),empName varchar(500),
		Designation varchar(250),Date datetime,InTime varchar(30),OutTime varchar(30),HrsWork varchar(30),
		lateinMin nvarchar(10),EarlyOutMin nvarchar(10),
		Inpunch varchar(20),Outpunch varchar(20),Indate datetime,Outdate datetime,
		Excess varchar(10),Remarks nvarchar(max),TotalMinsWorked int default(0),ExcessMins int,HrsLessExist int
		,HrsLessMins int,BreakHours int default(0),LunchHours int default(0)
		,BreakHoursMins int,LunchHoursMins int,manualIndate datetime,manualoutdate datetime,
		EmployeeAutoId int,ShftShrtName varchar(100),
		ManualInExist bit,ManualInStatus varchar(100),
		ManualOutExist bit,ManualOutStatus varchar(100)
	)
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''''    	
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,
							isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,
							replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,
							pd.date as Date,
							pd.InTime,
							pd.OutTime,
							pd.HrsWork,
							LateInMin,
							EarlyOutMin,
							Inpunch,
							Outpunch,
							Indate,
							Outdate,
							case when Excess=''''00:00'''' and HrsLess<>''''00:00'''' then ''''-'''' + HrsLess else Excess end,
							case 
								when	FNAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') 
										and ANAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')then FNAttendanceCode
								when	FNAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') 
										and ANAttendanceCode in(''''absent'''')then ANAttendanceCode+'''' / ''''+''''Half day - ''''+FNAttendanceCode +'''' (Approved)''''
								when	FNAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') 
										and ANAttendanceCode not in(''''absent'''')then ''''Half day - ''''+FNAttendanceCode +'''' (Approved)''''
								when	FNAttendanceCode in(''''absent'''') 
										and ANAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')then FNAttendanceCode+'''' / ''''+''''Half day - ''''+ANAttendanceCode+'''' (Approved)''''
								when	FNAttendanceCode not in(''''absent'''') 
										and ANAttendanceCode not in(''''Present'''',''''absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')then ''''Half day - ''''+ANAttendanceCode+'''' (Approved)''''
								when	FNAttendanceCode=''''Absent'''' and ANAttendanceCode=''''Absent'''' then ''''Absent''''
								when	FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''Holiday'''' then ''''Holiday''''
								when	FNAttendanceCode=''''RH'''' and ANAttendanceCode=''''RH'''' then ''''Holiday''''
								when	FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' then ''''Weekly Off''''
								else ''''''''
							end	
							Remarks,
							case when HrsWork is null then 0 
								 else ((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) 
							end as TotalMinsWorked,
							ExcessMins,
							case when Excess=''''00:00'''' and HrsLess<>''''00:00'''' then 1 
								 else 0 
							end,
							substring(hrsless,0,charindex('''':'''',hrsless))*60+substring(hrsless,charindex('''':'''',hrsless)+1,LEN(hrsless))%60, 
							BreakHours,
							LunchHours,
							BreakHoursMins,
							LunchHoursMins,
							date,
							case when isNightShift=1 then dateadd(d,1,date)
								 else date
							end,e.Employee_Id,ShftShrtName,'''''''','''''''','''''''','''''''' ''
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	SET @SQLQUERY = @SQLQUERY + '' WHERE 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, '''''' + CAST(@local_FromDate AS NVARCHAR(11)) + '''''', 102) AND PD.DATE <= CONVERT(DATETIME, '''''' + CAST(@local_ToDate AS NVARCHAR(11)) + '''''', 102)))''
	if(@local_UserGroupName<>''SuperAdmin'')  
		begin  
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel + ''''  
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''	
	insert into #TempMonthlyAttendance 
	exec(@sqlQuery)
	--select * from #TempMonthlyAttendance 
	update #TempMonthlyAttendance set Remarks=	case 
													 when tpd.Remarks=lt.LeaveType then lt.LeaveType + '' (Approved)''
													else tpd.Remarks 
												end from #TempMonthlyAttendance tpd
	inner join TA_Tbl_LeaveType LT on tpd.Remarks=lt.LeaveType where Remarks!='''' and Remarks is not null	
	update #TempMonthlyAttendance set Remarks=case when TM.Remarks!='''' then TM.Remarks+'' / ''+ lt.Leavetype +''-''+LAE.status
	else lt.Leavetype +''-''+LAE.status
	end from #TempMonthlyAttendance TM
	inner join ta_tbl_leaveapplicationexists LAE on LAE.Employee_Id=TM.EmployeeAutoId
	inner join ta_tbl_leaveapplication LA on LA.LeaveApplication_Id=LAE.LeaveApplicationId
	inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
	and Tm.Date=LAE.Leave_FromDate and LAE.status not in(''Approved'',''Rejected'') and LAE.isDeleted=0	
	--if manual in or out exists then should show the proper remarks.
	update #TempMonthlyAttendance set ManualInExist=1,ManualInStatus=ManualTimeEntry_Status
	from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and ((ManualTimeEntry_InDate=tpd.manualIndate))
	and MTE.ManualTimeEntry_Status!=''Rejected'' and MTE.isdeleted=0
	update #TempMonthlyAttendance set ManualOutExist=1,ManualOutStatus=ManualTimeEntry_Status
		from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and (ManualTimeEntry_OutDate)=tpd.manualoutdate 
	and MTE.ManualTimeEntry_Status!=''Rejected'' and MTE.isdeleted=0	
	--Manual Time Entry validation
	update #TempMonthlyAttendance set Remarks=
	case	when ManualInStatus=''Pending'' and ManualOutStatus=''Pending'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending''
								else ''Manual Time Entry - Pending''
								end
				when ManualInStatus=''Pending'' and ManualOutStatus=''Forwarded'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending,Forwarded''
								else ''Manual Time Entry - Pending,Forwarded''
								end
				when ManualInStatus=''Pending'' and ManualOutStatus=''Approved'' then  --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending''
								else ''Manual Time Entry - Pending''
								end
				when ManualInStatus=''Pending'' and ManualOutStatus='''' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending''
								else ''Manual Time Entry - Pending''
								end
				when ManualInStatus='''' and ManualOutStatus=''Pending'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending''
								else ''Manual Time Entry - Pending''
								end
				when ManualInStatus=''Forwarded'' and ManualOutStatus=''Pending'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded,Pending''
								else ''Manual Time Entry - Forwarded,Pending''
								end
				when ManualInStatus=''Forwarded'' and ManualOutStatus=''Forwarded'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded''
								else ''Manual Time Entry - Forwarded''
								end
				when ManualInStatus=''Forwarded'' and ManualOutStatus=''Approved'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded''
								else ''Manual Time Entry - Forwarded''
								end
				when ManualInStatus=''Forwarded'' and ManualOutStatus='''' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded''
								else ''Manual Time Entry - Forwarded''
								end
				when ManualInStatus='''' and ManualOutStatus=''Forwarded'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded''
								else ''Manual Time Entry - Forwarded''
								end								
				when ManualInStatus=''Approved'' and ManualOutStatus=''Pending'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Pending''
								else ''Manual Time Entry - Pending''
								end
				when ManualInStatus=''Approved'' and ManualOutStatus=''Forwarded'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Forwarded''
								else ''Manual Time Entry - Forwarded''
								end
				when ManualInStatus=''Approved'' and ManualOutStatus=''Approved'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Approved''
								else ''Manual Time Entry - Approved''
								end
				when ManualInStatus='''' and ManualOutStatus=''Approved'' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Approved''
								else ''Manual Time Entry - Approved''
								end
				when ManualInStatus=''Approved'' and ManualOutStatus='''' then --Completed
								case when tpd.Remarks!='''' then tpd.Remarks+'' / Manual Time Entry - Approved''
								else ''Manual Time Entry - Approved''
								end
				else
								case when tpd.Remarks!='''' then tpd.Remarks								
								end
	end
	from #TempMonthlyAttendance tpd
	inner join Ta_Tbl_ManualTimeEntry MTE on tpd.Employee_Id=MTE.ManualTimeEntry_Employee_Id
	and ((ManualTimeEntry_InDate=tpd.manualIndate) or (ManualTimeEntry_OutDate=tpd.manualoutdate))
	and MTE.ManualTimeEntry_Status!=''Rejected'' and MTE.isdeleted=0	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	select		
		Employee_Id,
		empName,
		Designation,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		Inpunch,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Indate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Indate, @dateFormat) 
		end AS Indate,	
		case when InTime<>''00:00'' then
					case	when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,InTime,0)), 114),0,6)
							else	case	when len(SUBSTRING(intime,0,charindex('':'',intime)))=1 then ''0''+intime
											else InTime 
									end
					end
			else '''' 
		end	InTime,
		Outpunch,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Outdate,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Outdate, @dateFormat) 
		end AS Outdate,
		case when OutTime<>''00:00'' then
					case	when (@TimeFormat)=''hh:mm'' then substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,OutTime,0)), 114),0,6)
							else	case	when len(SUBSTRING(OutTime,0,charindex('':'',OutTime)))=1 then ''0''+OutTime
											else OutTime 
									end
					end
			else ''''
		end OutTime,
		case	when InTime IS null and OutTime is null then ''-'' 
				when InTime ='''' and OutTime ='''' then ''-''				
				when InTime =''00:00'' and OutTime =''00:00'' then ''-''
				when InTime !='''' and OutTime ='''' then ''-''
				when InTime is not null and OutTime is null then ''-''
				when InTime ='''' and OutTime !='''' then ''-''
				when InTime is null and OutTime is not null then ''-''
				else HrsWork
		end as HrsWork,
		case	when InTime IS null and OutTime is null then ''-'' 
				when InTime ='''' and OutTime ='''' then ''-''
				when InTime =''00:00'' and OutTime =''00:00'' then ''-''				
				when InTime !='''' and OutTime ='''' then ''-''
				when InTime is not null and OutTime is null then ''-''
				when InTime ='''' and OutTime !='''' then ''-''
				when InTime is null and OutTime is not null then ''-''
				else Excess 
		end as Excess,
		case when CHARINDEX(''/'',
		case	when convert(int,lateinMin)>0		then ''Late In / ''				
					else '''' 
		end + ''''+
		case	when convert(int,EarlyOutMin)>0	then ''Early Exit / ''
					else '''' 
		end + ''''+
		case	when convert(int,HrsLessMins)>0	then ''Less Hours Worked / ''
					else '''' 
		end + ''''+
		case	when (InTime is not null and OutTime is null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when (InTime is null and OutTime is not null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when InTime IS null and OutTime is null and Remarks='''' then ''-'' 
					when InTime ='''' and OutTime ='''' and Remarks='''' then ''-''
					else Remarks
		end,		
		LEN(
		case	when convert(int,lateinMin)>0		then ''Late In / ''				
					else '''' 
		end + ''''+
		case	when convert(int,EarlyOutMin)>0	then ''Early Exit / ''
					else '''' 
		end + ''''+
		case	when convert(int,HrsLessMins)>0	then ''Less Hours Worked / ''
					else '''' 
		end + ''''+
		case	when (InTime is not null and OutTime is null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when (InTime is null and OutTime is not null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when InTime IS null and OutTime is null and Remarks='''' then ''-'' 
					when InTime ='''' and OutTime ='''' and Remarks='''' then ''-''
					else Remarks
		end))!=0 then
		SUBSTRING(case	when convert(int,lateinMin)>0		then ''Late In / ''				
					else '''' 
		end + ''''+
		case	when convert(int,EarlyOutMin)>0	then ''Early Exit / ''
					else '''' 
		end + ''''+
		case	when convert(int,HrsLessMins)>0	then ''Less Hours Worked / ''
					else '''' 
		end + ''''+
		case	when (InTime is not null and OutTime is null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when (InTime is null and OutTime is not null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when InTime IS null and OutTime is null and Remarks='''' then ''-'' 
					when InTime ='''' and OutTime ='''' and Remarks='''' then ''-''
					else Remarks
		end,0,len(case	when convert(int,lateinMin)>0		then ''Late In / ''				
					else '''' 
		end + ''''+
		case	when convert(int,EarlyOutMin)>0	then ''Early Exit / ''
					else '''' 
		end + ''''+
		case	when convert(int,HrsLessMins)>0	then ''Less Hours Worked / ''
					else '''' 
		end + ''''+
		case	when (InTime is not null and OutTime is null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when (InTime is null and OutTime is not null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when InTime IS null and OutTime is null and Remarks='''' then ''-'' 
					when InTime ='''' and OutTime ='''' and Remarks='''' then ''-''
					else Remarks
		end)-1)
		else
		case	when convert(int,lateinMin)>0		then ''Late In / ''				
					else '''' 
		end + ''''+
		case	when convert(int,EarlyOutMin)>0	then ''Early Exit / ''
					else '''' 
		end + ''''+
		case	when convert(int,HrsLessMins)>0	then ''Less Hours Worked / ''
					else '''' 
		end + ''''+
		case	when (InTime is not null and OutTime is null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when (InTime is null and OutTime is not null) then ''Missing Punch / ''
					else ''''
	    end+''''+
		case	when InTime IS null and OutTime is null and Remarks='''' then ''-'' 
					when InTime ='''' and OutTime ='''' and Remarks='''' then ''-''
					else Remarks
		end
		end		
		as Remarks,
		convert(int,lateinMin)as lateinMin,
		convert(int,EarlyOutMin)as EarlyOutMin,
		Date as format,			
		TotalMinsWorked,
		ExcessMins,
		HrsLessExist,
		isnull(HrsLessMins,0)HrsLessMins,
		BreakHoursMins,				
		case	when (BreakHours Is null Or BreakHours='''') then ''-'' 
				else	case	when LEN(BreakHours/60)=1 then ''0''+(CONVERT(varchar(10),(BreakHours/60)))
								else (CONVERT(varchar(10),(BreakHours/60))) 
						end 
						+'':''+
						case	when len(BreakHours%60)=1 then ''0''+CONVERT(varchar(10),(BreakHours%60))
								else CONVERT(varchar(10),(BreakHours%60)) 
						end 
		end as BreakHours,
		ShftShrtName,
		LunchHoursMins,
		case	when (LunchHours Is null Or LunchHours='''') then ''-'' 
				else	case	when len(LunchHours/60)=1 then ''0''+convert(varchar(10),(LunchHours/60))
								else convert(varchar(10),(LunchHours/60)) 
						end 
						+'':''+
						case	when LEN(LunchHours%60)=1 then ''0''+ CONVERT(varchar(10),(LunchHours%60))
								else CONVERT(varchar(10),(LunchHours%60)) 
						end 
		end as LunchHours					
		from #TempMonthlyAttendance 		
		order by Employee_Id,format 
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	drop table #TempMonthlyAttendance	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTemporaryShift]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTemporaryShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil Proc_TA_RptTemporaryShift ''05/01/2011'','''','''','''','''','''',''SuperAdmin'','''','''',323,0,''Both''
-- ALTER  date: 17Aug2007
-- Description:	Report Temporary Shift
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptTemporaryShift]  
(
	@fromDate datetime,	
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@EmployeeName varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
    @ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @shift int,
	@EmpAutoId bigint			          
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
    insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Temporary table''s creation
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
			--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
		--Employee Level insert in Temporary table
		insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) ELevel
		inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
		--Employee Designation insert in Temporary table
		insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
		select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EDesig
		inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
		AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
		--Employee Type insert in Temporary table
		insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpType
		inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
		AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
		--Employee Category insert in Temporary table
		insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 group by EmployeeId) EmpCategory
		inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
		AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
		----Employee Pay insert in Temporary table
		--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
		--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
		--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
		--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
		--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
		--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EPay.PayId is not null
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''
			set @sqlQuery = @sqlQuery + '' SELECT     dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''''&amp;'''',''''&'''')+ '''' ('''' + TA_Tbl_Shift.Shift_Starttime +'''' - '''' + TA_Tbl_Shift.Shift_endtime + '''')'''' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + Space(1) + ''
            set @sqlQuery = @sqlQuery + '' isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') as empname, replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, replace(dbo.TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,dbo.TA_Tbl_Employee.Gender '' 
			set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_TemporaryShiftAllocation LEFT OUTER JOIN''
            set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_TemporaryShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN''
            set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_TemporaryShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
       		set @sqlQuery = @sqlQuery + '' Inner join dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''      
			set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
			--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
			--set @sqlQuery = @sqlQuery + '' inner JOIN dbo.TA_Tbl_EmployeePay ON ta_tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId ''
			--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
            set @sqlQuery = @sqlQuery + '' WHERE (dbo.TA_Tbl_TemporaryShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_TemporaryShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0''
		if(@UserGroupName<>''SuperAdmin'')
			begin
				SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
			end
		if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
		If Not (@EmpSwipeCard = '''')  
			Begin  
				  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			End  
		if not(@EmployeeId='''')  
			begin  
				set @sqlQuery = @sqlQuery + ''and (ta_tbl_Employee.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
			end 
		if not(@EmployeeName='''')  
			begin  
				set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' +  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
			end  
		if(@employeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
			end
		if(@employeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
			end
		if(@DesignationID<>0)
			begin
			   set @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
			end	
	    if(@Gender<>''Both'')
			begin
			   set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
			end	
		if(@shift<>0)
			begin
				set @sqlQuery = @sqlQuery +  '' And  TA_Tbl_Shift.Shift_Id = '' +  cast(@shift  as nvarchar(20))  
			end
		set @sqlQuery = @sqlQuery + '' order by TA_Tbl_Employee.Employee_Code_Id'' 
exec (@sqlQuery)
--Remove the temporary tables here
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #EmployeeIds
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTawazunMonthlyAttendance]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTawazunMonthlyAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--exec Proc_TA_RptTawazunMonthlyAttendance @MinWorkHours=N'''',@fromDat=''2020-02-01 00:00:00'',@ToDat=''2021-03-24 00:00:00'',@EmployeeName=N'''',@LevelID=N''0,1'',@EmployeeId=N'''',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpSwipeCard=N'''',@ParentId=0,@DesignationID=0,@Gender=N''Both'',@Shift=0,@DataLoading=0,@EmpAutoId=0,@Export=0
CREATE  PROCEDURE [dbo].[Proc_TA_RptTawazunMonthlyAttendance]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		OD_Time varchar(20),
		Tot_OD_Mins int
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!=''Superadmin'')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER=''BOTH'' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME=''Superadmin'')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'''')='''' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'''')='''' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			--updated by velumani for Abraj Monthly attendance design issue
			--case when vp.INTIME=''00:00'' then '''' else vp.INTIME end,
			--case when vp.OUTTIME=''00:00'' then '''' else vp.OUTTIME end,
			--vp.SHIFT_ID,
			--case when vp.HRSWORK=''00:00'' then '''' else vp.HRSWORK end,
			(case when  vp.INTIME is null or vp.INTIME=''00:00''  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME=''00:00'' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK=''00:00'' then null else vp.HRSWORK end) as HRSWORK,
		-------------------------
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude,''00:00'',0
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY'') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY''))))
		AND ((INTIME IS NOT NULL OR not(INTIME=''00:00'')) OR (OUTTIME IS NOT NULL OR not(OUTTIME=''00:00'')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))
	)

	create table #Onduty(
		EMPLOYEE_CODE_ID VARCHAR(20),	
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		ManualTimeEntry_InDate datetime,
		ManualTimeEntry_OutDate datetime)
	insert into #Onduty
	Select ManualTimeEntry_Employee_Id,ManualTimeEntry_InTime,ManualTimeEntry_OutTime,ManualTimeEntry_InDate,ManualTimeEntry_OutDate from TA_Tbl_ManualTimeEntry where (ManualTimeEntry_InDate between convert(datetime, cast(@local_FROMDAT as nvarchar(11)) , 101) and convert(datetime, cast(@local_TODAT as nvarchar(11)) ,101) or ManualTimeEntry_OutDate between convert(datetime,cast(@local_FROMDAT as nvarchar(11)) , 101) and convert(datetime, cast(@local_TODAT as nvarchar(11)),101)) and IsOnDuty=1 and ManualTimeEntry_Status=''Approved'' and Isdeleted=0
	--Select * from #Onduty
	update T set 
	T.OD_Time=CONVERT(varchar(5),DATEADD(minute,DATEDIFF(MINUTE,(ManualTimeEntry_InDate + OD.INTIME),(ManualTimeEntry_OutDate + OD.OUTTIME)), 0), 114),
	T.Tot_OD_Mins=DATEDIFF(MINUTE,(ManualTimeEntry_InDate + OD.INTIME),(ManualTimeEntry_OutDate + OD.OUTTIME))
	from #TEMPPROCESSEDDATA T inner join #Onduty OD on T.EMPLOYEE_CODE_ID=OD.EMPLOYEE_CODE_ID and cast(T.DATE as date)=cast(OD.ManualTimeEntry_InDate as date)

	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE=''CL'' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''PM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''AM'' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''AM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''PM'' AND PD.OUTTIME>''00:00 AM'' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,''00:00''))
	if(@TOTALMIN='''') set @TOTALMIN=0
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20),
		Day_Name varchar(25),
		OD_Hours nvarchar(20),
		Tot_OD_Mins int
	)	
	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''PRESENT'' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''FN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION=''M'' then '' #'' else '''' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''PRESENT'' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''AN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION=''M'' then '' #'' else '''' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,
	REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
			WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
			ELSE PD.SUPPOSEDWORKHOURS 
	END ''SUPPOSEDWORKHOURS'',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
				 WHEN PD.SHIFT_ID=-1 THEN ''-''
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),''00:00''
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00'' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''NORMOTMINS'',
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''WEEKOFFOTMINS'',
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''HOLIDAYOTMINS'',
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00'' THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	''00:00'',
	''00:00'',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+''/''+
			CASE	WHEN ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude,Format(PD.DATE,''dddd'') ,PD.OD_Time,PD.Tot_OD_Mins
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME=''Superadmin'' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'''')='''' or dbo.ConvertHoursToMinites(isnull(HRSWORK,''00:00''))>=@TOTALMIN)
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'''' as Intime1,
		'''' as OutTime1,		 
		'''' as Intime2,
		'''' as OutTime2,
		'''' as Intime3,
		'''' as OutTime3,
		'''' as Intime4,
		'''' as OutTime4,
		'''' as Intime5,
		'''' as OutTime5,
		'''' as AcutalWorkedHours,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ '' : '' +left(datename(MONTH,DATE),15),ATTENDANCE,Day_Name,OD_Hours,Tot_OD_Mins
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	drop table #Onduty
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummaryCount]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummaryCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_RptSummaryCount   ''27/01/2015'',''superadmin'',0
CREATE PROCEDURE [dbo].[Proc_TA_RptSummaryCount]   
(    
 @Date VarChar(50),  
 @UserGroupName varchar(250),  
 @ParentId int      
)   
AS    
BEGIN    
  SET NOCOUNT ON 
 --added to prevent extra result sets from    
 -- interfering with SELECT statements.    
create table #LevelRights(LevelId int)  
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
Declare @SelectSQL As Varchar(8000)    
Set @SelectSQL = '' ''      
Set @SelectSQL = ''Select count(*) as ReportCount ''  
Set @SelectSQL = @SelectSQL + '' From Ta_Tbl_ProcessedData PD''  
Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Employee ED ON ED.SwipeCardNo = PD.Employee_Code_Id''    
Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_EmployeeLevel Lev ON Lev.EmployeeID= ED.Employee_Id''    
Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID=L.Id''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId = Lev.LevelId ''  
Set @SelectSQL = @SelectSQL + '' where ED.IsDeleted = ''''0''''  and ED.report_exclude=0''   
 If (@Date <> '''')    
 Begin    
  Set @SelectSQL = @SelectSQL + '' And (PD.Date >= CONVERT(DATETIME,''''''+cast(@Date as nvarchar(50))+'''''', 102))''
 End    
 exec (@SelectSQL)    
 --remove the temporary tables    
 SET NOCOUNT ON;    
END    ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary_Old]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummary_Old]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_RptSummary ''11-Jan-11'',''SuperAdmin'',''0''
create PROCEDURE [dbo].[Proc_TA_RptSummary_Old]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int       
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
--select * from #tempProcessSecSummary
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempProcessSecSummary ''    
set @SelectSQL = @SelectSQL + '' select replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,Ta_tbl_Employee.SwipeCardNo  
as Employee_Code_Id,Ta_Tbl_ProcessedData.Date,Ta_Tbl_ProcessedData.FNAttendanceCode,Ta_Tbl_ProcessedData.ANAttendanceCode,Ta_Tbl_ProcessedData.EarlyOutMins,Ta_Tbl_ProcessedData.LateInMins,Ta_Tbl_ProcessedData.intime,Ta_Tbl_ProcessedData.outtime ''    
set @SelectSQL = @SelectSQL + '' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave, null ''    
set @SelectSQL = @SelectSQL + '' From Ta_Tbl_ProcessedData inner join Ta_tbl_Employee on Ta_Tbl_ProcessedData.[date]='''''' + @Date +  '''''' and Ta_Tbl_ProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo''    
set @SelectSQL = @SelectSQL + '' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
--set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_Employee.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId ''    
set @SelectSQL = @SelectSQL + '' where Ta_tbl_Employee.Employee_Status=1 ''    
exec (@SelectSQL)     
  --select * from  #tempProcessSecSummary  
create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempProcessSecSummaryFinal ''    
set @SelectSQL = @SelectSQL + '' select distinct replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,'''''''' as   
Employee_Code_Id,'''''' + @Date +  '''''' as Date,'''''''' as FNAttendanceCode,'''''''' as ANAttendanceCode,0 as EarlyOutMins,0 as LateInMins,'''''''' as  intime,'''''''' as outtime ''    
set @SelectSQL = @SelectSQL + '' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 ''    
set @SelectSQL = @SelectSQL + '' From Ta_tbl_Employee''    
set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId ''    
set @SelectSQL = @SelectSQL + '' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
exec (@SelectSQL)     
update #tempProcessSecSummaryFinal set Absence=AbsenceCount.Absence    
from (select count(*) as Absence,levelID from #tempProcessSecSummary where    
FNAttendanceCode = ''Absent'' and ANAttendanceCode = ''Absent''    
Group by levelID) AbsenceCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AbsenceCount.levelID    
update #tempProcessSecSummaryFinal set EarlyOut=EarlyOutCount.EarlyOut    
from (select count(*) as EarlyOut,levelID from #tempProcessSecSummary where    
(EarlyOutMins != 0 and  EarlyOutMins is not null and intime is not null and (LateInMins=0))    
Group by levelID) EarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=EarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set LateIn=LateInCount.LateIn    
from (select count(*) as LateIn,levelID from #tempProcessSecSummary where    
(LateInMins != 0 and LateInMins is not null and outtime is not null and (EarlyOutMins=0))    
Group by levelID) LateInCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInCount.levelID    
update #tempProcessSecSummaryFinal set [LateIn/EarlyOut]=LateInEarlyOutCount.[LateIn/EarlyOut]    
from (select count(*) as [LateIn/EarlyOut],levelID from #tempProcessSecSummary where    
EarlyOutMins != 0 and EarlyOutMins is not null and LateInMins != 0 and LateInMins is not null    
Group by levelID) LateInEarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInEarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set TotalPresent=TotalPresentCount.TotalPresent    
from (select count(*) as TotalPresent,levelID from #tempProcessSecSummary where    
(intime is not null or outtime is not null)    
Group by levelID) TotalPresentCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalPresentCount.levelID    
update #tempProcessSecSummaryFinal set MissingOut=MissingOutCount.MissingOut    
from (select count(*) as MissingOut,levelID from #tempProcessSecSummary where    
((intime is null and outtime is not null)     
or (intime is not null and outtime is null))     
Group by levelID) MissingOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=MissingOutCount.levelID    
update #tempProcessSecSummaryFinal set AttendancePunched=AttendancePunchedCount.AttendancePunched    
from (select count(*) as AttendancePunched,levelID from #tempProcessSecSummary where    
intime is not null and outtime is not null    
and LateInMins = 0     
and EarlyOutMins = 0     
Group by levelID) AttendancePunchedCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AttendancePunchedCount.levelID    
update #tempProcessSecSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees    
--from (select count(*) as TotalEmployees,TA_Tbl_Employee.LevelId from TA_tbl_EmployeeLevel     
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID     
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0    
--and @Date between TA_Tbl_EmployeeLevel.EffectiveDate and isnull(TA_Tbl_EmployeeLevel.endDate,getdate())    
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalEmployeesCount.levelID    
select * from #tempProcessSecSummaryFinal order by Dept    
 --remove the temporary tables     
drop table #tempProcessSecSummary    
drop table #tempProcessSecSummaryFinal    
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptSummary]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptSummary]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_RptSummary ''11-Jan-11'',''SuperAdmin'',''0''
CREATE PROCEDURE [dbo].[Proc_TA_RptSummary]   
(    
 @Date VarChar(50),    
 @UserGroupName varchar(250),    
 @ParentId int       
)    
AS      
BEGIN      
create table #LevelRights(LevelId int)    
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId    
create table #tempProcessSecSummary (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
--select * from #tempProcessSecSummary
Declare @SelectSQL As Varchar(8000)      
Set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempProcessSecSummary ''    
set @SelectSQL = @SelectSQL + '' select replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,Ta_tbl_Employee.SwipeCardNo  
as Employee_Code_Id,Ta_Tbl_ProcessedData.Date,Ta_Tbl_ProcessedData.FNAttendanceCode,Ta_Tbl_ProcessedData.ANAttendanceCode,Ta_Tbl_ProcessedData.EarlyOutMins,Ta_Tbl_ProcessedData.LateInMins,Ta_Tbl_ProcessedData.intime,Ta_Tbl_ProcessedData.outtime ''    
set @SelectSQL = @SelectSQL + '' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave, null ''    
set @SelectSQL = @SelectSQL + '' From Ta_Tbl_ProcessedData inner join Ta_tbl_Employee on Ta_Tbl_ProcessedData.[date]='''''' + @Date +  '''''' and Ta_Tbl_ProcessedData.Employee_code_Id=Ta_tbl_Employee.SwipeCardNo''    
set @SelectSQL = @SelectSQL + '' and Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
--set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_Employee.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId = Ta_tbl_EmployeeLevel.LevelId ''    
set @SelectSQL = @SelectSQL + '' where Ta_tbl_Employee.Employee_Status=1 ''    
exec (@SelectSQL)     
  --select * from  #tempProcessSecSummary  
create table #tempProcessSecSummaryFinal (Dept varchar(250),levelID bigint,[level] bigint,Parent bigint,ParentName varchar(250),PEmployee_Code_Id varchar(15),PDate datetime,FNAttendanceCode varchar(150),ANAttendanceCode varchar(150),EarlyOutMins bigint,  
LateInMins bigint,intime varchar(10),outtime varchar(10)     
,AttendancePunched int,LateIn int, EarlyOut int,[LateIn/EarlyOut] int,MissingOut int,Absence int,TotalEmployees int,TotalPresent int,Leave int,LOP int null)    
set @SelectSQL = '' ''     
set @SelectSQL = @SelectSQL + '' insert into #tempProcessSecSummaryFinal ''    
set @SelectSQL = @SelectSQL + '' select distinct replace(L.Name,''''&amp;'''',''''&'''') as Dept,L.Id as levelID,L.levelID as level,L.ParentId as Parent,isnull(replace(Parent.name,''''&amp;'''',''''&''''),replace(L.Name,''''&amp;'''',''''&'''')) as ParentName,'''''''' as   
Employee_Code_Id,'''''' + @Date +  '''''' as Date,'''''''' as FNAttendanceCode,'''''''' as ANAttendanceCode,0 as EarlyOutMins,0 as LateInMins,'''''''' as  intime,'''''''' as outtime ''    
set @SelectSQL = @SelectSQL + '' ,0 as AttendancePunched,0 as LateIn, 0 as EarlyOut,0 as [LateIn/EarlyOut],0 as MissingOut,0 as Absence,0 as TotalEmployees,0 as TotalPresent,0 as Leave,0 ''    
set @SelectSQL = @SelectSQL + '' From Ta_tbl_Employee''    
set @SelectSQL = @SelectSQL + '' INNER JOIN Ta_tbl_EmployeeLevel ON  Ta_tbl_EmployeeLevel.EmployeeID = Ta_tbl_Employee.Employee_Id ''    
set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_LevelDetails L ON  Ta_tbl_EmployeeLevel.LevelID=L.Id ''    
set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_LevelDetails Parent ON  L.ParentId=Parent.Id ''    
set @SelectSQL = @SelectSQL + '' Inner join #LevelRights on #LevelRights.LevelId=Ta_tbl_EmployeeLevel.LevelId ''    
set @SelectSQL = @SelectSQL + '' where Ta_tbl_Employee.Employee_Status=1 and Ta_tbl_Employee.IsDeleted=0 and Ta_tbl_Employee.Report_Exclude=0 ''    
exec (@SelectSQL)     
update #tempProcessSecSummaryFinal set Absence=AbsenceCount.Absence    
from (select count(*) as Absence,levelID from #tempProcessSecSummary where    
FNAttendanceCode = ''Absent'' and ANAttendanceCode = ''Absent''    
Group by levelID) AbsenceCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AbsenceCount.levelID    
update #tempProcessSecSummaryFinal set EarlyOut=EarlyOutCount.EarlyOut    
from (select count(*) as EarlyOut,levelID from #tempProcessSecSummary where    
(EarlyOutMins != 0 and  EarlyOutMins is not null and intime is not null and (LateInMins=0))    
Group by levelID) EarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=EarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set LateIn=LateInCount.LateIn    
from (select count(*) as LateIn,levelID from #tempProcessSecSummary where    
(LateInMins != 0 and LateInMins is not null and outtime is not null and (EarlyOutMins=0))    
Group by levelID) LateInCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInCount.levelID    
update #tempProcessSecSummaryFinal set [LateIn/EarlyOut]=LateInEarlyOutCount.[LateIn/EarlyOut]    
from (select count(*) as [LateIn/EarlyOut],levelID from #tempProcessSecSummary where    
EarlyOutMins != 0 and EarlyOutMins is not null and LateInMins != 0 and LateInMins is not null    
Group by levelID) LateInEarlyOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=LateInEarlyOutCount.levelID    
update #tempProcessSecSummaryFinal set TotalPresent=TotalPresentCount.TotalPresent    
from (select count(*) as TotalPresent,levelID from #tempProcessSecSummary where    
(intime is not null or outtime is not null)    
Group by levelID) TotalPresentCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalPresentCount.levelID    
update #tempProcessSecSummaryFinal set MissingOut=MissingOutCount.MissingOut    
from (select count(*) as MissingOut,levelID from #tempProcessSecSummary where    
((intime is null and outtime is not null)     
or (intime is not null and outtime is null))     
Group by levelID) MissingOutCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=MissingOutCount.levelID    
update #tempProcessSecSummaryFinal set AttendancePunched=AttendancePunchedCount.AttendancePunched    
from (select count(*) as AttendancePunched,levelID from #tempProcessSecSummary where    
intime is not null and outtime is not null    
and LateInMins = 0     
and EarlyOutMins = 0     
Group by levelID) AttendancePunchedCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=AttendancePunchedCount.levelID    
update #tempProcessSecSummaryFinal set TotalEmployees = TotalEmployeesCount.TotalEmployees    
--from (select count(*) as TotalEmployees,TA_Tbl_Employee.LevelId from TA_tbl_EmployeeLevel     
from (select count(*) as TotalEmployees,TA_Tbl_EmployeeLevel.levelID from TA_tbl_EmployeeLevel     
inner join TA_Tbl_Employee on  TA_Tbl_Employee.Employee_Id=TA_tbl_EmployeeLevel.EmployeeID     
and TA_Tbl_Employee.IsDeleted=0 and TA_Tbl_Employee.Employee_Status=1 and TA_Tbl_Employee.Report_Exclude=0    
--and @Date between TA_Tbl_EmployeeLevel.EffectiveDate and isnull(TA_Tbl_EmployeeLevel.endDate,getdate())    
and TA_Tbl_EmployeeLevel.EffectiveDate<=@Date    
Group by TA_Tbl_EmployeeLevel.levelID) TotalEmployeesCount    
--Group by TA_Tbl_Employee.levelID) TotalEmployeesCount    
inner join #tempProcessSecSummaryFinal on #tempProcessSecSummaryFinal.levelID=TotalEmployeesCount.levelID    
select * from #tempProcessSecSummaryFinal order by Dept    
 --remove the temporary tables     
drop table #tempProcessSecSummary    
drop table #tempProcessSecSummaryFinal    
SET NOCOUNT ON;      
-- Insert statements for procedure here      
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftNotAllocated]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftNotAllocated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptShiftNotAllocated ''10/01/2019'',''10/31/2019'','''','''',''9547'','''','''',''SuperAdmin'',1,'''',0,0,''Both'',1
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation and  TA_tbl_TemporaryShiftAllocation
Created By : Sashma  
Created on : 10-May-2011    
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftNotAllocated] 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(max),  
 @LevelID varchar(8000), 
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoId bigint
AS  
BEGIN  
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
		if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	create table #TempEmployee 
	(EmployeeAutoID bigint,EmpName varchar(150),Employee_Code_Id varchar(20),Designation varchar(150),Gender varchar(10),name varchar(150),datetOfjoining datetime)
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
    set @sqlQuery = ''insert into #TempEmployee select e.employee_Id,e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,''''''''),e.employee_code_id,T.TitleName,e.Gender,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,e.DateOfJoining from TA_Tbl_Employee e ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id ''
		End
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id ''
		End
	set @sqlQuery=@sqlQuery + '' where e.Isdeleted=0  and e.Report_exclude=0 and e.Employee_Status=1 ''
		if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>='' + @GradeLevel  
		end
    if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	exec(@sqlQuery)  
	--To fill the dates in between the from date and to date for all employees
	create table #TempEmployeeWithDate(EmployeeAutoID bigint,EmpName varchar(150),Employee_Code_Id varchar(20),Designation varchar(150),Gender varchar(10),name varchar(150),Date datetime)
	;WITH DateField AS
	(
	SELECT @fromDat Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < @ToDat
	)
	insert into #TempEmployeeWithDate
	SELECT TE.EmployeeAutoID,TE.EmpName,TE.Employee_Code_Id,TE.Designation,TE.Gender,TE.name,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where (Df.Dates between @fromDat and @ToDat) and (DF.Dates>=TE.datetOfjoining)Option (maxrecursion 0) 
	
	--select * from #TempEmployeeWithDate where Employee_Code_Id=''9547''
	 
	create table #TempShiftNotAllocated_Permanent (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	create table #TempShiftNotAllocated_Temporary (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftNotAllocated_Permanent (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt where ShiftId<>0;
	--select * from #TempShiftNotAllocated_Permanent
	--Unpivot the temporary shift allocation table.
	insert into #TempShiftNotAllocated_Temporary (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt where ShiftId<>0;
	--select * from #TempShiftNotAllocated_Temporary
	--update the shift id in the permanent table from temporary table
	update #TempShiftNotAllocated_Permanent set ShiftId=T.ShiftId
	from #TempShiftNotAllocated_Permanent P
	inner join  #TempShiftNotAllocated_Temporary T on (P.EmployeeID=T.EmployeeID
	and P.Year=T.Year and P.Month=T.Month and P.Day=T.Day)
    --inserts the records from the temporary table to the permanant table(records which is not exists in permanant table
	insert into #TempShiftNotAllocated_Permanent
	select T.EmployeeID,T.Year,T.Month,T.Day,T.ShiftId,T.Date from #TempShiftNotAllocated_Temporary T
	where not exists (select * from #TempShiftNotAllocated_Permanent P where P.EmployeeID=T.EmployeeID
	and P.Year=T.Year and P.Month=T.Month and P.Day=T.Day)
    --delete from permanant table if the date is not valid
	delete from #TempShiftNotAllocated_Permanent where isDate(Date) = 0 
    --select records from permanant table which has shift Id as 0 and also the dates which does not exists in the permanant table
	select	E.Employee_Code_Id,
			E.empname,
			E.name as DeptName,
			E.Designation as TitleName,
			E.Gender,
			E.Date as NotAllocatedDates 
	from #TempEmployeeWithDate E 
	where not exists(select * from  #TempShiftNotAllocated_Permanent PS where E.EmployeeAutoID = EmployeeID and E.Date=cast(PS.Date as datetime) and cast(PS.Date as datetime) between @fromDat and @ToDat)
	--union all
	--select E.Employee_Code_Id,(E.Employee_FirstName + '' '' + E.Employee_LastName) as empname,
	--LD.name as DeptName,T.TitleName,E.Gender,cast(PS.Date as Datetime) as NotAllocatedDates from #TempShiftNotAllocated_Permanent PS
	--inner join TA_Tbl_Employee E on PS.EmployeeID=E.Employee_Id
	--inner join TA_Tbl_EmployeeDesignation ED on ED.EmployeeID=E.Employee_Id
	--inner join TA_Tbl_Title T on T.TitleId=ED.DesignationID
	--inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
	--inner join Ta_Tbl_levelDetails LD on LD.id= EL.LevelId
	--where PS.ShiftId=0 and cast(PS.Date as datetime) between @fromDat and @ToDat order by E.Employee_Code_Id,NotAllocatedDates
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights 
	drop table #TempEmployee
	drop table #TempEmployeeWithDate
	drop table #TempShiftNotAllocated_Permanent
	drop table #TempShiftNotAllocated_Temporary
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation_Surguru]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftAllocation_Surguru]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--exec Proc_TA_RptShiftAllocation @fromDat=''2019-07-01 00:00:00'',
--@ToDat=''2019-07-30 00:00:00'',@EmployeeName=N'''',@LevelID=N''0'',
--@EmployeeId=N''4'',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',
--@EmpSwipeCard=N'''',@ParentId=1,@DesignationID=0,@Gender=N''Both'',@Religion =0,@EmpAutoId = 0



/*  
Procedure Name : Proc_TA_RptShiftAllocation_Surguru ''01/01/2019'',''12/12/2019'','''','''','''','''','''',''SuperAdmin'',1,'''',0,0,''Both'',0,0
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By : Velumani P 
Created on :   

-- Description	:	SQL Query Optimazation & Emp name filtering
exec Proc_TA_RptShiftAllocation @fromDat=''2017-04-01 00:00:00'',
@ToDat=''2018-03-30 00:00:00'',@EmployeeName=N'''',@LevelID=N''26'',
@EmployeeId=N'''',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',
@EmpSwipeCard=N'''',@ParentId=26,@DesignationID=0,@Gender=N''Both'',@Religion =0,@EmpAutoId =0
*/ 

/*
Need to comment pivot table concept for product, Since lcoation table is not in product.
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftAllocation_Surguru] 
(
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000), 
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Religion int,
	@EmpAutoId bigint
)	
AS  
BEGIN  
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end


	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') as Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender, e.employee_id from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_Code_Id ''
		End
	set @sqlQuery=@sqlQuery + '' where e.Isdeleted=0 and 	
	 e.Report_exclude=0 and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat as nvarchar(20)) +'''''', 102 ))as nvarchar(10)),102) ''
	set @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102 ))as nvarchar(10)),102)''
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>='' + @GradeLevel  
		end
	IF(@Religion!=1 and @Religion!=0)
		BEGIN
			SET @sqlQuery=@sqlQuery+'' AND e.Religion = ''+cast(@Religion as varchar(50))+'' ''
		END
	if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
	  END
	set @sqlQuery = @sqlQuery + '' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month'' 
	exec(@sqlQuery)  

	--query to show employee shift allocated location in report 
	create table #ShiftLocationTble(EmployeeName varchar(100),employee_Code_Id int,Year int, Month int, 
	Day1Shift int,Day2Shift int,Day3Shift int,Day4Shift int,Day5Shift int,
	Day6Shift int,Day7Shift int,Day8Shift int,Day9Shift int,Day10Shift int,
	Day11Shift int,Day12Shift int,Day13Shift int,Day14Shift int,Day15Shift int,
	Day16Shift int,Day17Shift int,Day18Shift int,Day19Shift int,Day20Shift int,
	Day21Shift int,Day22Shift int,Day23Shift int,Day24Shift int,Day25Shift int,
	Day26Shift int,Day27Shift int,Day28Shift int,Day29Shift int,Day30Shift int,Day31Shift int,
    emp_id int, timestamp datetime, dateShift datetime, titleName varchar(50), Gender nvarchar(10),employee_id nvarchar(15))
	
	insert into #ShiftLocationTble exec(@sqlQuery)  --employee_Id

	

	create table #PivotShiftTable1 (Employee_Code_Id varchar(15), EmployeeName varchar(100),LocName varchar(220),ShiftDate datetime, DayShiftName varchar(10), monthNo int)

	insert into #PivotShiftTable1 
	select Employee_Code_Id, a.EmployeeName,
	UPPER(isnull(LVL.name,'''''''')) as LocName, dbo.DateOnly(LOC.ShiftDate) as ShiftDate,''Day''+convert(nvarchar, DATEPART(d, LOC.ShiftDate))+''Shift'' as DayShiftName, DATEPART(M, LOC.ShiftDate) as monthNo from #ShiftLocationTble a
	LEFT OUTER JOIN TA_tbl_ShiftAdd_Location LOC ON (convert(nvarchar,LOC.EmployeeId) = a.employee_Id)
	LEFT OUTER JOIN TA_TBL_LEVELDETAILS LVL on (LVL.Id = LOC.LocationId)
	where (LOC.ShiftDate) <=@ToDat and (LOC.ShiftDate >= @fromDat)

	select * from #PivotShiftTable1

	SELECT [Employee_Code_Id],EmployeeName,
	Day1Shift,Day2Shift,Day3Shift,Day4Shift, Day5Shift, 
	Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,
	Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,
	Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,
	Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,
	Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
	FROM   
	(
		SELECT DayShiftName,Employee_Code_Id, EmployeeName,LocName,monthNo FROM  #PivotShiftTable1
	)Tab1  
	
	PIVOT  
	
	(  
	Max(LocName) FOR DayShiftName	
	IN (
	Day1Shift,Day2Shift,Day3Shift,Day4Shift, Day5Shift, 
	Day6Shift,Day7Shift,Day8Shift,Day9Shift,Day10Shift,
	Day11Shift,Day12Shift,Day13Shift,Day14Shift,Day15Shift,
	Day16Shift,Day17Shift,Day18Shift,Day19Shift,Day20Shift,
	Day21Shift,Day22Shift,Day23Shift,Day24Shift,Day25Shift,
	Day26Shift,Day27Shift,Day28Shift,Day29Shift,Day30Shift,Day31Shift
	)
)	AS Tab2 
	
	ORDER BY [Tab2].[Employee_Code_Id] 

	--Remove the temporary tables here 
    drop table #ShiftLocationTble

	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptShiftAllocation]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--exec Proc_TA_RptShiftAllocation @fromDat=''2019-07-01 00:00:00'',@ToDat=''2019-07-30 00:00:00'',@EmployeeName=N'''',@LevelID=N''0'',@EmployeeId=N''4'',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpSwipeCard=N'''',@ParentId=1,@DesignationID=0,@Gender=N''Both'',@Religion =0,@EmpAutoId = 0
/*
Need to comment pivot table concept for product, Since lcoation table is not in product.
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptShiftAllocation] 
(
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000), 
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Religion int,
	@EmpAutoId bigint
)	
AS  
BEGIN  
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') as Employee_FirstName,e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender, e.employee_id from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_Code_Id ''
		End
	set @sqlQuery=@sqlQuery + '' where e.Isdeleted=0 and 	
	 e.Report_exclude=0 and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat as nvarchar(20)) +'''''', 102 ))as nvarchar(10)),102) ''
	set @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102 ))as nvarchar(10)),102)''
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>='' + @GradeLevel  
		end
	IF(@Religion!=1 and @Religion!=0)
		BEGIN
			SET @sqlQuery=@sqlQuery+'' AND e.Religion = ''+cast(@Religion as varchar(50))+'' ''
		END
	if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
	  END
	set @sqlQuery = @sqlQuery + '' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month'' 
	exec(@sqlQuery) 	
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptRawDataPunches_Dashboard]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptRawDataPunches_Dashboard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_RptRawDataPunches_Dashboard ''2015/09/01'',''2015/09/11'',''101,'',''karthikeyan'',''SuperAdmin'',0,1,0,0,''Both''
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptRawDataPunches_Dashboard]
(
@FromDate varchar(20),
@ToDate varchar(20),
@EmployeeId varchar(max),
@EmployeeName varchar(max),
@UserGroupName varchar(250),
@DesignationID int,
@employeeCategory int,
@employeeType int,
@ParentID int,
@Gender varchar(10),
@EmpAutoID int
)
	-- Add the parameters for the stored procedure here
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
		if(@EmployeeId is not null and @EmployeeId <> '''')
			begin
				create table #EmployeeID(EmployeeID varchar(25))
				insert into #EmployeeID
				select * from SplitupEmployeeCode(@EmployeeId)
			end	
		if(@EmployeeName is not null and @EmployeeName <> '''')
			begin
				create table #EmployeeName(EmployeeID varchar(25))
				insert into #EmployeeName
				select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
			end	
		--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		create table #LevelRights(LevelId int)
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Employee Level Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type insert in Temporary table
		insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
		insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
		insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
		declare @sqlEmpLevel nvarchar(Max)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select * from #LevelRights
		set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.SwipeCardNo ''
		End
	Execute(@sqlEmpLevel)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select CAST(Emp_ID as int) from TA_Tbl_Employee
		--select * from #EmployeeID
		--select * from #EmployeeName
		--select * from Ta_Tbl_levelDetails
		declare @sqlQuery as nvarchar(max)
		set @sqlQuery=''''
		set @sqlQuery=''select RD.CLK_CARDID as ''''Employee_Code_Id'''',Emp.Employee_FirstName + '''' '''' + Emp.Employee_LastName as EmployeeName,
		Ter.Terminal_Name,CONVERT(nvarchar(20),RD.CLK_DATE, ''+ convert(varchar,@dateFormat) +'') as ShiftDate,
		CONVERT(nvarchar(20),RD.CLK_DATE, ''+ convert(varchar,@dateFormat) +'') as PunchDate,RD.CLK_TIME as PunchTime,
		PY.PunchType,RD.*,ld.Name as LevelName,CAST(''''01-01-1900 '''' + RD.CLK_Time as datetime) as OrderTime
		from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.Employee_Code_Id=RD.CLK_CARDID  ''
		set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID ''
		set @sqlQuery = @sqlQuery + '' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value ''
		if(@ParentID=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
				set @sqlQuery = @sqlQuery + '' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
				set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
			end
		if(@employeeType=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
			end
		if(@DesignationID=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
			end
		if(@employeeCategory=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
			end
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.SwipeCard ''
		End
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.SwipeCard ''
		End
		set @sqlQuery = @sqlQuery + '' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where 
		RD.CLK_FLAG=1 and RD.CLK_PROCESS=1 and RD.ReasonId in (0) and RD.CLK_DATE >=''''''+ @FromDate +'''''' and RD.CLK_DATE <='''''' + @ToDate +''''''''
		if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and Emp.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (Emp.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		set @sqlQuery = @sqlQuery +''Order by RD.CLK_DATE,OrderTime desc''
		exec(@sqlQuery)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_rptRawData]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_rptRawData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_rptRawData ''2019/04/01'',''2019/08/24'','''','''',''SuperAdmin'',0,0,0,0,''Both'',2,1,''0''
-- Proc_TA_rptRawData ''2019/04/01'',''2019/08/24'','''','''',''SuperAdmin'',0,0,0,0,''Both'',2,1,''91280''
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- drop procedure [Proc_TA_rptRawData]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_rptRawData]
(
	@FromDate varchar(20),
	@ToDate varchar(20),
	@EmployeeId varchar(max),
	@EmployeeName varchar(max),
	@UserGroupName varchar(250),
	@DesignationID int,
	@employeeCategory int,
	@employeeType int,
	@ParentID int,
	@Gender varchar(10),
	@ProcessType int,
	@EmpAutoID int,
	@DeviceId varchar(50)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Isdel int
	SET @Isdel=0
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmployeeName(EmployeeID varchar(25))
	create table #EmployeeID(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '''')
	begin		
		insert into #EmployeeID
		select * from SplitupEmployeeCode(@EmployeeId)
	end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
	begin
		insert into #EmployeeName
		select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
	end	
	--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Type insert in Temporary table
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		LEFT OUTER JOIN #EmployeeID on #EmployeeID.EmployeeID=emp.Employee_Code_Id
		Left outer join #EmployeeName on #EmployeeName.EmployeeID=emp.Employee_Code_Id 
		where emp.Isdeleted=0 group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery=''select	RD.CLK_CARDID as ''''Employee_Code_Id'''',
							Emp.Employee_FirstName + '''' '''' + isnull(Emp.Employee_LastName,'''''''') as EmployeeName,
							(isnull(Ter.Terminal_Name,'''''''') + '''' ('''' + RD.CLK_DEVICEID + '''')'''') as ''''Terminal_Name'''', 
							case	when ''+cast(@dateFormat as varchar(100))+''=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') else CONVERT(VARCHAR, RD.CLK_DATE, ''+cast(@dateFormat as varchar(100))+'') 
									end AS ShiftDate,
							case	when ''+cast(@dateFormat as varchar(100))+''=106 then REPLACE(CONVERT(VARCHAR, RD.CLK_DATE,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') else CONVERT(VARCHAR, RD.CLK_DATE, ''+cast(@dateFormat as varchar(100))+'') end AS PunchDate,RD.CLK_TIME as PunchTime,(isnull(PY.PunchType,'''''''') + '''' ('''' + RD.CLK_TYPE + '''')'''') as ''''PunchType'''',RD.*,ld.Name as LevelName,CONVERT(datetime,''''01-01-1900 '''' + RD.CLK_Time,103) as OrderTime, case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''''Processing...'''' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''''Processed'''' else case when ReasonId=''''0'''' then ''''Processed'''' else case when ReasonId=''''1'''' then ''''Remedy 1'''' else case when ReasonId=''''2'''' then ''''Remedy 2'''' else case when ReasonId=''''3'''' then ''''Remedy 3'''' else ''''Remedy 4'''' end end end end end 
									end  as Resolution,
							case when (CLK_FLAG=0 and CLK_PROCESS=0) then ''''Processing...'''' else case when (CLK_FLAG=1 and CLK_PROCESS=1) then ''''Processed'''' else ''''Non Processed'''' end end as Process
	from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.SwipeCardNo=RD.CLK_CARDID  ''
	set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID ''
	set @sqlQuery = @sqlQuery + '' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value ''
	if(@ParentID=0)
	begin
		set @sqlQuery = @sqlQuery + '' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
		set @sqlQuery = @sqlQuery + '' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
	end
	else
	begin
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
	end
	if(@employeeType=0)
	begin
		set @sqlQuery = @sqlQuery + '' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
	end
	else
	begin
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
	end
	if(@DesignationID=0)
	begin
		set @sqlQuery = @sqlQuery + '' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
	end
	else
	begin
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
	end
	if(@employeeCategory=0)
	begin
		set @sqlQuery = @sqlQuery + '' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
	end
	else
	begin
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
	end
	If Not (@EmployeeId = '''')  
	Begin  
	SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.Employee_Code_Id ''
	End
	If Not (@EmployeeName = '''')  
	Begin  
		SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.Employee_Code_Id ''
	End
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where RD.CLK_DATE >=''''''+ @FromDate +'''''' and RD.CLK_DATE <='''''' + @ToDate +''''''''
	if(@ProcessType <> 0)
	begin
	if(@ProcessType =1)
	begin
		set @sqlQuery = @sqlQuery + '' and CLK_FLAG=1 and CLK_PROCESS=1 ''
	end
	else if(@ProcessType =2)
	begin
		set @sqlQuery = @sqlQuery + '' and CLK_FLAG=1 and CLK_PROCESS=0 ''
	end
	end	
	if(@Gender<>''Both'')
	begin
		set @sqlQuery = @sqlQuery + '' and Emp.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
	end
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + '' and (Emp.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	if(@DeviceId !=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' and RD.CLK_DEVICEID = '''''' + cast(@DeviceId as nvarchar(40)) + '''''' ''
	end
	set @sqlQuery = @sqlQuery +'' Order by RD.CLK_DATE,OrderTime desc''
	exec(@sqlQuery)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_rptPunctuality]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_rptPunctuality]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptMonthlyAttendance  
MOdified By : Gopinath.K  
Modified Date : 20-Dec-2013 & 11-Jan-2014
Description   :SQL Query Optimization & Emp name filtering
*/
-- proc_ta_rptPunctuality  ''01/01/2016'',''12/31/2020'','''',0,'''','''',0,0,''SuperAdmin'',''0'','''',0,0,''Both'',0,1
CREATE  PROCEDURE [dbo].[proc_ta_rptPunctuality]  
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeId varchar(max),  
	@shift int = 0,  
	@EmployeeName varchar(max),  
	@LevelID varchar(8000),
	@employeeCategory int = 0,
	@employeeType int = 0,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint,
	@ExportType int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	--This get the current datetime format
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	--To split up the comma separated values
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where emp.Isdeleted=0 
		and (isnull(@EmployeeId,'''')='''' or emp.Employee_Code_Id in(select * from #EmployeeID))
		and (isnull(@EmployeeName,'''')='''' or emp.Employee_Code_Id in(select * from #EmployeeName))
		and(@Gender=''Both'' or emp.Gender=@Gender)
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,@todat, 102) and EL.LevelId is not null
	
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
    insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	and (isnull(@EmployeeId,'''')='''' or TA_Tbl_Employee.Employee_Code_Id in(select * from #EmployeeID))
	and (isnull(@EmployeeName,'''')='''' or TA_Tbl_Employee.Employee_Code_Id in(select * from #EmployeeName))
	
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id
	from TA_Tbl_ProcessedData 
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
    where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102))  
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(20)), 102))  
	and  dbo.TA_Tbl_ProcessedData.LateIn=''00:00'' and intime<>''00:00''
	and (@shift=0 or TA_Tbl_ProcessedData.Shift_Id=@shift)
	
	Create table #TempPunc(shift_shartName nVarchar(5), shiftIn nvarchar(20),Employee_Code_Id nvarchar(20),Date nvarchar(20),shift_id int,InTime nvarchar(20),Employee_FirstName nvarchar(100),[Level Name] nvarchar(100),TitleName nvarchar(100),Gender nvarchar(10),format datetime)
	insert into #TempPunc 
	select	ta_tbl_shift.shift_shortName, 
			right(dbo.ta_tbl_shift.Shift_StartTime,8)as shiftIn, 
			TA_Tbl_Employee.Employee_Code_Id,
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, #TempProcessedData.Date,@dateFormat),'' '',''-'') 
					else CONVERT(VARCHAR, #TempProcessedData.Date, @dateFormat) 
			end AS ''Date'', #TempProcessedData.shift_id,
			#TempProcessedData.InTime,
			(dbo.TA_Tbl_Employee.Employee_FirstName + '' '' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''')) as Employee_FirstName,
			replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') AS ''Level Name'',
			replace(TA_Tbl_Title.TitleName,''&amp;'',''&'') AS ''TitleName'',
			TA_Tbl_Employee.Gender,#TempProcessedData.Date as format FROM
			#TempProcessedData INNER JOIN dbo.TA_Tbl_Employee  ON #TempProcessedData.EmpAutoId = ta_tbl_employee.Employee_ID 
			Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id 
			inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id
			inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId
			inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId
			INNER JOIN dbo.ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id
			Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id
			Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id
			where #TempProcessedData.InTime <> ''0'' and #TempProcessedData.InTime <> ''00:00:00'' and #TempProcessedData.InTime is not null
			And (	TA_Tbl_Employee.Employee_Status = 1 or (TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102) >= convert(varchar(11),#TempProcessedData.Date,102))) 
			AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0)
			and (@UserGroupName=''Superadmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			and(@isReportingto=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds))) 
			and(@EmpAutoId=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)))
			order by lower(TA_Tbl_Employee.Employee_Code_Id),ta_tbl_Employee.Employee_FirstName,cast(#TempProcessedData.Date as datetime)
	if(@ExportType=1)
	begin
		select Employee_Code_Id ,Employee_FirstName,Gender,Date,shiftIn,InTime,shift_shartName as shift_shortName,shift_id,[Level Name],TitleName,format from #TempPunc
	end
	else
	begin		
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct [Level Name] from #TempPunc
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempPunc order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + ''@''
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempPunc where [Level Name]=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
				end
				--select distinct Date from #TempLate where [Level Name]=(select Name from #TempLevelName where ID=@cou)
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + ''#''
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
	end
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
	drop table #TempProcessedData
	drop table #TempEmployee 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermission]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermission]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_RptPermission ''04/05/2011'',''05/15/2013'','''','''','''',0,0,''SuperAdmin'',0,''All'','''',0,0,''Both''
--  Proc_TA_RptPermission ''01/Aug/2016'',''30/Sep/2016'','''',''0,1'','''',0,0,''SuperAdmin'',0,''All'','''',1,0,''Both'',0
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
CREATE  PROCEDURE [dbo].[Proc_TA_RptPermission]
 (
    @fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@EmployeeCategory int,
	@EmployeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LeaveStatus varchar(30),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
    @Gender varchar(10),
    @EmpAutoId bigint
 )
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDat,@EmployeeId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as varchar(8000)
	set @sqlQuery=''''
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,e.Employee_FirstName +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,Ta_Tbl_levelDetails.name as BranchName,dbo.TA_Tbl_Title.TitleName as Designation, case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_Permission.Permission_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, TA_Tbl_Permission.Permission_Date, ''+cast(@dateFormat as varchar(100))+'')
	end AS Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,e.Gender,TA_Tbl_Permission.Permission_Hours,((SUBSTRING(ISNULL(TA_Tbl_Permission.Permission_Hours,''''00:00''''),0,CHARINDEX('''':'''',TA_Tbl_Permission.Permission_Hours))*60) + (SUBSTRING(ISNULL(TA_Tbl_Permission.Permission_Hours,''''00:00''''),(LEN(TA_Tbl_Permission.Permission_Hours)-1),2))) AS TOTALPERMISSIONMINS,Permission_Reason from TA_Tbl_Employee e inner join TA_Tbl_Permission  on e.Employee_Id=TA_Tbl_Permission.Employee_Id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON EDesig.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where e.report_exclude=0 and e.Isdeleted=0 and Ta_Tbl_Permission.IsDeleted=0 
	and 
	((e.employee_Status=1)
	or
	(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),TA_Tbl_Permission.Permission_Date,102))
	) 
	and (TA_Tbl_Permission.Permission_Date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and TA_Tbl_Permission.Permission_Date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102))''
	if(@UserGroupName<>''SuperAdmin'')
	begin
		set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
	end
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	   
	if not(@LeaveStatus=''All'')
		begin
			set @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Permission.Permission_Status= '''''' + cast(@LeaveStatus as nvarchar(100)) + ''''''''
		end
	if(@isReportingto > 0)
    BEGIN
       set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
    END
	set @sqlQuery = @sqlQuery + '' Group by TA_Tbl_Permission.Permission_Date,TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime,TA_Tbl_Permission.Permission_Status,TA_Tbl_Permission.Permission_Hours,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_LastName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName,e.Gender,Permission_Reason order by e.Employee_Code_Id,e.Employee_FirstName,Ta_Tbl_levelDetails.name,TA_Tbl_Title.TitleName,Permission_Reason ASC''	
    exec(@sqlQuery)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPermanentShift]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPermanentShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================      
-- Author:  senthil    Proc_TA_RptPermanentShift ''2015/05/01'',[0,1],''787,'','''',0,0,''SuperAdmin'',0,'''',0,0,''Both'',0
-- ALTER  date: 17Aug2007      
-- Description: Report Permanent Shift 
-- Modified by : sashma
-- Modified on : 12-May-2011   
-- =============================================      
CREATE  PROCEDURE [dbo].[Proc_TA_RptPermanentShift]       
(      
 @fromDate datetime,       
 @LevelID varchar(8000),
 @EmployeeId varchar(max),
 @EmployeeName varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @shift int,
 @EmpAutoId bigint	     
)      
AS      
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	----Employee Level insert in Temporary table
	--insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	--select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) ELevel
	--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and EL.LevelId is not null
	----select * from #EmpLevel
	----Employee Designation insert in Temporary table
	--insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	--select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	--inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EDesig
	--inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	--AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102) and ED.DesignationId is not null
	----select * from #EmpDesignation
	----Employee Type insert in Temporary table
	--insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	--select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	--inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EmpType
	--inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	--AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)  and EType.TypeId is not null
	----select * from #EmpType
	----Employee Category insert in Temporary table
	--insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	--select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	--inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	--inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	--AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@fromDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null	
	Declare @sqlEmpLevel nvarchar(4000)
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @fromDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @fromDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @fromDate,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@fromDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)      
	SET @sqlQuery = ''''      
	SET @sqlQuery1 = ''''
	DECLARE @timeformat   varchar(10)
	SET @timeformat=(SELECT TimeFormat FROM TA_Tbl_DateandTimeFormat)	
	if(@timeformat=''hh:mm tt'')
		begin
			SET @sqlQuery = @sqlQuery + '' SELECT dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''''&amp;'''',''''&'''') + '''' ('''' + TA_Tbl_Shift.Shift_Starttime +'''' - '''' + TA_Tbl_Shift.Shift_endtime + '''')'''' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + Space(1) + ''      
		end
	else
		begin
			SET @sqlQuery = @sqlQuery + '' SELECT dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift as ShiftId,dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId,dbo.TA_Tbl_Employee.Employee_Code_Id,replace(dbo.TA_Tbl_Shift.Shift_ShortName,''''&amp;'''',''''&'''') + '''' ('''' + convert(char(5),cast(TA_Tbl_Shift.Shift_Starttime as datetime),108)  +'''' - '''' + convert(char(5),cast(TA_Tbl_Shift.Shift_endtime as datetime),108) + '''')'''' as Shift_ShortName, isnull(dbo.TA_Tbl_Employee.Employee_FirstName,'''''''') + Space(1) + ''      
		end
	SET @sqlQuery = @sqlQuery + '' isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') as empname, replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,replace(dbo.TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender''      
	SET @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_PermanentShiftAllocation LEFT OUTER JOIN''      
	SET @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_PermanentShiftAllocation.Day'' + cast (day(@fromDate) as nvarchar(10)) + ''Shift = dbo.TA_Tbl_Shift.Shift_Id INNER JOIN''      
	SET @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Employee ON dbo.TA_Tbl_PermanentShiftAllocation.EmployeeId = dbo.TA_Tbl_Employee.Employee_Id''      
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''      
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	SET @sqlQuery = @sqlQuery + '' WHERE (dbo.TA_Tbl_PermanentShiftAllocation.Year ='' + cast (year(@fromDate) as nvarchar(10)) + '') AND (dbo.TA_Tbl_PermanentShiftAllocation.Month = '' + cast (month(@fromDate) as nvarchar(10)) + '')''      
	SET @sqlQuery = @sqlQuery + '' and dbo.TA_Tbl_Employee.Isdeleted=0 and dbo.TA_Tbl_Employee.employee_Status=1 and dbo.TA_Tbl_Employee.report_exclude=0''
	if(@shift<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery +  '' And  TA_Tbl_Shift.Shift_Id = '' +  cast(@shift  as nvarchar(20))  
		END
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End      	
	if(@Gender<>''Both'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		END		
	if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
		END
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
		END
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		END
	if(@isReportingto > 0)
		BEGIN
		   set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	exec (@sqlQuery)
	--Remove the temporary tables here
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_GeneralExport]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip_GeneralExport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author        : R.Manikandan
-- Create date   : 29-June-2015
-- Modified date :  
-- Description   : <Description,,>  
-- exec [Proc_TA_RptPayslip_GeneralExport] ''28/Sep/2015'',''31/Oct/2015'','''','''',''107'',''SuperAdmin'',''0'','''',0,0,''Male'',0,0,0
-- exec [Proc_TA_RptPayslip_GeneralExport] ''01/Dec/2015'',''31/Dec/2015'',''877'','''',''0'',''SuperAdmin'',''0'','''',0,0,''Both'',0,0,0
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip_GeneralExport]
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(100),   
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
    @ParentId int,  
    @DesignationID int,  
	@Gender varchar(10),
	@employeeCategory int,  
	@employeeType int,
	@EmpAutoId BIGINT
)  
AS  
BEGIN
	SET NOCOUNT ON ;
	Declare @FromDateOld datetime
	Declare @ToDateOld datetime
	--set @FromDateOld=''01/July/2015''
	--set @ToDateOld=''31/July/2015''
	Declare @Difference int
	Declare @datepart int
	Declare @M int
	Set @M=0
	declare @month char(2)
	Declare @start varchar(20)
	declare @enddate varchar(20)
	select @Difference=DATEDIFF(d,@fromDat,@ToDat)/2
	while @M>=0
	begin
		select @datepart= DATEPART(d,DATEADD(d,@M,@fromDat))	
		if(@Difference=@datepart)
			begin
			set @month= DATEPART(MONTH,DATEADD(d,@M,@fromDat))
			set @month=	case	when LEN(@month)=1 then ''0''+CONVERT(char(2),@month)
								else CONVERT(char(2),@month)
						end
			set @start=convert(varchar(20),DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-01''
			if(@month in(1,3,5,7,8,10,12))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-31''
				end
			else if(@month in(4,6,9,11))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-30''
				end
			else
				begin
					if(DATEPART(YEAR,@fromDat)/4=0)
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-29''
						end
					else
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-28''
						end
				end
			set @M=-2
		end
		set @M=@M+1
	end
	set @FromDateOld=CONVERT(datetime,@start+'' 00:00:00.000'')
	set @ToDateOld=CONVERT(datetime,@enddate+'' 00:00:00.000'')
	--select @FromDateOld,@ToDateOld
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '''', @Query VARCHAR(MAX), @I INT = 1;
	declare @DeviationColumns VARCHAR(MAX) = '''';
	declare @DeviationColumnsDisplay VARCHAR(MAX) = '''';
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlCommon nvarchar(max)	
	Declare @sqlEmpDesi nvarchar(max)
	Declare @sqlTempProcessedData varchar(max)	
	Declare @sqlCommonSwipeCardNo nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)	
	Declare @sqlEmpCategory nvarchar(max)
	Declare @sqlEmpType nvarchar(max)	
	set @sqlCommon=''''
	--Creates the tepmoraray tables.
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200) ,  
		[EmployeeId] varchar(50),  	
		Present numeric(8,1),
		LeaveDays numeric(8,1),
		LopDays numeric(8,1),
		LateEntryNoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		sat_WorkHrs decimal(18,1),
		MonToSat_WorkHrs decimal(18,1),
		LessHoursWorked numeric(8,1),
		LateInMins int,
		TotalHrsEnteredInArmis numeric(8,1),
		TotalDefinedWorkHrs numeric(8,1),
		DaysNeedToDeduct_Late decimal(18,2) default(0.0),
		DaysNeedToDeduct_Armis decimal(18,2) default(0.0),
		DaysNeedToDeduct_Working decimal(18,2) default(0.0),
		TotalMinutesWorked int
	)	 	
    create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20),sat_WorkHrs decimal(18,1),MonToSat_WorkHrs decimal(18,1))
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  	
	create table #EmpGrade(Grade_Id int) 
    create table #EmpAttendanceDetails
    (	EmployeeID  varchar(50),
		Present numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateInMins numeric(8,1),		
		LopDays numeric(8,1),
		LeaveDays numeric(8,1),
		NoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		TotalDefinedWorkHrsInMins int default(0),
		weeknumber int,
		TotalMinutesWorked int
	)      
    create table #TempProcessedData
    (
		Employee_Code_Id varchar(20),
		NumberOfPresentDays decimal(18,1),
		LateInMins int,
		TotalLeaveDays decimal(18,1),
		OtherLeaveDays decimal(18,1),
		OverAllDeviations varchar(20),
		NumberofDaysWorked as (NumberOfPresentDays+TotalLeaveDays-OtherLeaveDays),
		DeviationHoursFormat_Week1 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week2 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week3 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week4 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week5 varchar(30) default(''TC:00:00 A:00:00'')
	)   		
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID);
	--INSERT INTO @TempExecptionHrs
	--	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	--	WHERE [Date] BETWEEN @fromDat AND @ToDat
	--GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @fromDat, @ToDat)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @fromDat) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @fromDat)) != ''Sunday'' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT	@WeekName = ''Week'' + CAST(@I AS VARCHAR(10)),
			@DeviationColumns=@DeviationColumns+''+convert(int,isnull(DeviationHours_'' + @WeekName+'',0))'', 
			@DeviationColumnsDisplay=@DeviationColumnsDisplay+'',DeviationHoursFormat_'' + @WeekName ,
			@TableColumns = @TableColumns + '', TargetWorkHours_'' + @WeekName + '' VARCHAR(10), ActualWorkHours_'' + @WeekName + '' VARCHAR(10), ArmisWorkHours_'' + @WeekName + '' VARCHAR(10), [Leave_Permision_'' + @WeekName + ''] VARCHAR(10), 
	DeviationHours_'' + @WeekName + '' VARCHAR(30),DeviationHoursFormat_''+@WeekName+'' varchar(30)default(''''TC:00:00 A:00:00'''')'',@I = @I + 1 FROM WeekName
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]([Grade_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[EmployeeId],[LevelId] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[EmployeeId],[DesignationId] ASC)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[EmployeeId],[CategoryId])ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[EmployeeId],[TypeId]) ON [PRIMARY]  
	--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
	SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
	INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDat AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
	SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
	SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
	INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
	INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType 
	SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
	SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
	INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
	INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
	AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
	SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
	SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
	INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102)
	GROUP BY EmployeeId) EmpCategory
	INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
	AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
	INSERT INTO #EmpPay
	SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
	SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
	INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
	AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''FinalAttendanceSummary'')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC(''CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50),Sat_WorkHrs	numeric(18,1)'' + @TableColumns + '')'')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = ''Week'' + CAST(@I AS VARCHAR(10))		
		SELECT 
		@fromDat = Tbl1.WeekDates,
		@ToDat = Tbl2.WeekDates FROM (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
		INNER JOIN (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
		WHERE Tbl1.Id = @I				
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10),WeekDay_WorkHrs decimal(18,1))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int,
		Sat_WorkHrs	numeric(18,1)
		)
		--Commented for local database
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
		SET @SQLQuery = ''SELECT * FROM 
		[ProjectManagementV3July16].[dbo].[Fn_GetProgressReport]('''''' + CAST(@fromDat AS VARCHAR(20)) + '''''','''''' + CAST(@ToDat AS VARCHAR(20)) + '''''''' + (CASE WHEN @empId = '''' OR @empId IS NULL THEN '', NULL)'' ELSE '', '' + @empId + '')'' END)
		--Commented for local database
		INSERT INTO @ArmisTable
		EXEC(@SQLQuery)			
		--select * from @ArmisTable
		SET @SQLQuery = ''SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END,''
		SET @SQLQuery = @SQLQuery + '' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''''''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''''''), REPLACE(LD.Name, ''''&amp;'''', ''''&''''),''
		SET @SQLQuery = @SQLQuery + '' REPLACE(T.TitleName, ''''&amp;'''', ''''&''''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''''-''''), ISNULL(PD.OutTime, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' ISNULL(PD.HrsWork, ''''-''''), ((SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 4, 2))),''
		SET @SQLQuery = @SQLQuery + '' (S.Shift_ShortName + '''' ('''' + S.Shift_StartTime + '''' - ''''  + S.Shift_EndTime + '''')''''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' (CASE WHEN (ISNULL(PD.BreakIn, '''''''') = '''''''' OR ISNULL(PD.BreakOut, '''''''') = '''''''') AND PD.BreakHours <> ''''00:00'''' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')),ISNULL(SS.MaxWorkPlaceInHours, ''''00:10''''), NULL
		,C.WeekDay_WorkHrs*60.0 FROM Ta_Tbl_Employee E''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id''    
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId''   
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId ''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId ''		
		set @SQLQuery = @SQLQuery + '' where 
		(
			(e.Employee_Status = 1) 
			or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102))
		) 	
		AND (e.Isdeleted = 0) AND (e.report_exclude = 0)''
		SET @SQLQuery = @SQLQuery + '' AND ((PD.date >= CONVERT(DATETIME, '''''' + CAST(@fromDat AS NVARCHAR(11)) + '''''', 102) 
		AND PD.Date <= CONVERT(DATETIME, '''''' + CAST(@ToDat AS NVARCHAR(11)) + '''''', 102)))''
		IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel + ''''
		END
		IF NOT(@EmployeeName = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_FirstName + '''' '''' + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName +''%'' AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@empId='''')  
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_Code_Id = '''''' + CAST(@empId AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmpSwipeCard = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND E.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		If (@Gender <> ''Both'')  
		Begin  
			Set @SQLQuery = @SQLQuery + '' And E.Gender = '''''' + @Gender + '''''' ''  
		End
		SET @SQLQuery = @SQLQuery + '' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)''   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		--select * from #TempAttendanceDetails 
		--UPDATE #TempAttendanceDetails SET
		--HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		--TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		--FROM #TempAttendanceDetails AD
		--RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDat) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
		WHERE #TempAttendanceDetails.Day = ''Saturday'' AND #TempAttendanceDetails.Date = @ThirdSat
		INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.CategoryName,
			TA.DefinedWorkHours,
			TA.DefinedWorkHours - SUM(
		(((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
		ELSE 
		0.0
		END
		) * 8,
		SUM(CAST(TA.TotalMinsWorked AS INT)),
		0,
		SUM(
		(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
		WHEN C.Sat_WorkHrs = 2 THEN 
		(CASE 
		WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
		WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
		0.0 END)
		ELSE 
		(CASE
		WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
		WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
		0.0 END
		)
		END
		) * 8,
		0,
		CAST(MAX(TA.[Date]) AS DATE),
		0,0
		FROM #TempAttendanceDetails TA
		INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != ''Sunday''
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
		UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
		UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
		--Commented for local database
		UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
		INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id		
		UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
		--select 
		--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
		CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
		(ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
						(
							substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours)))*60
							+
							substring(convert(varchar(10),ArmisWorkHours),CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
							+ 
							[Leave_Permision] *60
							+ 
							(DefinedWorkHours - TargetWorkHours)*60
						)
					)
		ELSE 0 
		END,
		Sat_WorkHrs=C.Sat_WorkHrs
		FROM #TempAttendanceSummary TAS
		INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
		INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
		SELECT	@WeekName AS WeekName,
				Employee_Code_Id,
				EmployeeName,
				CategoryName,
				REPLACE((TargetWorkHours - [Leave_Permision]), ''.'', '':'') AS TargetWorkHours,
				CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + '':'' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
				REPLACE(ArmisWorkHours, ''.'', '':'') AS ArmisWorkHours,
				REPLACE([Leave_Permision], ''.'', '':'') AS [Leave_Permision],
				case	when DeviationHours>ArmisDeviationHrs then	DeviationHours																
						when ArmisDeviationHrs>DeviationHours then	ArmisDeviationHrs
						when ArmisDeviationHrs=DeviationHours then	DeviationHours
				end AS DeviationHours,
				--DeviationHours AS DeviationHours,
				Sat_WorkHrs,				
			''TC:''+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			''A:''+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END as DeviationHoursInFormat
		INTO #TempFinalResult FROM #TempAttendanceSummary WHERE (DeviationHours != 0 or ArmisDeviationHrs != 0 OR 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = ''UPDATE FinalAttendanceSummary SET 
		Employee_Code_Id	= TR.Employee_Code_Id,
		EmployeeName		= TR.EmployeeName,
		CategoryName		= TR.CategoryName,
		TargetWorkHours_'' + @WeekName + '' = TR.TargetWorkHours,
		ActualWorkHours_'' + @WeekName + '' = TR.ActualWorkHours,
		ArmisWorkHours_'' + @WeekName + '' = TR.ArmisWorkHours,
		[Leave_Permision_'' + @WeekName + ''] = TR.[Leave_Permision],
		DeviationHours_'' + @WeekName + '' = isnull(TR.DeviationHours,0),
		Sat_WorkHrs=TR.Sat_WorkHrs,
		DeviationHoursFormat_'' + @WeekName + '' = TR.DeviationHoursInFormat
		 FROM FinalAttendanceSummary FAS
		INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName''
		EXEC(@SQLQuery)
		SET @SQLQuery = ''
		INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName,
		Sat_WorkHrs,TargetWorkHours_'' + @WeekName + '', ActualWorkHours_'' + @WeekName + '', ArmisWorkHours_'' + @WeekName + '', 
		[Leave_Permision_'' + @WeekName + ''], DeviationHours_'' + @WeekName + '', DeviationHoursFormat_'' + @WeekName +'')
		SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName,TR.Sat_WorkHrs,TR.TargetWorkHours, TR.ActualWorkHours, 
		TR.ArmisWorkHours, TR.[Leave_Permision],isnull(TR.DeviationHours,0),TR.DeviationHoursInFormat FROM #TempFinalResult TR
		LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
		WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL''
		EXEC(@SQLQuery)
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		--Commented for local database
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	--select * from FinalAttendanceSummary
	--Getting 3rd saturday date.
	Create table #Temp(date datetime,day varchar(max),id int)
	;with cte(Date,id,week) as 
	(	
		select @FromDateOld,1 as id,DATEPART(WEEK,@FromDateOld)
		union all
		select Date+1,id+1,DATEPART(WEEK,Date+1) from cte where Date < @ToDateOld
	)
	insert into #Temp select Date,DATENAME(W,Date)Day,id from cte
	option (MAXRECURSION 0)
	Declare @ThirdSaturday datetime	
	select @ThirdSaturday=date from(select *,ROW_NUMBER()over(order by id)as row from #Temp where day=''Saturday'')as a where row=3
	set	@DeviationColumnsDisplay=SUBSTRING(@DeviationColumnsDisplay,2,len(@DeviationColumnsDisplay))
	--select @DeviationColumns
	--select @DeviationColumnsDisplay
	--declare @alter varchar(max)
	--set @alter=''alter table #TempProcessedData add ''+replace(@DeviationColumnsDisplay,'','','' varchar(20),'')+'' varchar(20)''
	--Execute(@alter)
	set @sqlTempProcessedData1=  
	''insert into #TempProcessedData
	(Employee_Code_Id,NumberOfPresentDays,LateInMins,TotalLeaveDays,OtherLeaveDays,OverAllDeviations,''+@DeviationColumnsDisplay+'')
	select	Employee_Code_Id	=	PD.Employee_Code_Id,
	NumberOfPresentDays	=	sum(CASE when PD.DATE= '''''' +CONVERT(varchar(20),@ThirdSaturday) + '''''' 
	and Sat_WorkHrs=2 and DATENAME(W,Date)=''''Saturday'''' then 
	case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
			when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
	end
	 when Sat_WorkHrs=0 and DATENAME(W,Date)=''''Saturday'''' then 
	 case	when FNAttendanceCode=''''Present''''	 and ANAttendanceCode=''''Present''''	 then 0.5
			when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Present''''    and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Present''''    then 0.5
	  end
	when Sat_WorkHrs>0 and DATENAME(W,Date)=''''Saturday'''' then
		case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
		end
	WHEN (FNAttendanceCode=''''Present'''') THEN 0.5
	else 0.0
	END)+
	sum(CASE when PD.DATE= '''''' +CONVERT(varchar(20),@ThirdSaturday) + '''''' and Sat_WorkHrs=2 and DATENAME(W,Date)=''''Saturday'''' 
	then case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
		when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
	end
		when Sat_WorkHrs=0 and DATENAME(W,Date)=''''Saturday'''' then case	when FNAttendanceCode=''''Present''''	 
		and ANAttendanceCode=''''Present''''	 then 0.5
		when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Present''''    and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Present''''    then 0.5
   end
		when Sat_WorkHrs>0 and DATENAME(W,Date)=''''Saturday'''' then
		case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
		end
		WHEN (ANAttendanceCode=''''Present'''') THEN 0.5
		else 0.0
   END),							
		LateInMins			=	sum(isnull(LateInMins,0)),
		TotalLeaveDays		=  sum(CASE WHEN FNAttendanceCode=''''CL''''		THEN 0.5
										WHEN FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN 1
										WHEN FNAttendanceCode=''''LOP''''		THEN 0.5
										WHEN FNAttendanceCode=''''Absent''''	THEN 0.5
										WHEN FNAttendanceCode=''''SL''''		THEN 0.5
										WHEN FNAttendanceCode=''''CompOff''''	THEN 0.5
										else 0 
										END
										)+
								sum(CASE	WHEN ANAttendanceCode=''''CL''''		THEN 0.5
											WHEN ANAttendanceCode=''''LOP'''' and FNAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN ANAttendanceCode=''''LOP''''		THEN 0.5
											WHEN ANAttendanceCode=''''Absent''''	THEN 0.5
											WHEN ANAttendanceCode=''''SL''''		THEN 0.5
											WHEN ANAttendanceCode=''''CompOff''''	THEN 0.5
											else 0 
									END
									),
		OtherLeaveDays		=	sum(CASE	WHEN FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN FNAttendanceCode=''''LOP''''		THEN 0.5
											WHEN FNAttendanceCode=''''Absent''''	THEN 0.5
											else 0 
									END
									) + 
								sum(CASE	WHEN ANAttendanceCode=''''LOP'''' and FNAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN ANAttendanceCode=''''LOP''''		THEN 0.5
											WHEN ANAttendanceCode=''''Absent''''	THEN 0.5
											else 0 
									END
									),
			OverAllDeviations	=	convert(int,''+@DeviationColumns+''),
			''+@DeviationColumnsDisplay+''
	from TA_Tbl_ProcessedData PD 
	inner join FinalAttendanceSummary as fat on fat.Employee_Code_Id=PD.Employee_Code_Id
    where ((PD.date >= CONVERT(DATETIME,''''''+cast( @FromDateOld as nvarchar(50))+'''''', 102))
	AND (PD.date <= CONVERT(DATETIME,''''''+cast(@ToDateOld as nvarchar(50))+'''''', 102)))''
	If Not (@empId = '''')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' And PD.Employee_Code_Id = '''''' + @empId + '''''' ''  
		End
	Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' group by PD.Employee_Code_Id,''+@DeviationColumnsDisplay+'',''+@DeviationColumns
	execute(@sqlTempProcessedData1)
	--select * from #TempProcessedData
	--select @FromDateOld,@ToDateOld
	--select * from TA_Tbl_ProcessedData PD where Employee_Code_Id=''787''
	--and ((PD.date >= CONVERT(DATETIME,cast( @FromDateOld as nvarchar(50)), 102))
	--AND (PD.date <= CONVERT(DATETIME,cast(@ToDateOld as nvarchar(50)), 102)))
	Create table #TempFinal([Employee ID] varchar(50),[Emp.Name] varchar(100),[Level Name] varchar(250),
	[Present] decimal(18,1),[Leave] decimal(18,1),[Other Leave] decimal(18,1),Deviation decimal(18,1))
	insert into #TempFinal
	select 
	--ld.id,	
	PD.Employee_Code_Id as [Employee ID],
			FS.EmployeeName as [Emp.Name],
			ld.name as [Level Name],			
			NumberOfPresentDays as [Present],
			TotalLeaveDays as [Leave],
			OtherLeaveDays as [Other Leave],			
			(
				select	case	when OverAllDeviations =0 then 0
								when OverAllDeviations	between  starttime1		and		EndTime1	then Day1
								when OverAllDeviations	between  StartTime2		and		EndTime2	then Day2
								when OverAllDeviations	between  StartTime3		and		EndTime3	then Day3
								when OverAllDeviations	between  StartTime4		and		EndTime4	then Day4
								when OverAllDeviations	between  StartTime5		and		EndTime5	then Day5
								when OverAllDeviations	between  StartTime6		and		EndTime6	then Day6
								when OverAllDeviations	between  StartTime7		and		EndTime7	then Day7
								when OverAllDeviations	between  StartTime8		and		EndTime8	then Day8
								when OverAllDeviations	between  StartTime9		and		EndTime9	then Day9
								when OverAllDeviations	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Workhrs
			)+
			(
				select	case	when LateInMins =0 then 0
								when LateInMins	between  starttime1		and		EndTime1	then Day1
								when LateInMins	between  StartTime2		and		EndTime2	then Day2
								when LateInMins	between  StartTime3		and		EndTime3	then Day3
								when LateInMins	between  StartTime4		and		EndTime4	then Day4
								when LateInMins	between  StartTime5		and		EndTime5	then Day5
								when LateInMins	between  StartTime6		and		EndTime6	then Day6
								when LateInMins	between  StartTime7		and		EndTime7	then Day7
								when LateInMins	between  StartTime8		and		EndTime8	then Day8
								when LateInMins	between  StartTime9		and		EndTime9	then Day9
								when LateInMins	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Lateentry
			)AS [Deviation]
	from #TempProcessedData PD
	inner join FinalAttendanceSummary FS on PD.Employee_Code_Id=FS.Employee_Code_Id
	INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = PD.Employee_Code_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId
	INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id
	INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId
	order by ld.id,convert(int,pd.Employee_Code_Id)	
	select [Employee ID] ,[Emp.Name] ,[Level Name],[Present],[Leave] ,[Other Leave] ,Deviation,	Present+Leave-[Other Leave]-Deviation as
	[Tot.Worked]
	from #TempFinal
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	DROP TABLE #EmployeeIds
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #EmpPay		
	DROP TABLE FinalAttendanceSummary
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip_General]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip_General]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author        : R.Manikandan
-- Create date   : 29-June-2015
-- Modified date :  
-- Description   : <Description,,>  
-- exec [Proc_TA_RptPayslip_General] ''01/Dec/2015'',''31/Dec/2015'',''877'','''',''0'',''SuperAdmin'',''0'','''',0,0,''Both'',0,0,0
-- =============================================    
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip_General]
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(100),   
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
    @ParentId int,  
    @DesignationID int,  
	@Gender varchar(10),
	@employeeCategory int,  
	@employeeType int,
	@EmpAutoId BIGINT
)  
AS  
BEGIN
	SET NOCOUNT ON ;
	Declare @FromDateOld datetime
	Declare @ToDateOld datetime
	--set @FromDateOld=''01/July/2015''
	--set @ToDateOld=''31/July/2015''
	Declare @Difference int
	Declare @datepart int
	Declare @M int
	Set @M=0
	declare @month char(2)
	Declare @start varchar(20)
	declare @enddate varchar(20)
	select @Difference=DATEDIFF(d,@fromDat,@ToDat)/2
	while @M>=0
	begin
		select @datepart= DATEPART(d,DATEADD(d,@M,@fromDat))	
		if(@Difference=@datepart)
			begin
			set @month= DATEPART(MONTH,DATEADD(d,@M,@fromDat))
			set @month=	case	when LEN(@month)=1 then ''0''+CONVERT(char(2),@month)
								else CONVERT(char(2),@month)
						end
			set @start=convert(varchar(20),DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-01''
			if(@month in(1,3,5,7,8,10,12))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-31''
				end
			else if(@month in(4,6,9,11))
				begin
					set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-30''
				end
			else
				begin
					if(DATEPART(YEAR,@fromDat)/4=0)
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-29''
						end
					else
						begin
							set @enddate=convert(varchar(20),+DATEPART(YEAR,@fromDat))+''-''+CONVERT(varchar(20),@month)+''-28''
						end
				end
			set @M=-2
		end
		set @M=@M+1
	end
	set @FromDateOld=CONVERT(datetime,@start+'' 00:00:00.000'')
	set @ToDateOld=CONVERT(datetime,@enddate+'' 00:00:00.000'')
	--select @FromDateOld,@ToDateOld
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '''', @Query VARCHAR(MAX), @I INT = 1;
	declare @DeviationColumns VARCHAR(MAX) = '''';
	declare @DeviationColumnsDisplay VARCHAR(MAX) = '''';
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
	Declare @sqlEmpLevel nvarchar(max)
	Declare @sqlCommon nvarchar(max)	
	Declare @sqlEmpDesi nvarchar(max)
	Declare @sqlTempProcessedData varchar(max)	
	Declare @sqlCommonSwipeCardNo nvarchar(max)
	Declare @sqlTempProcessedData1 varchar(max)	
	Declare @sqlEmpCategory nvarchar(max)
	Declare @sqlEmpType nvarchar(max)	
	set @sqlCommon=''''
	--Creates the tepmoraray tables.
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200) ,  
		[EmployeeId] varchar(50),  	
		Present numeric(8,1),
		LeaveDays numeric(8,1),
		LopDays numeric(8,1),
		LateEntryNoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		sat_WorkHrs decimal(18,1),
		MonToSat_WorkHrs decimal(18,1),
		LessHoursWorked numeric(8,1),
		LateInMins int,
		TotalHrsEnteredInArmis numeric(8,1),
		TotalDefinedWorkHrs numeric(8,1),
		DaysNeedToDeduct_Late decimal(18,2) default(0.0),
		DaysNeedToDeduct_Armis decimal(18,2) default(0.0),
		DaysNeedToDeduct_Working decimal(18,2) default(0.0),
		TotalMinutesWorked int
	)	 	
    create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20),sat_WorkHrs decimal(18,1),MonToSat_WorkHrs decimal(18,1))
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  	
	create table #EmpGrade(Grade_Id int) 
    create table #EmpAttendanceDetails
    (	EmployeeID  varchar(50),
		Present numeric(8,1),
		TotalLateDays numeric(8,1),
		TotalLateInMins numeric(8,1),		
		LopDays numeric(8,1),
		LeaveDays numeric(8,1),
		NoOfDaysDeducted numeric(8,1),
		TotalWorkingDays int,
		TotalDefinedWorkHrsInMins int default(0),
		weeknumber int,
		TotalMinutesWorked int
	)      
    create table #TempProcessedData
    (
		Employee_Code_Id varchar(20),
		NumberOfPresentDays decimal(18,1),
		LateInMins int,
		TotalLeaveDays decimal(18,1),
		OtherLeaveDays decimal(18,1),
		OverAllDeviations varchar(20),
		NumberofDaysWorked as (NumberOfPresentDays+TotalLeaveDays-OtherLeaveDays),
		DeviationHoursFormat_Week1 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week2 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week3 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week4 varchar(30) default(''TC:00:00 A:00:00''),
		DeviationHoursFormat_Week5 varchar(30) default(''TC:00:00 A:00:00'')
	)   		
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID);
	--INSERT INTO @TempExecptionHrs
	--	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	--	WHERE [Date] BETWEEN @fromDat AND @ToDat
	--GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @fromDat, @ToDat)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @fromDat) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @fromDat)) != ''Sunday'' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT	@WeekName = ''Week'' + CAST(@I AS VARCHAR(10)),
			@DeviationColumns=@DeviationColumns+''+convert(int,isnull(DeviationHours_'' + @WeekName+'',0))'', 
			@DeviationColumnsDisplay=@DeviationColumnsDisplay+'',DeviationHoursFormat_'' + @WeekName ,
			@TableColumns = @TableColumns + '', TargetWorkHours_'' + @WeekName + '' VARCHAR(10), ActualWorkHours_'' + @WeekName + '' VARCHAR(10), ArmisWorkHours_'' + @WeekName + '' VARCHAR(10), [Leave_Permision_'' + @WeekName + ''] VARCHAR(10), 
	DeviationHours_'' + @WeekName + '' VARCHAR(30),DeviationHoursFormat_''+@WeekName+'' varchar(30)default(''''TC:00:00 A:00:00'''')'',@I = @I + 1 FROM WeekName
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]([Employee_Code_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]([Grade_Id] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[EmployeeId],[LevelId] ASC) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[EmployeeId],[DesignationId] ASC)ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[EmployeeId],[CategoryId])ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[EmployeeId],[TypeId]) ON [PRIMARY]  
	--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
	SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
	INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDat AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
	SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
	SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
	INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
	INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType 
	SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
	SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
	INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
	INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
	AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
	SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
	SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
	INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102)
	GROUP BY EmployeeId) EmpCategory
	INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
	AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
	INSERT INTO #EmpPay
	SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
	SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
	INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
	WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
	AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDat AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''FinalAttendanceSummary'')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC(''CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50),Sat_WorkHrs	numeric(18,1)'' + @TableColumns + '')'')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = ''Week'' + CAST(@I AS VARCHAR(10))		
		SELECT 
		@fromDat = Tbl1.WeekDates,
		@ToDat = Tbl2.WeekDates FROM (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
		INNER JOIN (
		SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
		WHERE Tbl1.Id = @I				
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10),WeekDay_WorkHrs decimal(18,1))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int,
		Sat_WorkHrs	numeric(18,1)
		)
		--Commented for local database
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
		SET @SQLQuery = ''SELECT * FROM 
		[ProjectManagementV3July16].[dbo].[Fn_GetProgressReport]('''''' + CAST(@fromDat AS VARCHAR(20)) + '''''','''''' + CAST(@ToDat AS VARCHAR(20)) + '''''''' + (CASE WHEN @empId = '''' OR @empId IS NULL THEN '', NULL)'' ELSE '', '' + @empId + '')'' END)
		--Commented for local database
		INSERT INTO @ArmisTable
		EXEC(@SQLQuery)			
		--select * from @ArmisTable
		SET @SQLQuery = ''SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END,''
		SET @SQLQuery = @SQLQuery + '' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''''''') +  SPACE(1) + ISNULL(E.Employee_LastName, '''''''') + ''''$'''' + REPLACE(LD.Name, ''''&amp;'''', ''''&''''), REPLACE(LD.Name, ''''&amp;'''', ''''&''''),''
		SET @SQLQuery = @SQLQuery + '' REPLACE(T.TitleName, ''''&amp;'''', ''''&''''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''''-''''), ISNULL(PD.OutTime, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' ISNULL(PD.HrsWork, ''''-''''), ((SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 4, 2))),''
		SET @SQLQuery = @SQLQuery + '' (S.Shift_ShortName + '''' ('''' + S.Shift_StartTime + '''' - ''''  + S.Shift_EndTime + '''')''''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' (CASE WHEN (ISNULL(PD.BreakIn, '''''''') = '''''''' OR ISNULL(PD.BreakOut, '''''''') = '''''''') AND PD.BreakHours <> ''''00:00'''' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')),ISNULL(SS.MaxWorkPlaceInHours, ''''00:10''''), NULL
		,C.WeekDay_WorkHrs*60.0 FROM Ta_Tbl_Employee E''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id''    
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId''   
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId ''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId ''
		set @SQLQuery = @SQLQuery + '' where 
		(
			(e.Employee_Status = 1) 
			or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102))
		) 	
		AND (e.Isdeleted = 0) AND (e.report_exclude = 0)''
		SET @SQLQuery = @SQLQuery + '' AND ((PD.date >= CONVERT(DATETIME, '''''' + CAST(@fromDat AS NVARCHAR(11)) + '''''', 102) 
		AND PD.Date <= CONVERT(DATETIME, '''''' + CAST(@ToDat AS NVARCHAR(11)) + '''''', 102)))''
		IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel + ''''
		END
		IF NOT(@EmployeeName = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_FirstName + '''' '''' + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName +''%'' AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@empId='''')  
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_Code_Id = '''''' + CAST(@empId AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmpSwipeCard = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND E.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		If (@Gender <> ''Both'')  
		Begin  
			Set @SQLQuery = @SQLQuery + '' And E.Gender = '''''' + @Gender + '''''' ''  
		End
		SET @SQLQuery = @SQLQuery + '' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)''   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		--select * from #TempAttendanceDetails 
		--UPDATE #TempAttendanceDetails SET
		--HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		--TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		--FROM #TempAttendanceDetails AD
		--RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDat) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
		WHERE #TempAttendanceDetails.Day = ''Saturday'' AND #TempAttendanceDetails.Date = @ThirdSat
		INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.CategoryName,
			TA.DefinedWorkHours,
			TA.DefinedWorkHours - SUM(
		(((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
		ELSE 
		0.0
		END
		) * 8,
		SUM(CAST(TA.TotalMinsWorked AS INT)),
		0,
		SUM(
		(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
		CASE WHEN C.Sat_WorkHrs > 4 THEN 
		((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
		(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
		WHEN C.Sat_WorkHrs = 2 THEN 
		(CASE 
		WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
		WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
		0.0 END)
		ELSE 
		(CASE
		WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
		WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
		0.0 END
		)
		END
		) * 8,
		0,
		CAST(MAX(TA.[Date]) AS DATE),
		0,0
		FROM #TempAttendanceDetails TA
		INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != ''Sunday''
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
		UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
		UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
		--Commented for local database
		UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
		INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id		
		UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
		--select 
		--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
		CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
		(ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
						(
							substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours)))*60
							+
							substring(convert(varchar(10),ArmisWorkHours),CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
							+ 
							[Leave_Permision] *60
							+ 
							(DefinedWorkHours - TargetWorkHours)*60
						)
					)
		ELSE 0 
		END,
		Sat_WorkHrs=C.Sat_WorkHrs
		FROM #TempAttendanceSummary TAS
		INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
		INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId where E.Isdeleted = 0 AND E.report_exclude = 0
--select * from #TempAttendanceSummary 
		SELECT	@WeekName AS WeekName,
				Employee_Code_Id,
				EmployeeName,
				CategoryName,
				REPLACE((TargetWorkHours - [Leave_Permision]), ''.'', '':'') AS TargetWorkHours,
				CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + '':'' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
				REPLACE(ArmisWorkHours, ''.'', '':'') AS ArmisWorkHours,
				REPLACE([Leave_Permision], ''.'', '':'') AS [Leave_Permision],
				case	when DeviationHours>ArmisDeviationHrs then	DeviationHours																
						when ArmisDeviationHrs>DeviationHours then	ArmisDeviationHrs
						when ArmisDeviationHrs=DeviationHours then	DeviationHours
				end AS DeviationHours,
				--DeviationHours AS DeviationHours,
				Sat_WorkHrs,				
			''TC:''+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			''A:''+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END as DeviationHoursInFormat
		INTO #TempFinalResult FROM #TempAttendanceSummary WHERE (DeviationHours != 0 or ArmisDeviationHrs != 0 OR 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = ''UPDATE FinalAttendanceSummary SET 
		Employee_Code_Id	= TR.Employee_Code_Id,
		EmployeeName		= TR.EmployeeName,
		CategoryName		= TR.CategoryName,
		TargetWorkHours_'' + @WeekName + '' = TR.TargetWorkHours,
		ActualWorkHours_'' + @WeekName + '' = TR.ActualWorkHours,
		ArmisWorkHours_'' + @WeekName + '' = TR.ArmisWorkHours,
		[Leave_Permision_'' + @WeekName + ''] = TR.[Leave_Permision],
		DeviationHours_'' + @WeekName + '' = isnull(TR.DeviationHours,0),
		Sat_WorkHrs=TR.Sat_WorkHrs,
		DeviationHoursFormat_'' + @WeekName + '' = TR.DeviationHoursInFormat
		 FROM FinalAttendanceSummary FAS
		INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName''
		EXEC(@SQLQuery)
		SET @SQLQuery = ''
		INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName,
		Sat_WorkHrs,TargetWorkHours_'' + @WeekName + '', ActualWorkHours_'' + @WeekName + '', ArmisWorkHours_'' + @WeekName + '', 
		[Leave_Permision_'' + @WeekName + ''], DeviationHours_'' + @WeekName + '', DeviationHoursFormat_'' + @WeekName +'')
		SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName,TR.Sat_WorkHrs,TR.TargetWorkHours, TR.ActualWorkHours, 
		TR.ArmisWorkHours, TR.[Leave_Permision],isnull(TR.DeviationHours,0),TR.DeviationHoursInFormat FROM #TempFinalResult TR
		LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
		WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL''
		EXEC(@SQLQuery)
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		--Commented for local database
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	--select * from FinalAttendanceSummary
	--Getting 3rd saturday date.
	Create table #Temp(date datetime,day varchar(max),id int)
	;with cte(Date,id,week) as 
	(	
		select @FromDateOld,1 as id,DATEPART(WEEK,@FromDateOld)
		union all
		select Date+1,id+1,DATEPART(WEEK,Date+1) from cte where Date < @ToDateOld
	)
	insert into #Temp select Date,DATENAME(W,Date)Day,id from cte
	option (MAXRECURSION 0)
	Declare @ThirdSaturday datetime	
	select @ThirdSaturday=date from(select *,ROW_NUMBER()over(order by id)as row from #Temp where day=''Saturday'')as a where row=3
	set	@DeviationColumnsDisplay=SUBSTRING(@DeviationColumnsDisplay,2,len(@DeviationColumnsDisplay))
	--select @DeviationColumns
	--select @DeviationColumnsDisplay
	--declare @alter varchar(max)
	--set @alter=''alter table #TempProcessedData add ''+replace(@DeviationColumnsDisplay,'','','' varchar(20),'')+'' varchar(20)''
	--Execute(@alter)
	set @sqlTempProcessedData1=  
	''insert into #TempProcessedData
	(Employee_Code_Id,NumberOfPresentDays,LateInMins,TotalLeaveDays,OtherLeaveDays,OverAllDeviations,''+@DeviationColumnsDisplay+'')
	select	Employee_Code_Id	=	PD.Employee_Code_Id,
	NumberOfPresentDays	=	sum(CASE when PD.DATE= '''''' +CONVERT(varchar(20),@ThirdSaturday) + '''''' 
	and Sat_WorkHrs=2 and DATENAME(W,Date)=''''Saturday'''' then 
	case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
			when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
	end
	 when Sat_WorkHrs=0 and DATENAME(W,Date)=''''Saturday'''' then 
	 case	when FNAttendanceCode=''''Present''''	 and ANAttendanceCode=''''Present''''	 then 0.5
			when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Present''''    and ANAttendanceCode=''''Weekly Off'''' then 0.5
			when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Present''''    then 0.5
	  end
	when Sat_WorkHrs>0 and DATENAME(W,Date)=''''Saturday'''' then
		case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
		end
	WHEN (FNAttendanceCode=''''Present'''') THEN 0.5
	else 0.0
	END)+
	sum(CASE when PD.DATE= '''''' +CONVERT(varchar(20),@ThirdSaturday) + '''''' and Sat_WorkHrs=2 and DATENAME(W,Date)=''''Saturday'''' 
	then case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
		when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
	end
		when Sat_WorkHrs=0 and DATENAME(W,Date)=''''Saturday'''' then case	when FNAttendanceCode=''''Present''''	 
		and ANAttendanceCode=''''Present''''	 then 0.5
		when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Present''''    and ANAttendanceCode=''''Weekly Off'''' then 0.5
		when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Present''''    then 0.5
   end		
		when Sat_WorkHrs>0 and DATENAME(W,Date)=''''Saturday'''' then
		case	when FNAttendanceCode=''''Present''''	  and ANAttendanceCode=''''Present''''	  then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Present''''     and ANAttendanceCode=''''Weekly Off'''' then 0.5
				when FNAttendanceCode=''''Weekly Off''''  and ANAttendanceCode=''''Present''''    then 0.5
		end
		WHEN (ANAttendanceCode=''''Present'''') THEN 0.5
		else 0.0
   END),							
		LateInMins			=	sum(isnull(LateInMins,0)),
		TotalLeaveDays		=  sum(CASE WHEN FNAttendanceCode=''''CL''''		THEN 0.5
										WHEN FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN 1
										WHEN FNAttendanceCode=''''LOP''''		THEN 0.5
										WHEN FNAttendanceCode=''''Absent''''	THEN 0.5
										WHEN FNAttendanceCode=''''SL''''		THEN 0.5
										WHEN FNAttendanceCode=''''CompOff''''	THEN 0.5
										else 0 
										END
										)+
								sum(CASE	WHEN ANAttendanceCode=''''CL''''		THEN 0.5
											WHEN ANAttendanceCode=''''LOP'''' and FNAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN ANAttendanceCode=''''LOP''''		THEN 0.5											
											WHEN ANAttendanceCode=''''Absent''''	THEN 0.5
											WHEN ANAttendanceCode=''''SL''''		THEN 0.5
											WHEN ANAttendanceCode=''''CompOff''''	THEN 0.5
											else 0 
									END
									),
		OtherLeaveDays		=	sum(CASE	WHEN FNAttendanceCode=''''LOP'''' and ANAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN FNAttendanceCode=''''LOP''''		THEN 0.5
											WHEN FNAttendanceCode=''''Absent''''	THEN 0.5
											else 0 
									END
									) + 
								sum(CASE	WHEN ANAttendanceCode=''''LOP'''' and FNAttendanceCode=''''Weekly Off'''' THEN 1
											WHEN ANAttendanceCode=''''LOP''''		THEN 0.5
											WHEN ANAttendanceCode=''''Absent''''	THEN 0.5
											else 0 
									END
									),
			OverAllDeviations	=	convert(int,''+@DeviationColumns+''),
			''+@DeviationColumnsDisplay+''
	from TA_Tbl_ProcessedData PD 
	inner join FinalAttendanceSummary as fat on fat.Employee_Code_Id=PD.Employee_Code_Id
    where ((PD.date >= CONVERT(DATETIME,''''''+cast( @FromDateOld as nvarchar(50))+'''''', 102))
	AND (PD.date <= CONVERT(DATETIME,''''''+cast(@ToDateOld as nvarchar(50))+'''''', 102)))''
	If Not (@empId = '''')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' And PD.Employee_Code_Id = '''''' + @empId + '''''' ''  
		End
	Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' group by PD.Employee_Code_Id,''+@DeviationColumnsDisplay+'',''+@DeviationColumns
	execute(@sqlTempProcessedData1)
	--select @FromDateOld,@ToDateOld
	--select * from TA_Tbl_ProcessedData PD where Employee_Code_Id=''787''
	--and ((PD.date >= CONVERT(DATETIME,cast( @FromDateOld as nvarchar(50)), 102))
	--AND (PD.date <= CONVERT(DATETIME,cast(@ToDateOld as nvarchar(50)), 102)))
	select	PD.Employee_Code_Id,
			FS.EmployeeName,
			--Fs.CategoryName,
			NumberOfPresentDays,
			TotalLeaveDays,
			OtherLeaveDays,			
			(
				select	case	when OverAllDeviations =0 then 0
								when OverAllDeviations	between  starttime1		and		EndTime1	then Day1
								when OverAllDeviations	between  StartTime2		and		EndTime2	then Day2
								when OverAllDeviations	between  StartTime3		and		EndTime3	then Day3
								when OverAllDeviations	between  StartTime4		and		EndTime4	then Day4
								when OverAllDeviations	between  StartTime5		and		EndTime5	then Day5
								when OverAllDeviations	between  StartTime6		and		EndTime6	then Day6
								when OverAllDeviations	between  StartTime7		and		EndTime7	then Day7
								when OverAllDeviations	between  StartTime8		and		EndTime8	then Day8
								when OverAllDeviations	between  StartTime9		and		EndTime9	then Day9
								when OverAllDeviations	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Workhrs
			)+
			(
				select	case	when LateInMins =0 then 0
								when LateInMins	between  starttime1		and		EndTime1	then Day1
								when LateInMins	between  StartTime2		and		EndTime2	then Day2
								when LateInMins	between  StartTime3		and		EndTime3	then Day3
								when LateInMins	between  StartTime4		and		EndTime4	then Day4
								when LateInMins	between  StartTime5		and		EndTime5	then Day5
								when LateInMins	between  StartTime6		and		EndTime6	then Day6
								when LateInMins	between  StartTime7		and		EndTime7	then Day7
								when LateInMins	between  StartTime8		and		EndTime8	then Day8
								when LateInMins	between  StartTime9		and		EndTime9	then Day9
								when LateInMins	between  StartTime10	and		EndTime10	then Day10
								else Day6
						end
				from ta_tbl_NoOfDaysDeduction_Lateentry
			)AS Deviations_DeductionDays,NumberofDaysWorked,			
			CASE WHEN LEN(CAST((OverAllDeviations/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((OverAllDeviations/60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((OverAllDeviations%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((OverAllDeviations%60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations%60) AS VARCHAR(25)) 
			END as OverAllDeviationsHrs,
			OverAllDeviations,LateInMins as TotalLateInMins,
			CASE WHEN LEN(CAST((LateInMins/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((LateInMins/60) AS VARCHAR(25)) 
				 ELSE CAST((LateInMins/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((LateInMins%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((LateInMins%60) AS VARCHAR(25)) 
				 ELSE CAST((LateInMins%60) AS VARCHAR(25)) 
			END as TotalLateHrs,
			''W1:''+
			pd.DeviationHoursFormat_Week1+''#W2:''+pd.DeviationHoursFormat_Week2+''#W3:''+pd.DeviationHoursFormat_Week3
			+''#W4:''+pd.DeviationHoursFormat_Week4+''#W5:''+pd.DeviationHoursFormat_Week5+''#Tot:''+
			CASE WHEN LEN(CAST((OverAllDeviations/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((OverAllDeviations/60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((OverAllDeviations%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((OverAllDeviations%60) AS VARCHAR(25)) 
				 ELSE CAST((OverAllDeviations%60) AS VARCHAR(25)) 
			END as DeviationPerWeek
	from #TempProcessedData PD
	inner join FinalAttendanceSummary FS on PD.Employee_Code_Id=FS.Employee_Code_Id
	order by convert(int,pd.Employee_Code_Id)
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  	
	DROP TABLE #EmployeeIds
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	DROP TABLE #EmpPay		
	DROP TABLE FinalAttendanceSummary
END   ' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayslip]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayslip]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================  
-- Author:  Senthil  
-- Create date: 21-Apr-08  
-- Description: payslip Report  
-- Proc_TA_RptPayslip ''24'',''151'','''',0,0,''0,1,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120'',''SuperAdmin'',''0''  
-- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_RptPayslip]  
 @MonthClosureID as nvarchar(5),  
 @EmployeeId nvarchar(100),   
 @EmployeeName nvarchar(50),  
 @EmpCategory int,  
 @EmpType int,  
 @LevelID nvarchar(1000),
 @UserGroupName varchar(250),
 @GradeLevel varchar(20)			    
AS  
BEGIN  
 Declare @ToDate as DateTime  
 set @ToDate = (select MonthClosure_EndDate from ta_tbl_monthclosure where MonthClosure_ID=@MonthClosureID)  
 declare @sqlQuery as varchar(8000) 
 declare @sqlQuery1 as varchar(8000)
 set @sqlQuery=''''
 set @sqlQuery1=''''
 set @sqlQuery = ''select TA_Tbl_Title.TitleName,TA_Tbl_PayrollProcessDetails.PayrollProcess_Id, TA_Tbl_PayrollProcessDetails.MonthClosure_Id, TA_Tbl_MonthClosure.MonthClosure_Month, TA_Tbl_MonthClosure.MonthClosure_Year, Ta_Tbl_Employee.Employee_Code_ID,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as EmployeeName,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_levelDetails.name, TA_Tbl_PayrollProcessDetails.DA, ''   
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.MonthlyWages,TA_Tbl_PayrollProcessDetails.WorkingDays,''  
 --set @sqlQuery = @sqlQuery + '' cast((TA_Tbl_PayrollProcessDetails.MonthlyWages/TA_Tbl_PayrollProcessDetails.WorkingDays)* (isnull(TA_Tbl_PayrollProcessDetails.PresentDays,0) + isnull(TA_Tbl_PayrollProcessDetails.PaidHolidays,0)) as int) as EmpWages,TA_Tbl_PayrollProcessDetails.WorkingDays,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.AbsentDays, TA_Tbl_PayrollProcessDetails.PaidHolidays, ''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.PresentDays as WorkedDays, TA_Tbl_PayrollProcessDetails.Wages,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,''  
    --set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.NormOT as OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.Incentive,TA_Tbl_PayrollProcessDetails.GrossWages,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.PF, TA_Tbl_PayrollProcessDetails.ESI,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.Mess,TA_Tbl_PayrollProcessDetails.OtherDeductions,''  
 set @sqlQuery = @sqlQuery + '' isnull(TA_Tbl_PayrollProcessDetails.Mess,0) + isnull(TA_Tbl_PayrollProcessDetails.OtherDeductions,0) + isnull(TA_Tbl_PayrollProcessDetails.PF,0) + isnull(TA_Tbl_PayrollProcessDetails.ESI,0) as TotalDeduction,''  
 set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.NetWages,''  
 set @sqlQuery = @sqlQuery + '' RoundUp = Case (Cast(TA_Tbl_PayrollProcessDetails.NetWages as int)%10) when 0 Then TA_Tbl_PayrollProcessDetails.NetWages Else (TA_Tbl_PayrollProcessDetails.NetWages + (10 - (Cast (TA_Tbl_PayrollProcessDetails.NetWages as int) %10))) End''  
 set @sqlQuery = @sqlQuery + '' from Ta_Tbl_employee inner join ta_tbl_payrollprocessDetails on Ta_Tbl_Employee.SwipeCardNo=ta_tbl_payrollprocessDetails.Employee_ID''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_MonthClosure on ta_tbl_payrollprocessDetails.MonthClosure_ID = TA_Tbl_MonthClosure.MonthClosure_Id''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
 set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID INNER JOIN''
 set @sqlQuery = @sqlQuery + '' dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
 set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
--    set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_levelDetails on Ta_Tbl_Employee.LevelID = TA_Tbl_levelDetails.id''  
--  
-- set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''  
-- set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''  
-- --set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''  
-- --set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''  
 set @sqlQuery = @sqlQuery + '' where (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) and (TA_Tbl_Employee.Employee_Code_Id<>''''18000000'''')''  
    set @sqlQuery = @sqlQuery + '' And (ta_tbl_payrollprocessDetails.MonthClosure_ID='' + @MonthClosureID + '')''  
set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(getdate() as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
 set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(getdate() as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
 set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(getdate() as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
 set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(getdate() as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)'' 
-- set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and  EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@Todate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''  
if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end
if not(@EmpCategory='''' or @EmpCategory=''0'')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ''and TA_Tbl_Employee.EmpCategory ='''''' + @EmpCategory + '''''' ''  
 end  
 if not(@EmpType='''' or @EmpType=''0'')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ''and TA_Tbl_Employee.EmpType ='''''' + @EmpType + '''''' ''  
 end  
 if not(@EmployeeName='''' or @EmployeeName=''0'')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + ''and TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''' ''  
 end   
 if not (@EmployeeId='''' or @EmployeeId=''0'')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''  
 end
 if not (@LevelID='''' or @LevelID=''0'')  
 begin     
  set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeLevel.LevelId IN ('' + @LevelId + '')'' 
 end
 exec(@sqlQuery + @sqlQuery1)   
END  
 set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptPayroll]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptPayroll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.manikandan>
-- Create date: <04-Jul-2019 11:21 am>
-- Description:	<Get the payroll details as per the client given format>
-- Proc_TA_RptPayroll ''2019/05/01'',''2019/05/30'','''','''',''SuperAdmin'',''0'',0,0,''Both'',0,0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptPayroll]
	@fromDat datetime,  
	@ToDat datetime,  
	@empId NVARCHAR(max),   
	@EmployeeName NVARCHAR(max),
	@UserGroupName NVARCHAR(250),  
	@GradeLevel NVARCHAR(20)  ,  
	@ParentId int,  
	@DesignationID int,  
	@Gender NVARCHAR(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
AS
BEGIN
	SET NOCOUNT ON
	CREATE TABLE #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),
		[Employee Id] NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		[Norm OT Hrs] numeric(8,1),
		[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),
		Others numeric(8,1),
		Total_Spec_NormOT1 int,
		[Sick Leave] numeric(8,1)
	)
	CREATE TABLE #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	CREATE TABLE #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50)) 
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	DECLARE @isReportingto AS INT
	
	CREATE TABLE #EmployeeIds(EmpAutoId int)
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    INSERT INTO  #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
    SELECT @isReportingto=ReportsBasedOn FROM TA_Tbl_Usergroup WHERE groupName=@UserGroupName
	CREATE TABLE #EmpAttendanceDetails
	(
		EmployeeID  NVARCHAR(50),
		Present numeric(8,1),
		Absent numeric(8,1),
		NormalOTHrs numeric(8,1),
		WeekOffOTHrs numeric(8,1),
		HolidayOTHours numeric(8,1),
		Leave Numeric(8,1),
		Total_Spec_NormOT1 int,
		[Sick Leave] numeric(8,1)
	)
	CREATE TABLE #LevelRights(LevelId int)
	CREATE TABLE #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id NVARCHAR(20),
		fnattendanceCode nvarchar(20),
		anattendanceCode nvarchar(20),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		Total_Spec_NormOT1 int,
		OtMins int
	)
	CREATE TABLE #TempEmployeeForProcessedData(EmpAutoId bigint,EmpSwipeCardNo NVARCHAR(20),EmployeeCodeId  NVARCHAR(50), EmployeeName nvarchar(200) ,Gender NVARCHAR(20)) 
	INSERT INTO  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @todat,@empId,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @todat,@empId,@EMPLOYEECATEGORY
	--To split up the comma separated values
	if(@empId is not null and @empId <> '''')
		begin
			create table #EmployeeID(EmployeeID NVARCHAR(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID NVARCHAR(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@empId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)	
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo=
	''insert into #TempEmployeeForProcessedData 
	select e.Employee_ID,e.SwipeCardNo, e.employee_code_id,isnull(Employee_FirstName,'''''''') + SPACE(1) + isnull(Employee_LastName,''''''''),e.Gender
	from TA_Tbl_Employee  e
	inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
	Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id 
	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''	
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' where SwipeCardNo is not null and e.Isdeleted=0 AND e.report_exclude = 0 ''
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' and (e.Employee_Status = 1  or  e.Employee_Status = 0 )''
	if(@UserGroupName<>''SuperAdmin'')  
		begin  
			set @sqlCommonSwipeCardNo=@sqlCommonSwipeCardNo+'' AND TA_Tbl_Grade.Grade_Level >='''''' + cast(@GradeLevel as nvarchar(8)) + '''''' ''
		end  
	if(@Gender<>''Both'')  
		begin  
			set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end   
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	execute(@sqlCommonSwipeCardNo)	
	insert into #TempProcessedData 
	select	#TempEmployeeForProcessedData.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			case when PD.OvertimeStatus=''Approved'' then ISNULL(sot.Modified_Spec_NormOTMins1,PD.SPEC_NormOTMins1) end,
			PD.OtMins
	FROM TA_Tbl_ProcessedData PD
	INNER JOIN #TempEmployeeForProcessedData on #TempEmployeeForProcessedData.EmpSwipeCardNo=PD.Employee_Code_Id  
	INNER JOIN TA_Tbl_Employee E on E.SwipeCardNo=#TempEmployeeForProcessedData.EmpSwipeCardNo
	Left outer join Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=PD.Employee_Code_Id and sot.Date=PD.Date)
	WHERE (PD.date >= CONVERT(DATETIME,@fromDat, 102)) AND (PD.date <= CONVERT(DATETIME,@ToDat, 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date) or (E.Employee_Status=1))
	
	INSERT INTO #TempDetailedAttendance([Employee Id],[Employee Name]) 
	SELECT DISTINCT EmployeeCodeId,EmployeeName FROM #TempEmployeeForProcessedData	
	
	INSERT INTO #EmpAttendanceDetails 
	SELECT TPD.Employee_code_Id,  
			Present= 
			sum
			(
				CASE	WHEN FNAttendanceCode=''Present''	 AND ANAttendanceCode=''Present''	THEN 1.0
						WHEN FNAttendanceCode=''Holiday''  AND  ANAttendanceCode=''Holiday''	THEN 1.0
						WHEN FNAttendanceCode=''Present''  AND  ANAttendanceCode!=''Present'' THEN 0.5
						WHEN FNAttendanceCode!=''Present'' AND  ANAttendanceCode=''Present'' THEN 0.5
						WHEN FNAttendanceCode=''Comp Off'' AND  ANAttendanceCode=''Comp Off''THEN 1.0
						WHEN FNAttendanceCode=''BL'' AND  ANAttendanceCode=''BL''			THEN 1.0
						ELSE 0.0
				END
			),
			Absent=
			sum
			(
				CASE	WHEN FNAttendanceCode=''Absent''	AND  ANAttendanceCode=''Absent''	THEN 1.0 
						WHEN FNAttendanceCode=''Absent''	AND  ANAttendanceCode!=''Absent''	THEN 0.5
						WHEN FNAttendanceCode!=''Absent'' AND  ANAttendanceCode=''Absent''	THEN 0.5
						WHEN FNAttendanceCode IS NULL AND  ANAttendanceCode IS NULL		THEN 1 
						ELSE 0.0
				END
			), 
			[Norm OT Hrs]		=SUM(CASE WHEN ISNULL(NormOt,''00:00'')=''00:00''	THEN 0 ELSE OtMins END),
			[WeekOff OT Hrs]	=SUM(CASE WHEN ISNULL(OffOT,''00:00'')=''00:00''	THEN 0 ELSE OtMins END),
			[Holiday OT Hrs]	=SUM(CASE WHEN ISNULL(HolOT,''00:00'')=''00:00''	THEN 0 ELSE OtMins END), 
			''Leave''=SUM(CASE WHEN FNAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 0.5 else 0 END) + 
					SUM(CASE WHEN ANAttendanceCode not in(''Absent'',''Present'',''Holiday'',''Weekly Off'') THEN 0.5 else 0 END), 
			isnull(SUM(TPD.Total_Spec_NormOT1),0),
			sum
			(
				CASE	WHEN FNAttendanceCode=''SL''	 AND ANAttendanceCode=''SL''	THEN 1.0
						WHEN FNAttendanceCode=''SL''  AND  ANAttendanceCode!=''SL'' THEN 0.5
						WHEN FNAttendanceCode!=''SL'' AND  ANAttendanceCode=''SL'' THEN 0.5
						ELSE 0.0
				END
			)			
			from #TempProcessedData  TPD
			INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = TPD.EmpAutoId  
			INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = TPD.EmpAutoId 
			Inner join #TempDetailedAttendance TDA on TDA.[Employee Id]=TPD.Employee_Code_Id			
			group by TPD.Employee_Code_ID
			
				
	update #TempDetailedAttendance set Present = TEAD.Present,
	Absent = TEAD.Absent,  
	[Norm OT Hrs]		= TEAD.NormalOTHrs,
	[WeekOff OT Hrs]	= TEAD.WeekOffOTHrs,  
	[Holiday OT Hrs]	= TEAD.HolidayOTHours,
	Total_Spec_NormOT1	=TEAD.Total_Spec_NormOT1,
	[Sick Leave]=TEAD.[Sick Leave]
	from #EmpAttendanceDetails TEAD 
	inner join #TempDetailedAttendance on TEAD.EmployeeID=#TempDetailedAttendance.[Employee Id]
	
	--Inserts the Others details in the temporary table  
	--declare @SqlOthers NVARCHAR(4000)  
	--create table #Others(SwipeCardNo  NVARCHAR(50),Others numeric(8,1))  
	--Insert into #Others 
	--select Employee_Code_Id ,	
	--sum
	--(
	--	CASE	WHEN (FNAttendanceCode=''RH'' or FNAttendanceCode=''LOP'') THEN 0.5
	--			ELSE 0 
	--	END
	--)+ 
	--sum
	--( 
	--	CASE WHEN (ANAttendanceCode=''RH'' or ANAttendanceCode=''LOP'') THEN 0.5
	--		 ELSE 0 
	--	END
	--)
	--from #TempProcessedData where Employee_Code_Id in(select [Employee Id] from #TempDetailedAttendance)
	--group by Employee_Code_ID
	
	--Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype NVARCHAR(10) )  
	
	--INSERT INTO #tempLeaveTypeforOthers 
	--SELECT LT.LeaveType FROM Ta_Tbl_LeaveType LT
	--LEFT OUTER JOIN #tempLeavetype TLT on LT.LeaveType=TLT.Leavetype
	--WHERE TLT.Leavetype is null
	
	select 	
		[Employee Id],
		--[Employee Name],		
		Present=isnull(Present,0),
		[Sick Leave]=isnull([Sick Leave],0),
		--Absent=ISNULL(Absent,0),		
		[Daytime OT Hours]=dbo.ConvertMinsToHours([Norm OT Hrs]),
		[Nighttime OT Hours]=dbo.ConvertMinsToHours(Total_Spec_NormOT1),
		[Holiday OT Hours]=dbo.ConvertMinsToHours([WeekOff OT Hrs]+[Holiday OT Hrs]),		
		'''' Remarks
	from #TempDetailedAttendance	
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpAttendanceDetails  
	--drop table #Others  
	--drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployeeForProcessedData  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceLabour]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendanceLabour]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
[Proc_TA_RptMonthlyAttendanceLabour] @MINWORKHOURS=N'''',@FROMDAT=''2019-01-01 00:00:00'',@TODAT=''2019-01-31 00:00:00'',
@EMPLOYEENAME=N''Manikandan ,Sathishkumar ,'',@LEVELID=N''19'',@EMPLOYEEID=N''787,758,'',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N''SUPERADMIN'',
@GRADELEVEL=N''0'',@EMPSWIPECARD=N'''',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N''BOTH'',@SHIFT=0,@DATALOADING=0,@EMPAUTOID=0,@EXPORT=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceLabour]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId int,
	@Export int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT))  
	
	
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,HrsWork nvarchar(10),SupposedWorkHours nvarchar(10),Status nvarchar(50),Attendance nvarchar(20),anAttendanceCode nvarchar(15),fnAttendanceCode nvarchar(15),PrevShift_ID int,Process_Rec_ID bigint,Exactshift_StartTime nvarchar(25),Shift_Secondhalf_startTime datetime,LateInmin	nvarchar(10),EarlyOut nvarchar(10),LateIn nvarchar(10),NormOT nvarchar(10),OffOT nvarchar(10),HolOT nvarchar(10),OtMins float,EarlyOutMin nvarchar(10),overtimeStatus varchar(20),NightOrMorn int)
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END		
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF not(@local_GENDER=''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@local_GENDER AS NVARCHAR(8)) + '''''' ''  
	END		
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@local_TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@local_EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	IF NOT (@local_EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	
	Declare @sqlEmpDesi nvarchar(4000)

	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY

	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  	
	Declare @sqlTempProcessedData varchar(8000)

	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id where SwipeCardNo is not null'' 
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sqlTempProcessedData = @sqlTempProcessedData + '' And SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End	
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	''insert into #TempProcessedData 
	select	#TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,
			TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork,TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.anAttendanceCode,TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Process_Rec_ID,S.Shift_startTime,cast(S.Shift_Secondhalf_startTime as datetime)
	,LateInMins,EarlyOut,LateIn,TA_Tbl_ProcessedData.NormOT,TA_Tbl_ProcessedData.OffOT,TA_Tbl_ProcessedData.HolOT,OtMins,EarlyOutMins,OvertimeStatus,0
	from TA_Tbl_ProcessedData inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id  
	left outer join ta_tbl_shift S on S.Shift_Id=TA_Tbl_ProcessedData.Shift_Id	
	where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,''''''+cast( @local_FROMDAT as nvarchar(50))+'''''', 102))    
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''''''+cast(@local_TODAT as nvarchar(50))+'''''', 102))'' 
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' And TA_Tbl_ProcessedData.Employee_Code_Id = '''''' + @EmpSwipeCard + '''''' ''  
		End
	Execute(@sqlTempProcessedData1)
	
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode=''CL'' 	
	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@local_FROMDAT as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@local_TODAT as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@local_FROMDAT as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@local_TODAT as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)=''AM'' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)=''AM'' and SUBSTRING(S.Shift_Endtime,7,8)=''PM'' and PD.OutTime>''00:00 AM'' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id

	declare @pos as int  
	set @pos = charindex('':'',@local_MINWORKHOURS)  
	declare @TotalMin as int  
	set @TotalMin = substring(@local_MINWORKHOURS,0,@pos)*60 + substring(@local_MINWORKHOURS,@pos+1,2)  

	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),Date varchar(30),InTime varchar(30),OutTime varchar(30),HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),TotalMinsWorked varchar(30),Shift_ShortName varchar(20),shift_TotalWorkingHours varchar(20),Gender nvarchar(10),EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),NightOrMorn int)
	
	if (@local_MINWORKHOURS<>'''')  
		begin  
			declare @sqlQueryTemp as varchar(max)    
			set @sqlQueryTemp=''''   
			set @sqlQueryTemp =  ''select pd.Employee_Code_Id as SwipeCardNo,pd.date as Date,((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalWorkMins from Ta_Tbl_Employee e ''
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpDesignation EDesig on e.employee_id = EDesig.EmployeeId ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''  
			Set @sqlQueryTemp = @sqlQueryTemp + '' Left JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id ''
			set @sqlQueryTemp = @sqlQueryTemp + '' where  (	(e.Employee_Status = 1) or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102)
			)) AND (e.Isdeleted = 0) AND (e.report_exclude = 0)''
			insert into #EmpProcessedData exec(@sqlQueryTemp)  
		end
	
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''''    	
	set @sqlQuery = ''select  
	CASE	WHEN PD.FNATTENDANCECODE=''''PRESENT'''' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''FN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END 
			ELSE PD.FNATTENDANCECODE
	END as FirstSession,
	CASE	WHEN PD.ANATTENDANCECODE =''''PRESENT'''' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''AN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END  
			ELSE PD.ANATTENDANCECODE
	END as SecondSession, 
	e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''''Weekly Off'''' and anAttendanceCode=''''Weekly Off'''' then	''''-'''' 
	when pd.fnAttendanceCode=''''Holiday''''or anAttendanceCode=''''Holiday'''' then ''''-''''
	else pd.SupposedWorkHours end ''''SupposedWorkHours'''',(pd.Attendance +  CASE pd.Status WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + isnull(pd.Status,'''''''')) as Status,((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked''  
	set @sqlQuery = @sqlQuery + '' ,(CASE pd.Shift_Id WHEN ''''-1'''' THEN ''''Weekly Off'''' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN ''''-'''' 
						 when pd.Shift_Id=-1 then ''''-''''
						 ELSE shf.shift_TotalWorkingHours END
				),''''00:00''''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''''00:00'''' end Overtime,
	CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''NormOTMins'''',
	CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''WeekOffOTMins'''',
	CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''HolidayOTMins'''',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('''':'''',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('''':'''',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('''':'''',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('''':'''',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''''-'''' else OvertimeStatus end,NightOrMorn ''  
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	if (@local_MINWORKHOURS<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + '' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id''  
		end   
		set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, '''''' + cast(@local_FROMDAT as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@local_TODAT as nvarchar(11)) + '''''', 102)))''    
	if(@local_USERGROUPNAME<>''SuperAdmin'')  
		begin  
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GRADELEVEL + ''''  
		end
	if(@Shift<>0)  
		begin  
			Set @sqlQuery = @sqlQuery + '' AND pd.shift_id= ''+  cast (@Shift as nvarchar(50))  + ''''  
		end
	if (@local_MINWORKHOURS<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and #EmpProcessedData.TotalWorkMins >= '' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''     	
	
	insert into #TempMonthlyAttendance exec(@sqlQuery)
	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession=''Present'' OR FirstSession=''*Present'' OR FirstSession=''Holiday'' OR FirstSession=''*Holiday'' OR FirstSession=''Weekly Off'' OR FirstSession=''*Weekly Off'') and ME.ManualTimeEntry_InTime IS NOT NULL then  FirstSession+'' #''	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id and isnull(ME.ManualTimeEntry_Id,0)<>0 
	and (ME.ManualTimeEntry_InDate=#TempMonthlyAttendance.Date) and isnull(ME.IsOnDuty,0)=0 
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status=''Approved''	
	and (cast(#TempMonthlyAttendance.Date+CONVERT(datetime,#TempMonthlyAttendance.InTime) as datetime)=cast(Me.ManualTimeEntry_InDate+CONVERT(datetime,Me.ManualTimeEntry_InTime) as datetime))
		
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession=''Present'' OR SecondSession = ''*Present'' OR SecondSession =''Holiday'' OR SecondSession =''*Holiday'' OR SecondSession =''Weekly Off'' OR SecondSession =''*Weekly Off'')  and ME.ManualTimeEntry_OutTime IS NOT NULL  then  SecondSession+'' #''
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id and isnull(ME.ManualTimeEntry_Id,0)<>0 
	and ME.ManualTimeEntry_OutDate=#TempMonthlyAttendance.Date 
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status=''Approved''	
	and isnull(ME.IsOnDuty,0)=0 and (cast( #TempMonthlyAttendance.Date+convert(datetime,#TempMonthlyAttendance.OutTime) as datetime)=cast(Me.ManualTimeEntry_OutDate+CONVERT(datetime,Me.ManualTimeEntry_OutTime) as datetime))

	update #TempMonthlyAttendance set SecondSession=case when (SecondSession=''Present'' OR SecondSession = ''*Present'' OR SecondSession =''Holiday'' OR SecondSession =''*Holiday'' OR SecondSession =''Weekly Off'' OR SecondSession =''*Weekly Off'')  and ME.ManualTimeEntry_OutTime IS NOT NULL  then  SecondSession+'' #''
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance 
	inner join TA_Tbl_ManualTimeEntry ME ON #TempMonthlyAttendance.Employee_Id=ME.ManualTimeEntry_Employee_Id 	
	and ME.ManualTimeEntry_OutDate=dateadd(d,1,#TempMonthlyAttendance.Date)	
	--Added by Manikandan. on 18-09-2014 07:31 PM
	and ME.Isdeleted=0 and ManualTimeEntry_Status=''Approved''	
	and (cast( dateadd(d,1,#TempMonthlyAttendance.Date)+convert(datetime,#TempMonthlyAttendance.OutTime) as datetime)=cast(Me.ManualTimeEntry_OutDate+CONVERT(datetime,Me.ManualTimeEntry_OutTime) as datetime))
	and NightOrMorn=1	
		 
	select 
		Employee_Id,
		empName,
		Date,
		CASE WHEN Shift_ShortName=''Weekly Off'' THEN ''Off'' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
		InTime,
		OutTime,
		[Shift Hours]=shift_TotalWorkingHours,
		'''' as BreakHours,
		HrsWork,
		LateIn,
		EarlyOut,
		NormOT,
		OffOT,
		HolOT,		
		FirstSession,		
		SecondSession ,
		SupposedWorkHours,
		---
		BranchName,
		Designation,
		Status,
		convert(int,isnull(TotalMinsWorked,''0''))TotalMinsWorked,
		Gender,
		overtime,
		NormOTMin,
		OffOTMin,
		HolOTMin,
		lateinMin,
		EarlyOutMin,
		TotDefWorkHrs,
		TotSupWorkHrs,
		overtimeStatus ,
		shift_TotalWorkingHours
	from #TempMonthlyAttendance order by Employee_Id,Date
	
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
Modified by gopinath on 19Jun15, for adding the break time in report   
Proc_TA_RptMonthlyAttendance_Dashboard '''',''29/May/2018'',''29/May/2018'','''',''0'',''B001273'',0,0,''uiStaff'',''4'','''',0,0,''Both'',0,0,3
Proc_TA_RptMonthlyAttendanceDashboard_Surguru '''',''2019-09-05 00:00:00.000'',''2019-09-05 00:00:00.000'','''',''110'','''',0,0,''SuperAdmin'',''0'','''',110,0,''Both'',0,0,0,115
*/
 --select * from TA_Tbl_ProcessedData where Employee_Code_Id in (''3210'',''3211'',''3212'',''3213'') and date=''20190905''
--select * from ta_tbl_levelDetails
--select * from testmontylysurguru
--Delete from testmontylysurguru
--create table testmontylysurguru (
--	MinWorkHours  nvarchar(10),
--	fromDat datetime,
--	ToDat datetime,
--	EmployeeName varchar(max),
--	LevelID varchar(8000),
--	EmployeeId varchar(max),
--	employeeCategory int,
--	employeeType int,
--	UserGroupName varchar(250),
--	GradeLevel varchar(20),
--	EmpSwipeCard varchar(20),
--	ParentId int,
--	DesignationID int,
--	Gender varchar(10),
--	Shift int,
--	DataLoading int,
--	EmpAutoId bigint,
--	workLocation int
--	)
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendanceDashboard_Surguru]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId bigint,
	@workLocation int
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	--Temporary table''s creation  
	insert into testmontylysurguru  values(
	@MinWorkHours,
	@fromDat,
	@ToDat,
	@EmployeeName,
	@LevelID,
	@EmployeeId,
	@employeeCategory,
	@employeeType,
	@UserGroupName,
	@GradeLevel,
	@EmpSwipeCard,
	@ParentId,
	@DesignationID,
	@Gender,
	@Shift,
	@DataLoading,
	@EmpAutoId
	,@workLocation 
	)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsWork nvarchar(10),
		SupposedWorkHours nvarchar(10),
		Status nvarchar(50),
		Attendance nvarchar(20),
		anAttendanceCode nvarchar(15),
		fnAttendanceCode nvarchar(15),
		PrevShift_ID int,
		Process_Rec_ID bigint,
		Exactshift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		LateInmin	nvarchar(10),
		EarlyOut nvarchar(10),
		LateIn nvarchar(10),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		OTMINS decimal(18,0),
		EarlyOutMin int,
		overtimeStatus varchar(20),
		NightOrMorn int
		,InNotation char(1),
		OutNotation char(1),
		BreakHours varchar(20),
		LunchHours varchar(20),
		BreakHoursMins int,
		LunchHoursMins int
		,Skills varchar(max)
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Date],[Employee_Code_Id] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] 
	) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId]
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId]
	)ON [PRIMARY]  
	Declare @sqlEmpLevel nvarchar(4000)
	--insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	--insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	--insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(100)) + '''''')''
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
	Execute(@sqlEmpCategory)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF(@GENDER<>''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' ''  
	END	
	if(@isReportingto > 0)
    BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + '' and (EMP.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '' 
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.SwipeCardNo ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.SwipeCardNo ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	''insert into #TempProcessedData 
	select	#EMPLEVEL.EMPLOYEEID,
			TA_Tbl_ProcessedData.Date,
			TA_Tbl_ProcessedData.Employee_Code_Id,
			TA_Tbl_ProcessedData.intime,
			TA_Tbl_ProcessedData.outtime,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.HrsWork,
			TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,
			TA_Tbl_ProcessedData.Attendance,
			TA_Tbl_ProcessedData.anAttendanceCode,
			TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.Process_Rec_ID,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime)
			,LateInMins,
			EarlyOut,
			LateIn,
			TA_Tbl_ProcessedData.NormOT,
			TA_Tbl_ProcessedData.OffOT,
			TA_Tbl_ProcessedData.HolOT,
			OtMins,
			case when charindex(''''.'''',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex(''''.'''',convert(varchar(20),EarlyOutmins))))
			else EarlyOutmins end,
			OvertimeStatus,
			0,
			InNotation,
			OutNotation,
			BreakHrs,
			LunchHrs,
			BreakHrsInMins,
			LunchHrsInMins,
			((case when len(customfield1)>0 then convert(varchar(100),customfield1)+''''#'''' else '''''''' End) +
			(case when len(customfield2)>0 then convert(varchar(100),customfield2) +''''#'''' else '''''''' End) +
			(case when len(customfield3)>0 then convert(varchar(100),customfield3) +''''#'''' else '''''''' End) +
			(case when len(customfield4)>0 then convert(varchar(100),customfield4)+''''#'''' else '''''''' End) +
			(case when len(customfield5)>0 then convert(varchar(100),customfield5) +''''#'''' else '''''''' End)) 
			as Skills
			FROM TA_TBL_PROCESSEDDATA 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID
	inner join ta_tbl_Employee EM on EM.SwipeCardNo = TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID
	left outer join TA_tbl_ShiftAdd_Location LOC on LOC.employeeId = EM.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102)
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102))
	'' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND TA_Tbl_ProcessedData.shift_id= ''+  cast (@Shift as nvarchar(50))
		end	
	if(@workLocation<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND LOC.LocationId= ''+  cast (@workLocation as nvarchar(50))
		end	
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode=''CL'' 	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)=''AM'' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)=''AM'' and SUBSTRING(S.Shift_Endtime,7,8)=''PM'' and PD.OutTime>''00:00 AM'' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id
	declare @pos as int  
	set @pos = charindex('':'',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),
	Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),
	Date datetime,InTime varchar(30),OutTime varchar(30),
	HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),
	TotalMinsWorked varchar(30),Shift_ShortName varchar(20),
	shift_TotalWorkingHours varchar(20),Gender nvarchar(10),
	EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),
	NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),
	OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,
	TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),
	NightOrMorn int,LunchInTime nvarchar(20),LunchOutTime nvarchar(20)
	,InNotation char(1),OutNotation char(1)
	,BreakHours varchar(20),LunchHours varchar(20),
	BreakHoursMins int,LunchHoursMins int,
	Shift_StartTime	nvarchar(10),
	Shift_EndTime	nvarchar(10)
	,Skills nvarchar(max)
	)
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''''    	
	set @sqlQuery = ''select  pd.fnAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''''FN'''',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''''''' else ''''(BL)'''' end as FirstSession
	,pd.anAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''''AN'''',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''''''' else ''''(BL)'''' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''''Weekly Off'''' and anAttendanceCode=''''Weekly Off'''' then	''''-'''' 
	when pd.fnAttendanceCode=''''Holiday''''or anAttendanceCode=''''Holiday'''' then ''''-''''
	else pd.SupposedWorkHours end ''''SupposedWorkHours'''',(pd.Attendance +  CASE pd.Status WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + isnull(pd.Status,'''''''')) as Status,((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked''  
	set @sqlQuery = @sqlQuery + '' ,(CASE pd.Shift_Id WHEN ''''-1'''' THEN ''''Weekly Off'''' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN ''''-'''' 
						 when pd.Shift_Id=-1 then ''''-''''
						 ELSE shf.shift_TotalWorkingHours END
				),''''00:00''''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''''00:00'''' end Overtime,
	CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''NormOTMins'''',
	CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''WeekOffOTMins'''',
	CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''HolidayOTMins'''',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('''':'''',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('''':'''',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('''':'''',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('''':'''',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''''-'''' else OvertimeStatus end,NightOrMorn,''''00:00'''',''''00:00'''',InNotation,OutNotation,PD.BREAKHOURS,LunchHours,BreakHoursMins,LunchHoursMins,
	Shift_StartTime,Shift_EndTime, pd.Skills
	 ''
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + '' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id''  
		end   
		set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''    
	if(@Gender<>''Both'')  
		begin  
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end		
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')  
		begin  
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''  
		end	
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and #EmpProcessedData.TotalWorkMins >= '' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''     	
	insert into #TempMonthlyAttendance exec(@sqlQuery)	
	Create table #TempOutPunches
	(
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_Date] [datetime] NULL,
		PunchType varchar(20)
	)
	insert into #TempOutPunches
	select Clk_EmpId,min(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_OutPunchType in(''Lunch Out'')	
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,max(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_InPunchType in(''Lunch In'')	
	group by Clk_EmpId,Clk_Date,Clk_InPunchType	
	update #TempMonthlyAttendance set LunchInTime=case when PunchType=''Lunch In'' then TP.Clk_OutTime else TM.LunchInTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType=''Lunch In''
	update #TempMonthlyAttendance set LunchOutTime=case when PunchType=''Lunch Out'' then TP.Clk_OutTime else TM.LunchOutTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType=''Lunch Out''	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession=''Present'' OR FirstSession=''*Present'' OR FirstSession=''Holiday'' OR FirstSession=''*Holiday'' OR FirstSession=''Weekly Off'' OR FirstSession=''*Weekly Off'') and InNotation=''M'' then  FirstSession+'' #''	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession=''Present'' OR SecondSession = ''*Present'' OR SecondSession =''Holiday'' OR SecondSession =''*Holiday'' OR SecondSession =''Weekly Off'' OR SecondSession =''*Weekly Off'')  and OutNotation=''M'' then  SecondSession+'' #''
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	select 
	case	when (@TimeFormat)=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchInTime,0)), 114)
			else	substring(LunchInTime,13,5)+'' '' + substring(LunchInTime,18,2) 					
	end LunchIn,
	case	when (@TimeFormat)=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchOutTime,0)), 114)
			else	substring(LunchOutTime,13,5)+'' '' + substring(LunchOutTime,18,2) 					
	end LunchOut
	,FirstSession,SecondSession ,Employee_Id,empName,BranchName,Designation,
	case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
	else CONVERT(VARCHAR, Date, @dateFormat) end AS
	Date,
	InTime,OutTime,HrsWork,SupposedWorkHours,
	Status,convert(int,isnull(TotalMinsWorked,''0''))TotalMinsWorked,CASE WHEN Shift_ShortName=''Weekly Off'' THEN ''Off'' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
	shift_TotalWorkingHours,Gender,EarlyOut,LateIn,overtime,NormOTMin,OffOTMin,HolOTMin,NormOT,OffOT,HolOT,
	convert(int,lateinMin)as lateinMin,
	convert(int,EarlyOutMin)as EarlyOutMin,TotDefWorkHrs,TotSupWorkHrs,overtimeStatus,BreakHoursMins,
	BreakHours=isnull(BreakHours,''-''),LunchHoursMins,LunchHours=isnull(LunchHours,''-''),
	Shift_StartTime,Shift_EndTime, Skills,
	(
	case
	when (b.Onduty_EmployeeID) <> 0 and Status=''Present'' then ''On Duty'' 
 	when (Status=''Present'') then ''Present'' 
	when  (FirstSession not in(''Present #'',''Absent'',''Weekly Off'',''Holiday'',''RH'',''Present'')
	     or SecondSession not in(''Present  #'',''Absent'',''Weekly Off'',''Holiday'',''RH'',''Present'')) then ''Leave''
	when (Status=''Absent'') then ''Absent''
	End
	) 
	as AttendanceType
	from #TempMonthlyAttendance 
	left outer join TA_Tbl_OndutyEntry b on b.Onduty_EmployeeID = #TempMonthlyAttendance.Employee_Id
	order by AttendanceType
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Detail]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    Script Date: 12/24/2013 14:17:35 ******/
/*
Proc_TA_RptMonthlyAttendance_Detail '''',''01/Feb/2015'',''28/Feb/2015'','''',''0,22'','''',0,0,''SuperAdmin'',''0'','''',0,0,''Both'',0,2
exec Proc_TA_RptMonthlyAttendance_Detail @MinWorkHours=N'''',@fromDat=''2014-10-01 00:00:00'',@ToDat=''2014-10-31 00:00:00'',
@EmployeeName=N'''',@LevelID=N''0'',@EmployeeId=N''1111,'',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',
@GradeLevel=N''0'',@EmpSwipeCard=N'''',@ParentId=0,@DesignationID=0,@Gender=N''Both'',@Shift=0,@DataLoading=0
*/    
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Detail]    
 @MinWorkHours as varchar(10),   
 @fromDat datetime,    
 @ToDat datetime,    
 @EmployeeName varchar(max),    
 @LevelID varchar(8000),  
 @EmployeeId varchar(max),  
 @employeeCategory int,  
 @employeeType int,  
 @UserGroupName varchar(250),  
 @GradeLevel varchar(20),      
 @EmpSwipeCard varchar(20),  
 @ParentId int, 
@DesignationID int,  
@Gender varchar(10),
@Shift int ,
@DataLoading int,
@EmpAutoID int
AS    
BEGIN    
	SET NOCOUNT ON;
	Declare @Fromdate1 datetime
	set @Fromdate1 = @fromDat
	Declare @Count int
	declare @Diff int
	Declare @SQLDays nvarchar(2000)
	Declare @SQL nvarchar(max)
	Declare @SQLAttnDay nvarchar(max)
	Declare @SQLShiftDay nvarchar(max)
	Declare @SQLInDay nvarchar(max)
	Declare @SQLOutDay nvarchar(max)
	Declare @SQLTWHDay nvarchar(max)
	Declare @SQLLateInDay nvarchar(4000)
	Declare @SQLTempHeader nvarchar(4000)
	create table #TempHeader(id int,Day1 int,Day2 int,Day3 int,Day4 int,Day5 int,Day6 int,Day7 int,Day8 int,Day9 int,Day10 int,Day11 int,Day12 int,Day13 int,Day14 int,Day15 int,Day16 int,Day17 int,Day18 int,Day19 int,Day20 int,Day21 int,Day22 int,Day23 int,Day24 int,Day25 int,Day26 int,Day27 int,Day28 int,Day29 int,Day30 int,Day31 int)
	set @Diff = datediff(d,@fromDat,@ToDat) +1
	insert into #TempHeader(id) values(1)
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)  
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,
		Shift_FH_StartTime nvarchar(25),Shift_FH_Endtime datetime,Shfit_SH_StartTime datetime,Shift_SH_Endtime nvarchar(25),HrsWork nvarchar(10),TotalMinsWorked int,
		Status nvarchar(50),Attendance nvarchar(100),anAttendanceCode nvarchar(100), fnAttendanceCode nvarchar(100),
		EarlyOut Numeric(18,0),LateIn Numeric(18,0),TotalLateMins int,TotalLate varchar(20),DayFNAttendanceCode nvarchar(100),
		DayANAttendanceCode nvarchar(100),AttandanceCode nvarchar(100),TotPresentDays nvarchar(15)  DEFAULT ''0.0'' ,TotHoursWorked nvarchar(15)DEFAULT ''00:00'',TotLateHrs nvarchar(15) DEFAULT ''00:00''
		,TotLeaveDays nvarchar(15) DEFAULT ''0.0'',TotAbsentDays nvarchar(15) DEFAULT ''0.0'',PrevShift_ID int,
		TotalEarlyMins int,TotEOHrs nvarchar(15) DEFAULT ''00:00'',NormOt int,Offot int,Hot int,
		TotNormOT nvarchar(15) DEFAULT ''00:00'',
		TotOffOT nvarchar(15) DEFAULT ''00:00'',TotHOT nvarchar(15) DEFAULT ''00:00'',TotalLateAndEarlymins int,TotalEarlyPerDay nvarchar(20) default ''00:00''
	)    
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[LevelId],[EmployeeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
	(  
		[DesignationId],[EmployeeId],[EffectiveDate] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[TypeId],[EmployeeId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[CategoryId],[EmployeeId] ASC  
	)ON [PRIMARY]  
	--Employee Level insert in Temporary table
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory	
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData=	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '' 
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End	
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''
	Execute(@sqlTempProcessedData)
	select SwipeCardNo,inActiveDate into #InActiveDatas from ta_tbl_employee where inactivedate is not null and Employee_Status=0  
	Declare @sqlTempProcessedData1 varchar(8000)
	Declare @sqlTempProcessedData2 varchar(8000)
	set @sqlTempProcessedData1=	
	''insert into #TempProcessedData  
	select #TempEmployee.EmpAutoId,pd.Date,pd.Employee_Code_Id,REPLACE(lower(pd.InTime),'''' '''',''''''''),REPLACE(lower(pd.OutTime),'''' '''',''''''''),pd.Shift_Id,S.Shift_FirstHalf_StartTime ,cast(S.Shift_FirstHalf_EndTime as datetime),cast(S.Shift_SecondHalf_StartTime as datetime),
	S.Shift_SecondHalf_EndTime,pd.HrsWork, ((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))),pd.Status,pd.Attendance,  
	case when (anAttendanceCode=''''Weekly Off'''' and ((OutTime is not null and OutTime <> ''''00:00'''') or (InTime is not null and InTime <> ''''00:00''''))) then  anAttendanceCode   
	when (anAttendanceCode=''''Holiday'''' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then  anAttendanceCode   
	when (fnAttendanceCode=''''Holiday'''' and (OutTime is null or OutTime = ''''00:00'''') and (InTime is not null and InTime <> ''''00:00'''')) then  anAttendanceCode   
	when (anAttendanceCode=''''RH'''' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then anAttendanceCode   
	when (fnAttendanceCode=''''RH'''' and (OutTime is null or OutTime = ''''00:00'''') and (InTime is not null and InTime <> ''''00:00'''')) then anAttendanceCode   
	when (anAttendanceCode=''''Present'''' and fnAttendanceCode <> ''''Present'''' and (pd.EarlyOut <> ''''00:00'''')) then  pd.anAttendanceCode    
	when (anAttendanceCode=''''Present'''' and fnAttendanceCode = ''''Present'''' and (PD.EarlyOut <> ''''00:00'''' )) then pd.anAttendanceCode   
	else pd.anAttendanceCode   
	end,  
	case when (fnAttendanceCode =''''Weekly Off'''' and ((OutTime is not null and OutTime <> ''''00:00'''') or (InTime is not null and InTime <> ''''00:00''''))) then  fnAttendanceCode  
	when  (fnAttendanceCode=''''Holiday'''' and S.Shift_FirstHalf_EndTime is not null and CAST(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then fnAttendanceCode  
	when  (fnAttendanceCode=''''RH'''' and S.Shift_FirstHalf_EndTime is not null and CAST(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when (fnAttendanceCode=''''Present'''' and anAttendanceCode<>''''Present'''' and (pd.LateIn <> ''''00:00'''')) then pd.fnAttendanceCode  
	when (fnAttendanceCode=''''Present'''' and anAttendanceCode=''''Present'''' and (pd.LateIn <> ''''00:00'''')) then pd.fnAttendanceCode  
	else pd.fnAttendanceCode end,pd.EarlyOutMins,Pd.LateInMins,Pd.LateInMins, '''''''' as TotalLate,
	'''''''' as DayFNAttendanceCode,''''''''AS DayANAttendanceCode,'''''''','''''''','''''''','''''''','''''''',''''''''
	,S.Shift_Id,Pd.EarlyOutMins,'''''''',
	Case when PD.NormOT is not null AND pd.NormOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end, 
	case when Pd.OffOT is not NULL AND pd.OffOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end,
	case when pd.HolOT is not null AND pd.HolOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end,
	'''''''','''''''','''''''',case when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)=0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)=0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 else isnull(EarlyOutMins,0)+isnull(LateInMins,0) end,''''''''
	from TA_Tbl_ProcessedData PD  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id   
	left outer join TA_Tbl_Shift S on S.Shift_Id=pd.Shift_Id   
	inner join #InActiveDatas IA on (#TempEmployee.EmpSwipeCardNo=IA.SwipeCardNo and pd.Date<=IA.inactivedate)  
	where (date>=CONVERT(DATETIME,''''''+cast(@FromDat as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102))''
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND pd.shift_id= ''+  cast (@Shift as nvarchar(50))  + ''''  
		end
	if(@DataLoading<>0)
		begin			
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + (select case when @DataLoading=1 then '' AND (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday'''')''
						when @DataLoading=2 then '' AND ((pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''') or (pd.Shift_ID= -1))''
						else '' AND (((pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''')or (pd.Shift_ID= -1))
			OR (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday''''))''
			end)
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' and ((Intime is not null or intime<>''''00:00'''') or (outtime is not null or outtime<>''''00:00''''))''
		end	
	Execute(@sqlTempProcessedData1)	   
	set @sqlTempProcessedData2=	
	''insert into #TempProcessedData  
	select #TempEmployee.EmpAutoId,pd.Date,pd.Employee_Code_Id,REPLACE(lower(pd.InTime),'''' '''',''''''''),REPLACE(lower(pd.OutTime),'''' '''',''''''''),pd.Shift_Id,S.Shift_FirstHalf_StartTime,S.Shift_FirstHalf_EndTime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,pd.HrsWork,
	((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))),pd.Status,pd.Attendance,  
	case when (anAttendanceCode=''''Weekly Off'''' and ((OutTime is not null and OutTime <> ''''00:00'''') or (InTime is not null and InTime <> ''''00:00''''))) then anAttendanceCode   
	when (anAttendanceCode=''''Holiday'''' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then  anAttendanceCode   
	when (fnAttendanceCode=''''Holiday'''' and (OutTime is null or OutTime = ''''00:00'''') and (InTime is not null and InTime <> ''''00:00'''')) then  anAttendanceCode   
	when (anAttendanceCode=''''RH'''' and S.Shift_SecondHalf_StartTime is not null and cast(OutTime as datetime) >= cast(S.Shift_SecondHalf_StartTime as datetime))  then anAttendanceCode   
	when (fnAttendanceCode=''''RH'''' and (OutTime is null or OutTime = ''''00:00'''') and (InTime is not null and InTime <> ''''00:00'''')) then anAttendanceCode   
	when (anAttendanceCode=''''Present'''' and fnAttendanceCode <> ''''Present'''' and (pd.EarlyOut <> ''''00:00'''')) then  pd.anAttendanceCode    
	when (anAttendanceCode=''''Present'''' and fnAttendanceCode = ''''Present'''' and (PD.EarlyOut <> ''''00:00'''' )) then  pd.anAttendanceCode   
	else pd.anAttendanceCode end,  
	case when (fnAttendanceCode =''''Weekly Off'''' and ((OutTime is not null and OutTime <> ''''00:00'''') or (InTime is not null and InTime <> ''''00:00''''))) then  fnAttendanceCode  
	when  (fnAttendanceCode=''''Holiday'''' and S.Shift_FirstHalf_EndTime is not null and cast(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when  (fnAttendanceCode=''''RH'''' and S.Shift_FirstHalf_EndTime is not null and cast(inTime as datetime) <= cast(S.Shift_FirstHalf_EndTime as datetime)) then  fnAttendanceCode  
	when (fnAttendanceCode=''''Present'''' and anAttendanceCode<>''''Present'''' and (pd.LateIn <> ''''00:00'''')) then pd.fnAttendanceCode  
	when (fnAttendanceCode=''''Present'''' and anAttendanceCode=''''Present'''' and (pd.LateIn <> ''''00:00'''')) then  pd.fnAttendanceCode  
	else pd.fnAttendanceCode end,pd.EarlyOutMins,Pd.LateInMins,Pd.LateInMins, LateIn as TotalLate,'''''''' as DayFNAttendanceCode,''''''''AS DayANAttendanceCode,'''''''','''''''','''''''','''''''','''''''',''''''''
	,S.Shift_Id,Pd.EarlyOutMins,'''''''',
	Case when PD.NormOT is not null AND pd.NormOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end, 
	case when Pd.OffOT is not NULL AND pd.OffOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end,
	case when pd.HolOT is not null AND pd.HolOT<>''''00:00'''' then cast(OtMins as varchar(50)) else 0 end,
	'''''''','''''''','''''''', case when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)<>0 and isnull(EarlyOutMins,0)=0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 when isnull(LateInMins,0)=0 and isnull(EarlyOutMins,0)<>0 then isnull(EarlyOutMins,0)+isnull(LateInMins,0)
						 else isnull(EarlyOutMins,0)+isnull(LateInMins,0) end,''''''''
	from TA_Tbl_ProcessedData PD  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id   
	left outer join TA_Tbl_Shift S on S.Shift_Id=pd.Shift_Id   
	where   
	(date>=CONVERT(DATETIME,''''''+cast(@FromDat as nvarchar(50))+'''''', 102) and Date <=CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102))  
	and #TempEmployee.EmpSwipeCardNo not in(select distinct swipecardno from #InActiveDatas)'' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + '' AND pd.shift_id= ''+  cast (@Shift as nvarchar(50))  + ''''  
		end
	if(@DataLoading<>0)
		begin			
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + (select case when @DataLoading=1 then '' AND (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday'''')''
						when @DataLoading=2 then '' AND ((pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''') or (pd.Shift_ID= -1))''
						else '' AND (((pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''')or (pd.Shift_ID= -1))
			OR (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday''''))''
			end)
			Set @sqlTempProcessedData2 = @sqlTempProcessedData2 + '' and ((Intime is not null or intime<>''''00:00'''') or (outtime is not null or outtime<>''''00:00''''))''
		end	
	Execute(@sqlTempProcessedData2) 	
	--Added by Manjula.P on 19-Feb-2014 for getting weekly off codes from montlhy attendacne vertical
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
	select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
	(
	select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
	from #TempProcessedData where Shift_Id=-1 	
	)
	as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	where
	(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
	select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
	(
	select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
	from #TempProcessedData where PrevShift_ID=-1 	
	)
	as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	where
	(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
	AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   
	--Added by Manjula.P on 19-Feb-2014 for updating OD Entry as like from monthly attendacne report horizondal
	update pd set pd.fnAttendanceCode= pd.fnAttendanceCode + 
	[dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,pd.Employee_Code_Id,''FN'',
	shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end,	
	pd.anAttendanceCode=pd.anAttendanceCode + 
	[dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,pd.Employee_Code_Id,''AN'',
	shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''' else ''(BL)'' end 
	from #TempProcessedData pd
	left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id
	Inner join TA_Tbl_Employee E on Pd.Employee_Code_Id=E.SwipeCardNo 
	where E.Isdeleted=0
	--**********************************************************************************************************  
	Set @SQL=''''
	Set @SQL=''Update #TempProcessedData set DayFNAttendanceCode= ''
	Set @SQL= @SQL + '' Case #TempProcessedData.fnAttendanceCode '' 
	Set @SQL=@SQL+ ''WHEN ''''Present'''' THEN  
	CASE 
	WHEN anAttendanceCode=''''Present'''' and (#TempProcessedData.LateIn<>''''0'''') THEN ''''*P''''
	WHEN anAttendanceCode<>''''Present'''' and (#TempProcessedData.LateIn<>''''0'''' or #TempProcessedData.EarlyOut<>''''0'''')
	and cast(Intime as datetime)>=cast(#TempProcessedData.Shift_FH_Starttime as datetime) THEN ''''*P''''
	ELSE ''''P''''
	END ''
	Set @SQL=@SQL+''WHEN ''''Absent'''' THEN ''''A'''' ''
	Set @SQL=@SQL+''WHEN ''''holiday (on duty)'''' THEN ''''OD'''' ''
	set @SQL = @SQL + '' when ''''Holiday'''' then case when ANAttendanceCode=''''Holiday'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*H''''
	when ANAttendanceCode<>''''Holiday'''' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''''*H''''
	else ''''H'''' end''
	set @SQL = @SQL + '' when ''''Local Holiday'''' then case when ANAttendanceCode=''''Local Holiday'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*LH''''
								  when ANAttendanceCode<>''''Local Holiday'''' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''''*LH''''
								  else ''''LH'''' end''
	set @SQL = @SQL + '' when ''''RH'''' then case when ANAttendanceCode=''''RH'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*RH''''
	when ANAttendanceCode<>''''RH'''' and cast(Intime as datetime)<=cast(#TempProcessedData.Shift_FH_Endtime as datetime) then ''''*RH''''
	else ''''RH'''' end''
	set @SQL = @SQL + '' when ''''Tour'''' then ''''T'''' ''	
	set @SQL = @SQL + '' when ''''Training'''' then ''''TG'''' ''
	set @SQL = @SQL + '' when ''''Weekly Off'''' then case when (InTime is not null and Intime<> ''''00:00'''')then ''''*W'''' else ''''W'''' end ''
	set @SQL = @SQL + '' when ''''weekly off (on duty)'''' then  ''''OD'''' ''
	set @SQL = @SQL + '' when ''''CL'''' then ''''CL'''' ''
	set @SQL = @SQL + '' when ''''EL'''' then ''''EL'''' ''
	set @SQL = @SQL + '' when ''''OL'''' then ''''OL'''' ''	
	set @SQL = @SQL + '' when ''''Present (On Duty)'''' then ''''OD'''' ''	
	set @SQL = @SQL + '' when ''''Comp Off'''' then ''''C'''' ''
	set @SQL = @SQL + '' when ''''FieldDuty'''' then ''''FD'''' ''	
	set @SQL = @SQL + '' Else '''''''' + lower(FNAttendanceCode) + '''''''' ''
	set @SQL = @SQL + '' end ''
	set @SQL = @SQL + '' ,DayANAttendanceCode =case #TempProcessedData.ANAttendanceCode ''
	set @SQL = @SQL + '' when ''''Present''''  then case 
	when FNAttendanceCode=''''present'''' and (#TempProcessedData.EarlyOut <> ''''0'''' ) then ''''*P'''' 
	when FNAttendanceCode<>''''present'''' and (#TempProcessedData.EarlyOut <> ''''0'''' ) then ''''*P''''
	else ''''P'''' end''
	set @SQL = @SQL + '' when ''''Absent'''' then ''''A'''' ''
	Set @SQL=@SQL+''WHEN ''''holiday (on duty)'''' THEN ''''OD'''' ''
	set @SQL = @SQL + '' when ''''Holiday'''' then case when FNAttendanceCode=''''Holiday'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*H'''' 
	when FNAttendanceCode<>''''Holiday'''' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''''*H''''
	else ''''H'''' end''
	set @SQL = @SQL + '' when ''''Local Holiday'''' then case when FNAttendanceCode=''''Local Holiday'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*LH'''' 
								  when FNAttendanceCode<>''''Local Holiday'''' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''''*LH''''
								  else ''''LH'''' end''	                             
	set @SQL = @SQL + '' when ''''RH'''' then case when FNAttendanceCode=''''RH'''' and (Intime<> ''''00:00'''' or OutTime<>''''00:00'''') then ''''*RH'''' 
	when FNAttendanceCode<>''''RH'''' and cast(Outtime as datetime)>=cast(#TempProcessedData.Shfit_SH_StartTime as datetime) then ''''*RH''''
	else ''''RH'''' end''
	set @SQL = @SQL + '' when ''''Tour'''' then ''''T'''' ''	
	set @SQL = @SQL + '' when ''''Training'''' then ''''TG'''' ''	
	set @SQL = @SQL + '' when ''''Weekly Off'''' then case when (Outtime is not null and Outtime<> ''''00:00'''') then ''''*W'''' else ''''W'''' end ''
	set @SQL = @SQL + '' when ''''weekly off (on duty)'''' then  ''''OD'''' ''
	set @SQL = @SQL + '' when ''''CL'''' then ''''CL'''' ''
	set @SQL = @SQL + '' when ''''EL'''' then ''''EL'''' ''
	set @SQL = @SQL + '' when ''''OL'''' then ''''OL'''' ''	
	set @SQL = @SQL + '' when ''''Present (On Duty)'''' then ''''OD'''' ''
	set @SQL = @SQL + '' when ''''Comp Off'''' then ''''C'''' ''	
	set @SQL = @SQL + '' when ''''FieldDuty'''' then ''''FD'''' ''
	set @SQL = @SQL + '' Else '''''''' + lower(ANAttendanceCode) + ''''''''''
	Set @SQL= @SQL + '' END''
	Exec (@SQL)
	--Select 1
	Set @SQL=''''   
	Set @SQL=''Update #TempProcessedData Set AttandanceCode=DayFNAttendanceCode+''''/ ''''+DayANAttendanceCode''
	Exec (@SQL)Set @SQL='''' 
	--Present
	update #TempProcessedData set  TotPresentDays =Isnull (REPLACE(A.Present,'''',''0.0''),''0.0'')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE fnattendanceCode When ''Present'' Then 0.5 When ''Holiday'' Then 0.5 Else 0 END) + sum(CASE fnattendanceCode When ''Tour'' Then 0.5 Else 0 END) + sum(CASE fnattendanceCode When ''Weekly off'' Then 0.5 Else 0 END) + 
	sum(CASE anattendanceCode When ''Present'' Then 0.5 When ''Holiday'' Then 0.5 Else 0 END)+sum(CASE anattendanceCode When ''Tour'' Then 0.5 Else 0 END)+sum(CASE anattendanceCode When ''Weekly off'' Then 0.5 Else 0 END)) as Present,Employee_code_Id 
	from #TempProcessedData group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
--Total Early out hours
	update #TempProcessedData set  TotEOHrs= Isnull (REPLACE(A.LateInHours,'''',''00:00''),''00:00'')
	from #TempProcessedData TDA inner join 
	(
	select LateInHours=case when len(convert(varchar(20),sum(TotalEarlyMins)/60))=1 then ''0''+convert(varchar(20),sum(TotalEarlyMins)/60)
	else convert(varchar(20),sum(TotalEarlyMins)/60)end+'':''+
	case when convert(varchar(20),sum(TotalEarlyMins)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(TotalEarlyMins)%60))=1 then ''0''+convert(varchar(20),sum(TotalEarlyMins)%60)
	else convert(varchar(20),sum(TotalEarlyMins)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id	
	--Total late hours
	update #TempProcessedData set  TotLateHrs=Isnull (REPLACE(A.LateInHours,'''',''00:00''),''00:00'')
	from #TempProcessedData TDA inner join 
	(	
	select LateInHours=case when len(convert(varchar(20),sum(TotalLateMins)/60))=1 then ''0''+convert(varchar(20),sum(TotalLateMins)/60)
	else convert(varchar(20),sum(TotalLateMins)/60)end+'':''+
	case when convert(varchar(20),sum(TotalLateMins)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(TotalLateMins)%60))=1 then ''0''+convert(varchar(20),sum(TotalLateMins)%60)
	else convert(varchar(20),sum(TotalLateMins)%60)end end
	,Employee_code_Id from 
	#TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	update #TempProcessedData set  TotalEarlyPerDay=Isnull (REPLACE(A.LateInHours,'''',''00:00''),''00:00'')
	from #TempProcessedData TDA inner join 
	(	
	select LateInHours=case when len(convert(varchar(20),TotalLateAndEarlymins/60))=1 then ''0''+convert(varchar(20),TotalLateAndEarlymins/60)
	else convert(varchar(20),TotalLateAndEarlymins/60)end+'':''+
	case when convert(varchar(20),TotalLateAndEarlymins%60)=0 then
	''00'' else case when len(convert(varchar(20),TotalLateAndEarlymins%60))=1 then ''0''+convert(varchar(20),TotalLateAndEarlymins%60)
	else convert(varchar(20),TotalLateAndEarlymins%60)end end
	,Employee_code_Id,Date from 
	#TempProcessedData  
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id and A.Date=TDA.Date
	----Calculate late hrs
	----update #TempProcessedData set  TotLateHrs= Isnull (REPLACE(A.LateInHours,'''',''00:00''),''00:00'')
	----from #TempProcessedData TDA inner join 
	----(
	--select LateInHours=
	--case when len(convert(varchar(20),sum(TotalEarlyMins)/60))=1 then (convert(varchar(20),sum(TotalLateMins)/60)+convert(varchar(20),sum(TotalEarlyMins)/60))/60
	--else convert(varchar(30),(convert(varchar(20),sum(TotalLateMins)/60)+convert(varchar(20),sum(TotalEarlyMins)/60))/60) end +'':''+
	--case when convert(varchar(20),sum(TotalEarlyMins)%60)=0 then
	--''00'' else case when len(convert(varchar(20),sum(TotalEarlyMins)%60))=1 then convert(varchar(30),(convert(varchar(20),sum(TotalLateMins)%60)+convert(varchar(20),sum(TotalEarlyMins)%60))%60)
	--else convert(varchar(20),(convert(varchar(20),sum(TotalLateMins)%60)+convert(varchar(20),sum(TotalEarlyMins)%60))%60) end end
	--,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	----) as A on TDA.Employee_Code_Id = A.Employee_code_Id	
	----End
	update #TempProcessedData set  TotNormOT= Isnull (REPLACE(A.WeekdayOT,'''',''00:00''),''00:00''),
	TotOffOT= Isnull (REPLACE(A.WOffot,'''',''00:00''),''00:00''),
	TotHOT= Isnull (REPLACE(A.Holiot,'''',''00:00''),''00:00'')
	from #TempProcessedData TDA inner join 
	(
	select WeekdayOT=case when len(convert(varchar(20),sum(NormOt)/60))=1 then ''0''+convert(varchar(20),sum(NormOt)/60)
	else convert(varchar(20),sum(NormOt)/60)end+'':''+
	case when convert(varchar(20),sum(NormOt)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(NormOt)%60))=1 then ''0''+convert(varchar(20),sum(NormOt)%60)
	else convert(varchar(20),sum(NormOt)%60)end end,
	WOffot=
	case when len(convert(varchar(20),sum(Offot)/60))=1 then ''0''+convert(varchar(20),sum(Offot)/60)
	else convert(varchar(20),sum(Offot)/60)end+'':''+
	case when convert(varchar(20),sum(Offot)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(Offot)%60))=1 then ''0''+convert(varchar(20),sum(Offot)%60)
	else convert(varchar(20),sum(Offot)%60)end end,
	Holiot=
	case when len(convert(varchar(20),sum(Hot)/60))=1 then ''0''+convert(varchar(20),sum(Hot)/60)
	else convert(varchar(20),sum(Hot)/60)end+'':''+
	case when convert(varchar(20),sum(Hot)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(Hot)%60))=1 then ''0''+convert(varchar(20),sum(Hot)%60)
	else convert(varchar(20),sum(Hot)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id		
	----Leave Availed
	update #TempProcessedData set  TotLeaveDays=  Isnull (REPLACE(A.LeaveAvailed,'''',''0.0''),''0.0'')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE	when fnattendanceCode IS NULL  then 0 
						When fnattendanceCode =''Weekly off'' Then 0 
						when fnattendanceCode =''Holiday'' then 0 
						when fnattendanceCode =''Local Holiday'' then 0  
						when fnattendanceCode =''Present'' then 0 
						when fnattendanceCode =''Absent'' then 0 
						when fnattendanceCode =''Tour'' then 0 Else 0.5 END) + 
	sum(CASE When anattendanceCode is null then 0 
			 when anattendanceCode =''Weekly off'' Then 0 
			 when anattendanceCode =''Holiday'' then 0 
			 when anattendanceCode =''Local Holiday'' then 0 
			 when anattendanceCode =''Present'' then 0 
			 when anattendanceCode =''Absent'' then 0 
			 when anattendanceCode =''Tour'' then 0 Else 0.5 END)) as LeaveAvailed,Employee_code_Id 
	from TA_tbl_ProcessedData
	where Date between @fromDat and @ToDat
	group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--Absent
	update #TempProcessedData set  TotAbsentDays = Isnull (REPLACE(A.Absent,'''',''0.0''),''0.0'')
	from #TempProcessedData TDA inner join 
	(
	select (sum(CASE fnattendanceCode When ''Absent'' Then 0.5 Else 0 END) + 
	sum(CASE anattendanceCode When ''Absent'' Then 0.5 Else 0 END)) as Absent,Employee_code_Id 
	from #TempProcessedData group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	--Total hours Worked
	update #TempProcessedData set  TotHoursWorked= Isnull ( REPLACE(A.LateInHours,'''',''00.00''),''00:00'')
	from #TempProcessedData TDA inner join 
	(
	select LateInHours=case when len(convert(varchar(20),sum(TotalMinsWorked)/60))=1 then ''0''+convert(varchar(20),sum(TotalMinsWorked)/60)
	else convert(varchar(20),sum(TotalMinsWorked)/60)end+'':''+
	case when convert(varchar(20),sum(TotalMinsWorked)%60)=0 then
	''00'' else case when len(convert(varchar(20),sum(TotalMinsWorked)%60))=1 then ''0''+convert(varchar(20),sum(TotalMinsWorked)%60)
	else convert(varchar(20),sum(TotalMinsWorked)%60)end end
	,Employee_code_Id from #TempProcessedData  group by Employee_code_Id
	) as A on TDA.Employee_Code_Id = A.Employee_code_Id
	declare @pos as int  
	set @pos = charindex('':'',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	if (@MinWorkHours<>'''')  
		begin  
			declare @sqlQueryTemp as varchar(8000)    
			set @sqlQueryTemp=''''   
			set @sqlQueryTemp = ''select pd.Employee_Code_Id as SwipeCardNo,CONVERT(VARCHAR,cast(pd.date as datetime),111) as Date,   pd.TotalMinsWorked from Ta_Tbl_Employee e ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''      
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join #EmpDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''   
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join  #EmpCategory on e.Employee_Id =  #EmpCategory.EmployeeId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join #EmpType  on e.Employee_Id = #EmpType.EmployeeId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1''
			if not(@EmployeeName='''' or @EmployeeName=''0'')    
				begin    
					set @sqlQueryTemp = @sqlQueryTemp + ''and (e.Employee_FirstName + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''  
				end   
			set @sqlQueryTemp = @sqlQueryTemp + '' order by e.Employee_FirstName,cast(pd.date as datetime)''    
			insert into #EmpProcessedData exec(@sqlQueryTemp)
		end  
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''''    
	set @sqlQuery = ''select isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,
	e.Employee_Code_Id as Employee_Id, replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,
	CONVERT(VARCHAR,cast(pd.date as datetime),111) as Date,Pd.AttandanceCode,
	CASE pd.Shift_Id WHEN ''''-1'''' THEN ''''Off'''' ELSE shf.Shift_ShortName END
	Shift_ShortName,
	pd.InTime,
	pd.OutTime,pd.HrsWork,
	pd.TotalLate ,pd.TotPresentDays,pd.TotHoursWorked,pd.TotLateHrs,pd.TotLeaveDays ,pd.TotAbsentDays,pd.TotEOHrs,TotNormOT,
	TotOffOT ,TotHOT,TotalEarlyPerDay'' 
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''      
	set @sqlQuery = @sqlQuery + '' inner join #EmpDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''   
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
	set @sqlQuery = @sqlQuery + '' inner join #EmpCategory  on e.Employee_Id = #EmpCategory.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on #EmpCategory.CategoryId = TA_Tbl_Category.CategoryId''  
	set @sqlQuery = @sqlQuery + '' inner join #EmpType  on e.Employee_Id = #EmpType.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on #EmpType.TypeId = TA_Tbl_Type.TypeId''  
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id ''
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + '' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id''  
		end
	set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and((pd.date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''    
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and #EmpProcessedData.TotalWorkMins >= '' + cast(@TotalMin as nvarchar(8))    
		end
	if(@Gender<>''Both'')  
		begin  
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')  
		begin  
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''  
		end  	 
	create table #MonthlyAttendancedata
	(EmployeeName nvarchar(255) ,EmployeeID nvarchar(255),Designation nvarchar(255),Date Datetime,Attandance nvarchar(50),ShiftName nvarchar(50),InTime nvarchar(25),OutTime nvarchar(25),
	WorkedHours nvarchar(15),LateHours nvarchar(15),TotPresentDays nvarchar(15),TotHoursWorked nvarchar(15),TotLateHours nvarchar(15),TotLeaveDays nvarchar(15),TotAbsentDays nvarchar(15),TotEOHrs nvarchar(15) DEFAULT ''00:00''
	,TotNormOT nvarchar(15) DEFAULT ''00:00'', TotOffOT nvarchar(15) DEFAULT ''00:00'',TotHOT nvarchar(15) DEFAULT ''00:00'' 
,TotalEarlyPerDay nvarchar(20) default ''00:00''
	)
	Insert Into #MonthlyAttendancedata 
	exec(@sqlQuery) 
	Set @sqlQuery=''''
	create table #AllMonthlyAttendancedata
	(EmployeeName nvarchar(255) ,EmployeeID nvarchar(255),Designation nvarchar(255),TotPresentDays nvarchar(15),TotHoursWorked nvarchar(15),TotLateHours nvarchar(15),TotLeaveDays nvarchar(15),TotAbsentDays nvarchar(15),
	Attn_Day1 nvarchar(100) DEFAULT ''-'',Attn_Day2 nvarchar(100) DEFAULT ''-'',Attn_Day3 nvarchar(100) DEFAULT ''-'',Attn_Day4 nvarchar(100) DEFAULT ''-'',Attn_Day5 nvarchar(100) DEFAULT ''-'',Attn_Day6 nvarchar(100) DEFAULT ''-'',Attn_Day7 nvarchar(100) DEFAULT ''-'',Attn_Day8 nvarchar(100) DEFAULT ''-'',Attn_Day9 nvarchar(100) DEFAULT ''-'',Attn_Day10 nvarchar(100) DEFAULT ''-'',Attn_Day11 nvarchar(100) DEFAULT ''-'',Attn_Day12 nvarchar(100) DEFAULT ''-'',Attn_Day13 nvarchar(100) DEFAULT ''-'',Attn_Day14 nvarchar(100) DEFAULT ''-'',Attn_Day15 nvarchar(100) DEFAULT ''-'',Attn_Day16 nvarchar(100) DEFAULT ''-'',Attn_Day17 nvarchar(100) DEFAULT ''-'',Attn_Day18 nvarchar(100) DEFAULT ''-'',Attn_Day19 nvarchar(100) DEFAULT ''-'',Attn_Day20 nvarchar(100) DEFAULT ''-'',Attn_Day21 nvarchar(100) DEFAULT ''-'',Attn_Day22 nvarchar(100) DEFAULT ''-'',Attn_Day23 nvarchar(100) DEFAULT ''-'',Attn_Day24 nvarchar(100) DEFAULT ''-'',Attn_Day25 nvarchar(100) DEFAULT ''-'',Attn_Day26 nvarchar(100) DEFAULT ''-'',Attn_Day27 nvarchar(100) DEFAULT ''-'',Attn_Day28 nvarchar(100) DEFAULT ''-'',Attn_Day29 nvarchar(100) DEFAULT ''-'',Attn_Day30 nvarchar(100) DEFAULT ''-'',Attn_Day31 nvarchar(100) DEFAULT ''-'',
	Shift_Day1 nvarchar(100) DEFAULT ''-'',Shift_Day2 nvarchar(100) DEFAULT ''-'',Shift_Day3 nvarchar(100) DEFAULT ''-'',Shift_Day4 nvarchar(100) DEFAULT ''-'',Shift_Day5 nvarchar(100) DEFAULT ''-'',Shift_Day6 nvarchar(100) DEFAULT ''-'',Shift_Day7 nvarchar(100) DEFAULT ''-'',Shift_Day8 nvarchar(100) DEFAULT ''-'',Shift_Day9 nvarchar(100) DEFAULT ''-'',Shift_Day10 nvarchar(100) DEFAULT ''-'',Shift_Day11 nvarchar(100) DEFAULT ''-'',Shift_Day12 nvarchar(100) DEFAULT ''-'',Shift_Day13 nvarchar(100) DEFAULT ''-'',Shift_Day14 nvarchar(100) DEFAULT ''-'',Shift_Day15 nvarchar(100) DEFAULT ''-'',Shift_Day16 nvarchar(100) DEFAULT ''-'',Shift_Day17 nvarchar(100) DEFAULT ''-'',Shift_Day18 nvarchar(100) DEFAULT ''-'',Shift_Day19 nvarchar(100) DEFAULT ''-'',Shift_Day20 nvarchar(100) DEFAULT ''-'',Shift_Day21 nvarchar(100) DEFAULT ''-'',Shift_Day22 nvarchar(100) DEFAULT ''-'',Shift_Day23 nvarchar(100) DEFAULT ''-'',Shift_Day24 nvarchar(100) DEFAULT ''-'',Shift_Day25 nvarchar(100) DEFAULT ''-'',Shift_Day26 nvarchar(100) DEFAULT ''-'',Shift_Day27 nvarchar(100) DEFAULT ''-'',Shift_Day28 nvarchar(100) DEFAULT ''-'',Shift_Day29 nvarchar(100) DEFAULT ''-'',Shift_Day30 nvarchar(100) DEFAULT ''-'',Shift_Day31 nvarchar(100) DEFAULT ''-'',
	In_Day1 nvarchar(100) DEFAULT ''-'',In_Day2 nvarchar(100) DEFAULT ''-'',In_Day3 nvarchar(100) DEFAULT ''-'',In_Day4 nvarchar(100) DEFAULT ''-'',In_Day5 nvarchar(100) DEFAULT ''-'',In_Day6 nvarchar(100) DEFAULT ''-'',In_Day7 nvarchar(100) DEFAULT ''-'',In_Day8 nvarchar(100) DEFAULT ''-'',In_Day9 nvarchar(100) DEFAULT ''-'',In_Day10 nvarchar(100) DEFAULT ''-'',In_Day11 nvarchar(100) DEFAULT ''-'',In_Day12 nvarchar(100) DEFAULT ''-'',In_Day13 nvarchar(100) DEFAULT ''-'',In_Day14 nvarchar(100) DEFAULT ''-'',In_Day15 nvarchar(100) DEFAULT ''-'',In_Day16 nvarchar(100) DEFAULT ''-'',In_Day17 nvarchar(100) DEFAULT ''-'',In_Day18 nvarchar(100) DEFAULT ''-'',In_Day19 nvarchar(100) DEFAULT ''-'',In_Day20 nvarchar(100) DEFAULT ''-'',In_Day21 nvarchar(100) DEFAULT ''-'',In_Day22 nvarchar(100) DEFAULT ''-'',In_Day23 nvarchar(100) DEFAULT ''-'',In_Day24 nvarchar(100) DEFAULT ''-'',In_Day25 nvarchar(100) DEFAULT ''-'',In_Day26 nvarchar(100) DEFAULT ''-'',In_Day27 nvarchar(100) DEFAULT ''-'',In_Day28 nvarchar(100) DEFAULT ''-'',In_Day29 nvarchar(100) DEFAULT ''-'',In_Day30 nvarchar(100) DEFAULT ''-'',In_Day31 nvarchar(100) DEFAULT ''-'',
	Out_Day1 nvarchar(100) DEFAULT ''-'',Out_Day2 nvarchar(100) DEFAULT ''-'',Out_Day3 nvarchar(100) DEFAULT ''-'',Out_Day4 nvarchar(100) DEFAULT ''-'',Out_Day5 nvarchar(100) DEFAULT ''-'',Out_Day6 nvarchar(100) DEFAULT ''-'',Out_Day7 nvarchar(100) DEFAULT ''-'',Out_Day8 nvarchar(100) DEFAULT ''-'',Out_Day9 nvarchar(100) DEFAULT ''-'',Out_Day10 nvarchar(100) DEFAULT ''-'',Out_Day11 nvarchar(100) DEFAULT ''-'',Out_Day12 nvarchar(100) DEFAULT ''-'',Out_Day13 nvarchar(100) DEFAULT ''-'',Out_Day14 nvarchar(100) DEFAULT ''-'',Out_Day15 nvarchar(100) DEFAULT ''-'',Out_Day16 nvarchar(100) DEFAULT ''-'',Out_Day17 nvarchar(100) DEFAULT ''-'',Out_Day18 nvarchar(100) DEFAULT ''-'',Out_Day19 nvarchar(100) DEFAULT ''-'',Out_Day20 nvarchar(100) DEFAULT ''-'',Out_Day21 nvarchar(100) DEFAULT ''-'',Out_Day22 nvarchar(100) DEFAULT ''-'',Out_Day23 nvarchar(100) DEFAULT ''-'',Out_Day24 nvarchar(100) DEFAULT ''-'',Out_Day25 nvarchar(100) DEFAULT ''-'',Out_Day26 nvarchar(100) DEFAULT ''-'',Out_Day27 nvarchar(100) DEFAULT ''-'',Out_Day28 nvarchar(100) DEFAULT ''-'',Out_Day29 nvarchar(100) DEFAULT ''-'',Out_Day30 nvarchar(100) DEFAULT ''-'',Out_Day31 nvarchar(100) DEFAULT ''-'',
	TWH_Day1 nvarchar(100) DEFAULT ''-'',TWH_Day2 nvarchar(100) DEFAULT ''-'',TWH_Day3 nvarchar(100) DEFAULT ''-'',TWH_Day4 nvarchar(100) DEFAULT ''-'',TWH_Day5 nvarchar(100) DEFAULT ''-'',TWH_Day6 nvarchar(100) DEFAULT ''-'',TWH_Day7 nvarchar(100) DEFAULT ''-'',TWH_Day8 nvarchar(100) DEFAULT ''-'',TWH_Day9 nvarchar(100) DEFAULT ''-'',TWH_Day10 nvarchar(100) DEFAULT ''-'',TWH_Day11 nvarchar(100) DEFAULT ''-'',TWH_Day12 nvarchar(100) DEFAULT ''-'',TWH_Day13 nvarchar(100) DEFAULT ''-'',TWH_Day14 nvarchar(100) DEFAULT ''-'',TWH_Day15 nvarchar(100) DEFAULT ''-'',TWH_Day16 nvarchar(100) DEFAULT ''-'',TWH_Day17 nvarchar(100) DEFAULT ''-'',TWH_Day18 nvarchar(100) DEFAULT ''-'',TWH_Day19 nvarchar(100) DEFAULT ''-'',TWH_Day20 nvarchar(100) DEFAULT ''-'',TWH_Day21 nvarchar(100) DEFAULT ''-'',TWH_Day22 nvarchar(100) DEFAULT ''-'',TWH_Day23 nvarchar(100) DEFAULT ''-'',TWH_Day24 nvarchar(100) DEFAULT ''-'',TWH_Day25 nvarchar(100) DEFAULT ''-'',TWH_Day26 nvarchar(100) DEFAULT ''-'',TWH_Day27 nvarchar(100) DEFAULT ''-'',TWH_Day28 nvarchar(100) DEFAULT ''-'',TWH_Day29 nvarchar(100) DEFAULT ''-'',TWH_Day30 nvarchar(100) DEFAULT ''-'',TWH_Day31 nvarchar(100) DEFAULT ''-'',
	LateIn_Day1 nvarchar(100) DEFAULT ''-'',LateIn_Day2 nvarchar(100) DEFAULT ''-'',LateIn_Day3 nvarchar(100) DEFAULT ''-'',LateIn_Day4 nvarchar(100) DEFAULT ''-'',LateIn_Day5 nvarchar(100) DEFAULT ''-'',LateIn_Day6 nvarchar(100) DEFAULT ''-'',LateIn_Day7 nvarchar(100) DEFAULT ''-'',LateIn_Day8 nvarchar(100) DEFAULT ''-'',LateIn_Day9 nvarchar(100) DEFAULT ''-'',LateIn_Day10 nvarchar(100) DEFAULT ''-'',LateIn_Day11 nvarchar(100) DEFAULT ''-'',LateIn_Day12 nvarchar(100) DEFAULT ''-'',LateIn_Day13 nvarchar(100) DEFAULT ''-'',LateIn_Day14 nvarchar(100) DEFAULT ''-'',LateIn_Day15 nvarchar(100) DEFAULT ''-'',LateIn_Day16 nvarchar(100) DEFAULT ''-'',LateIn_Day17 nvarchar(100) DEFAULT ''-'',LateIn_Day18 nvarchar(100) DEFAULT ''-'',LateIn_Day19 nvarchar(100) DEFAULT ''-'',LateIn_Day20 nvarchar(100) DEFAULT ''-'',LateIn_Day21 nvarchar(100) DEFAULT ''-'',LateIn_Day22 nvarchar(100) DEFAULT ''-'',LateIn_Day23 nvarchar(100) DEFAULT ''-'',LateIn_Day24 nvarchar(100) DEFAULT ''-'',LateIn_Day25 nvarchar(100) DEFAULT ''-'',LateIn_Day26 nvarchar(100) DEFAULT ''-'',LateIn_Day27 nvarchar(100) DEFAULT ''-'',LateIn_Day28 nvarchar(100) DEFAULT ''-'',LateIn_Day29 nvarchar(100) DEFAULT ''-'',LateIn_Day30 nvarchar(100) DEFAULT ''-'',LateIn_Day31 nvarchar(100) DEFAULT ''-''
	,TotEarlyOutHours nvarchar(15)	
	,TotNormOT nvarchar(15) DEFAULT ''00:00'', TotOffOT nvarchar(15) DEFAULT ''00:00'',TotHOT nvarchar(15) DEFAULT ''00:00'' 
	,TotalEarlyPerDay nvarchar(20) default ''00:00''
	)
	Insert into #AllMonthlyAttendancedata (EmployeeName,EmployeeID,Designation,TotPresentDays,TotHoursWorked,TotLateHours,TotLeaveDays,TotAbsentDays,TotEarlyOutHours,TotNormOT , TotOffOT ,TotHOT)
	select distinct EmployeeName,EmployeeID,Designation,TotPresentDays,TotHoursWorked,TotLateHours,TotLeaveDays,TotAbsentDays,TotEOHrs
	,TotNormOT , TotOffOT ,TotHOT
	from #MonthlyAttendancedata 
	Declare @SQLUpdate varchar(max)
	--select * from #MonthlyAttendancedata
	set @SQLUpdate=''''
	set @Count=1
	Set @SQLTempHeader=''''
	set @Fromdate1=@fromDat
	while(@Count <=31)
		begin
			set @SQLTempHeader = @SQLTempHeader + '' update #TempHeader set Day''+cast(@Count as varchar(10)) + ''='' + cast(datepart(d,@Fromdate1)as varchar(10)) + ''where id=1''
			exec(@SQLTempHeader)
			set @SQLTempHeader=''''
			if(@Count <=@Diff and @Count<=31)
				begin 
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set Attn_Day''+ cast(@Count as varchar(10)) + ''= Case When len(Isnull(#MonthlyAttendancedata.Attandance,''''''''))>0 then #MonthlyAttendancedata.Attandance Else ''''-'''' End''	
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' +CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
					set @SQLUpdate=''''
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set Shift_Day''+ cast(@Count as varchar(10)) + '' = Case When len(Isnull(#MonthlyAttendancedata.ShiftName,''''''''))>0 then #MonthlyAttendancedata.ShiftName Else ''''-'''' End''
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' + CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
					set @SQLUpdate=''''
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set In_Day''+ cast(@Count as varchar(10)) + '' = Case When len(Isnull(#MonthlyAttendancedata.InTime,''''''''))>0 then #MonthlyAttendancedata.InTime Else ''''-'''' End''
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' + CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
					set @SQLUpdate=''''
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set Out_Day''+ cast(@Count as varchar(10)) + '' = Case When len(Isnull(#MonthlyAttendancedata.OutTime,''''''''))>0 then #MonthlyAttendancedata.OutTime Else ''''-'''' End''
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' + CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
					set @SQLUpdate=''''
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set TWH_Day''+ cast(@Count as varchar(10)) + '' = Case When len(Isnull(#MonthlyAttendancedata.WorkedHours,''''''''))>0 then #MonthlyAttendancedata.WorkedHours Else ''''-'''' End''
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' + CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
					set @SQLUpdate=''''
					set @SQLUpdate = @SQLUpdate + '' update #AllMonthlyAttendancedata set LateIn_Day''+ cast(@Count as varchar(10)) + '' = Case When len(Isnull(#MonthlyAttendancedata.TotalEarlyPerDay,''''''''))>0 then #MonthlyAttendancedata.TotalEarlyPerDay Else ''''-'''' End''
					set @SQLUpdate = @SQLUpdate + '' from  #MonthlyAttendancedata inner join #AllMonthlyAttendancedata on #AllMonthlyAttendancedata.EmployeeID=	''
					set @SQLUpdate = @SQLUpdate + ''	#MonthlyAttendancedata.EmployeeID and #MonthlyAttendancedata.date =   CONVERT(DATETIME, '''''' + CAST(@Fromdate1 as varchar(50)) + '''''' , 102)''
					exec(@SQLUpdate)
				end
			set @Fromdate1=dateadd(d,1,@Fromdate1)
			set @Count=@Count +1
		end	
	Select * from #AllMonthlyAttendancedata	
	select * from #TempHeader
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #TempHeader   
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee
	Drop table  #AllMonthlyAttendancedata    
	Drop table  #MonthlyAttendancedata 
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
Modified by gopinath on 19Jun15, for adding the break time in report   
Proc_TA_RptMonthlyAttendance_Dashboard '''',''29/May/2018'',''29/May/2018'','''',''0'',''B001273'',0,0,''uiStaff'',''4'','''',0,0,''Both'',0,0,3
Proc_TA_RptMonthlyAttendance '''',''29/May/2018'',''29/May/2018'','''',''0'',''B001273'',0,0,''uiStaff'',''4'','''',0,0,''Both'',0,0,3,0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Dashboard]
(   
	@MinWorkHours as varchar(10),
	@fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeId varchar(max),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@Shift int,
	@DataLoading int,
	@EmpAutoId bigint
)   
AS    
BEGIN    
	SET NOCOUNT ON;  	
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins VARCHAR(50))    
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(20),
		InTime nvarchar(25),
		OutTime nvarchar(25),
		Shift_Id int,
		HrsWork nvarchar(10),
		SupposedWorkHours nvarchar(10),
		Status nvarchar(50),
		Attendance nvarchar(20),
		anAttendanceCode nvarchar(15),
		fnAttendanceCode nvarchar(15),
		PrevShift_ID int,
		Process_Rec_ID bigint,
		Exactshift_StartTime nvarchar(25),
		Shift_Secondhalf_startTime datetime,
		LateInmin	nvarchar(10),
		EarlyOut nvarchar(10),
		LateIn nvarchar(10),
		NormOT nvarchar(10),
		OffOT nvarchar(10),
		HolOT nvarchar(10),
		OTMINS decimal(18,0),
		EarlyOutMin int,
		overtimeStatus varchar(20),
		NightOrMorn int
		,InNotation char(1),
		OutNotation char(1),
		BreakHours varchar(20),
		LunchHours varchar(20),
		BreakHoursMins int,
		LunchHoursMins int
	)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Date],[Employee_Code_Id] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] 
	) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId],[DesignationId]
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
	(  
		[EffectiveDate],[EmployeeId],[TypeId] 
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
	(  
		[EffectiveDate],[EmployeeId],[CategoryId]
	)ON [PRIMARY]  
	Declare @sqlEmpLevel nvarchar(4000)
	--insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	--insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	--insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(100)) + '''''')''
	Execute(@sqlEmpDesi)
	--Employee Type insert in Temporary table
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
	Execute(@sqlEmpType)
	--Employee Category insert in Temporary table
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102),'''''' + cast(@EmployeeId as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
	Execute(@sqlEmpCategory)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF(@GENDER<>''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' ''  
	END	
	if(@isReportingto > 0)
    BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + '' and (EMP.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	--if(@EmpAutoId > 0)
 --   BEGIN
	--	set @SQLEMPLEVEL = @SQLEMPLEVEL + '' and (EMP.Employee_ID IN (select * from #EmployeeIds)) ''  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData=	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id '' 
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.SwipeCardNo ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.SwipeCardNo ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''
	Execute(@sqlTempProcessedData)
	set @sqlTempProcessedData1=
	''insert into #TempProcessedData 
	select	#EMPLEVEL.EMPLOYEEID,
			TA_Tbl_ProcessedData.Date,
			TA_Tbl_ProcessedData.Employee_Code_Id,
			TA_Tbl_ProcessedData.intime,
			TA_Tbl_ProcessedData.outtime,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.HrsWork,
			TA_Tbl_ProcessedData.WorkHrs,
			TA_Tbl_ProcessedData.Status,
			TA_Tbl_ProcessedData.Attendance,
			TA_Tbl_ProcessedData.anAttendanceCode,
			TA_Tbl_ProcessedData.fnAttendanceCode,
			TA_Tbl_ProcessedData.Shift_Id,
			TA_Tbl_ProcessedData.Process_Rec_ID,
			S.Shift_startTime,
			cast(S.Shift_Secondhalf_startTime as datetime)
			,LateInMins,
			EarlyOut,
			LateIn,
			TA_Tbl_ProcessedData.NormOT,
			TA_Tbl_ProcessedData.OffOT,
			TA_Tbl_ProcessedData.HolOT,
			OtMins,
			case when charindex(''''.'''',convert(varchar(20),EarlyOutmins))!=0 then convert(int,substring(convert(varchar(20),EarlyOutMins),0,charindex(''''.'''',convert(varchar(20),EarlyOutmins))))
			else EarlyOutmins end,
			OvertimeStatus,
			0,
			InNotation,
			OutNotation,
			BreakHrs,
			LunchHrs,
			BreakHrsInMins,
			LunchHrsInMins
			FROM TA_TBL_PROCESSEDDATA 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102))
	AND (dbo.TA_Tbl_ProcessedData.ANAttendanceCode=''''PRESENT'''' or dbo.TA_Tbl_ProcessedData.FNAttendanceCode=''''Present'''' or (FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' and (intime<>''''00:00'''' or outtime<>''''00:00''''))
						or (FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''Holiday'''' and (intime<>''''00:00'''' or outtime<>''''00:00'''')))'' 
	if(@Shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND TA_Tbl_ProcessedData.shift_id= ''+  cast (@Shift as nvarchar(50))
		end	
	if(@DataLoading<>0)
		begin			
			--Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday'''')''  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + (
			select	case	when @DataLoading=1 then '' AND (TA_Tbl_ProcessedData.FNAttendanceCode= ''''Holiday'''' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''''Holiday'''')''
							when @DataLoading=2 then '' AND ((TA_Tbl_ProcessedData.FNAttendanceCode= ''''Weekly Off'''' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''''Weekly Off'''') or (TA_Tbl_ProcessedData.Shift_ID= -1))''
							else ''	AND (((TA_Tbl_ProcessedData.FNAttendanceCode= ''''Weekly Off'''' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''''Weekly Off'''')or (TA_Tbl_ProcessedData.Shift_ID= -1))
									OR (TA_Tbl_ProcessedData.FNAttendanceCode= ''''Holiday'''' AND TA_Tbl_ProcessedData.ANAttendanceCode= ''''Holiday''''))''					end)
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' and ((Intime is not null or intime<>''''00:00'''') or (outtime is not null or outtime<>''''00:00''''))''
		end
	--if(@DataLoading=2)
	--	begin
	--		Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND (pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''')''  
	--	end
	--if(@DataLoading=3)
	--	begin
	--		Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND ((pd.FNAttendanceCode= ''''Weekly Off'''' AND pd.ANAttendanceCode= ''''Weekly Off'''')
	--		OR (pd.FNAttendanceCode= ''''Holiday'''' AND pd.ANAttendanceCode= ''''Holiday''''))''
	--	end
	Execute(@sqlTempProcessedData1)
	update PD set Exactshift_StartTime=cast(convert(varchar(25),Shift_Secondhalf_startTime,108) as datetime) from #TempProcessedData PD
	inner join ta_tbl_processeddata OPD on PD.Process_Rec_Id=OPD.Process_Rec_ID where OPD.FNAttendanceCode=''CL'' 	
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
		where
		(P.Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102))    
		AND (P.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set NightOrMorn= case when SUBSTRING(S.Shift_StartTime,7,8)=''PM'' and SUBSTRING(S.Shift_Endtime,7,8)=''AM'' then 1 
													when SUBSTRING(S.Shift_StartTime,7,8)=''AM'' and SUBSTRING(S.Shift_Endtime,7,8)=''PM'' and PD.OutTime>''00:00 AM'' then 1
													else 0 end 
	from #TempProcessedData PD inner join TA_Tbl_Shift S on PD.PrevShift_ID=S.Shift_Id
	declare @pos as int  
	set @pos = charindex('':'',@MinWorkHours)  
	declare @TotalMin as int  
	set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)  
	create table #TempMonthlyAttendance(FirstSession varchar(50),SecondSession varchar(50),
	Employee_Id varchar(25),empName varchar(500),BranchName varchar(500),Designation varchar(250),
	Date datetime,InTime varchar(30),OutTime varchar(30),
	HrsWork varchar(30),SupposedWorkHours varchar(30),Status varchar(30),
	TotalMinsWorked varchar(30),Shift_ShortName varchar(20),
	shift_TotalWorkingHours varchar(20),Gender nvarchar(10),
	EarlyOut nvarchar(10),LateIn nvarchar(10),overtime varchar(20),
	NormOTMin int,OffOTMin int,HolOTMin int,NormOT nvarchar(20),
	OffOT nvarchar(20),HolOT nvarchar(20),lateinMin int,EarlyOutMin int,
	TotDefWorkHrs int,TotSupWorkHrs int,overtimeStatus varchar(20),
	NightOrMorn int,LunchInTime nvarchar(20),LunchOutTime nvarchar(20)
	,InNotation char(1),OutNotation char(1)
	,BreakHours varchar(20),LunchHours varchar(20),
	BreakHoursMins int,LunchHoursMins int,
	Shift_StartTime	nvarchar(10),
	Shift_EndTime	nvarchar(10)
	)
	if (@MinWorkHours<>'''')  
		begin  
			declare @sqlQueryTemp as varchar(max)    
			set @sqlQueryTemp=''''   
			set @sqlQueryTemp =  ''select pd.Employee_Code_Id as SwipeCardNo,pd.date as Date,((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalWorkMins from Ta_Tbl_Employee e ''
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpDesignation EDesig on e.employee_id = EDesig.EmployeeId ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
			set @sqlQueryTemp = @sqlQueryTemp + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
			set @sqlQueryTemp = @sqlQueryTemp + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''  
			Set @sqlQueryTemp = @sqlQueryTemp + '' Left JOIN ta_tbl_shift sh ON sh.shift_id = pd.shift_id ''
			set @sqlQueryTemp = @sqlQueryTemp + '' where  (	(e.Employee_Status = 1) or 	
			(e.Employee_Status = 0 and  convert(nvarchar(11), e.InActiveDate,102) >= convert(nvarchar(11),pd.date,102)
			)) AND (e.Isdeleted = 0) AND (e.report_exclude = 0)''
			insert into #EmpProcessedData exec(@sqlQueryTemp)  
		end
	declare @sqlQuery as varchar(max)    
	set @sqlQuery=''''    	
	set @sqlQuery = ''select  pd.fnAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''''FN'''',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''''''' else ''''(BL)'''' end as FirstSession
	,pd.anAttendanceCode + [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''''AN'''',shf.Shift_StartTime,shf.Shift_SecondHalf_StartTime,shf.Shift_Endtime,E.isFlexible,SHF.Shift_id,pd.HRSWORK) + case  when Status is null then '''''''' else ''''(BL)'''' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull
	(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,convert(varchar(20),pd.date,101) as Date,
	pd.InTime,pd.OutTime,pd.HrsWork,case when pd.fnAttendanceCode=''''Weekly Off'''' and anAttendanceCode=''''Weekly Off'''' then	''''-'''' 
	when pd.fnAttendanceCode=''''Holiday''''or anAttendanceCode=''''Holiday'''' then ''''-''''
	else pd.SupposedWorkHours end ''''SupposedWorkHours'''',(pd.Attendance +  CASE pd.Status WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + isnull(pd.Status,'''''''')) as Status,((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked''  
	set @sqlQuery = @sqlQuery + '' ,(CASE pd.Shift_Id WHEN ''''-1'''' THEN ''''Weekly Off'''' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
	ISNULL(
				(
					CASE WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN ''''-'''' 
						 when pd.Shift_Id=-1 then ''''-''''
						 ELSE shf.shift_TotalWorkingHours END
				),''''00:00''''
			) as shift_TotalWorkingHours,
	e.Gender,	
	pd.EarlyOut,pd.LateIn,
	Case when Pd.NormOT is not null then cast(OtMins as varchar(50))
		 when Pd.OffOT is not null then cast(OtMins as varchar(50))
		 when pd.HolOT is not null then cast(OtMins as varchar(50))
		 else ''''00:00'''' end Overtime,
	CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''NormOTMins'''',
	CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''WeekOffOTMins'''',
	CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''HolidayOTMins'''',
	pd.NormOt as HrsOT,pd.OffOT,pd.HolOT,LateInMin,EarlyOutMin,	
	Case when pd.Shift_Id=-1 then 0
		 WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
		 else SUBSTRING(shf.shift_TotalWorkingHours,0,charindex('''':'''',shf.shift_TotalWorkingHours,0))*60+SUBSTRING(shf.shift_TotalWorkingHours,charindex('''':'''',shf.shift_TotalWorkingHours,0)+1,LEN(shf.shift_TotalWorkingHours))
		 end as TotDefWorkHrs
	,Case	when pd.Shift_Id=-1 then 0
			WHEN ((pd.fnAttendanceCode = ''''Holiday'''') OR (pd.anAttendanceCode = ''''Holiday'''')) THEN 0
			else SUBSTRING(pd.SupposedWorkHours,0,charindex('''':'''',pd.SupposedWorkHours,0))*60+SUBSTRING(pd.SupposedWorkHours,charindex('''':'''',pd.SupposedWorkHours,0)+1,LEN(pd.SupposedWorkHours))
	end as TotSupWorkHrs,case when OvertimeStatus is null then ''''-'''' else OvertimeStatus end,NightOrMorn,''''00:00'''',''''00:00'''',InNotation,OutNotation,PD.BREAKHOURS,LunchHours,BreakHoursMins,LunchHoursMins,
	Shift_StartTime,Shift_EndTime
	 ''
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e ''  
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''   
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''     
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.PrevShift_ID = shf.Shift_Id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + '' Inner join #EmpProcessedData on #EmpProcessedData.ProcessDate=pd.Date and #EmpProcessedData.SwipeCardNo=pd.Employee_Code_Id''  
		end   
		set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and 
		((e.employee_Status=1)
		or
		(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.Date,102)) )
		and((pd.date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''    
	if(@Gender<>''Both'')  
		begin  
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end		
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')  
		begin  
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''  
		end	
	if (@MinWorkHours<>'''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and #EmpProcessedData.TotalWorkMins >= '' + cast(@TotalMin as nvarchar(8))    
		end 	
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''     	
	insert into #TempMonthlyAttendance exec(@sqlQuery)	
	Create table #TempOutPunches
	(
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_Date] [datetime] NULL,
		PunchType varchar(20)
	)	
	--insert into #TempOutPunches
	--select Clk_EmpId,min(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	--inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	--where ta_tbl_clockdetails.IsVoid=0
	--and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	--and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	--and Clk_InPunchType in(''In'',''Shift In'')	
	--group by Clk_EmpId,Clk_Date,Clk_InPunchType
	--insert into #TempOutPunches
	--select Clk_EmpId,max(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	--inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	--where ta_tbl_clockdetails.IsVoid=0
	--and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	--and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	--and Clk_OutPunchType in(''Out'',''Shift Out'')	
	--group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,min(Clk_OutTime),Clk_Date,Clk_OutPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_OutPunchType in(''Lunch Out'')	
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType
	insert into #TempOutPunches
	select Clk_EmpId,max(Clk_InTime),Clk_Date,Clk_InPunchType from TA_Tbl_ClockDetails 
	inner join #TempEmployee on Clk_EmpId=EmpSwipeCardNo
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@fromDat as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@ToDat as nvarchar(20)), 102)
	and Clk_InPunchType in(''Lunch In'')	
	group by Clk_EmpId,Clk_Date,Clk_InPunchType	
	--update #TempMonthlyAttendance set InTime=case when (PunchType=''Shift In'' or PunchType=''In'') then TP.Clk_OutTime else TM.InTime end
	--from #TempMonthlyAttendance TM
	--inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	--and TP.PunchType in(''In'',''Shift In'')
	--update #TempMonthlyAttendance set OutTime=case when (PunchType=''Shift Out'' or PunchType=''Out'') then TP.Clk_OutTime else TM.OutTime end
	--from #TempMonthlyAttendance TM
	--inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	--and TP.PunchType in(''Out'',''Shift Out'')
	update #TempMonthlyAttendance set LunchInTime=case when PunchType=''Lunch In'' then TP.Clk_OutTime else TM.LunchInTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType=''Lunch In''
	update #TempMonthlyAttendance set LunchOutTime=case when PunchType=''Lunch Out'' then TP.Clk_OutTime else TM.LunchOutTime end
	from #TempMonthlyAttendance TM
	inner join #TempOutPunches TP on TM.Employee_Id=TP.[Clk_EmpId] and TM.Date=TP.Clk_Date
	and TP.PunchType=''Lunch Out''	
	update #TempMonthlyAttendance set FirstSession=case when (FirstSession=''Present'' OR FirstSession=''*Present'' OR FirstSession=''Holiday'' OR FirstSession=''*Holiday'' OR FirstSession=''Weekly Off'' OR FirstSession=''*Weekly Off'') and InNotation=''M'' then  FirstSession+'' #''	
	else #TempMonthlyAttendance.FirstSession end from #TempMonthlyAttendance
	update #TempMonthlyAttendance set SecondSession=case
	when (SecondSession=''Present'' OR SecondSession = ''*Present'' OR SecondSession =''Holiday'' OR SecondSession =''*Holiday'' OR SecondSession =''Weekly Off'' OR SecondSession =''*Weekly Off'')  and OutNotation=''M'' then  SecondSession+'' #''
	else #TempMonthlyAttendance.SecondSession end from #TempMonthlyAttendance
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	DECLARE @TimeFormat as nvarchar(25)
	select @TimeFormat=TimeFormat from TA_Tbl_DateandTimeFormat
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	select 
	case	when (@TimeFormat)=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchInTime,0)), 114)
			else	substring(LunchInTime,13,5)+'' '' + substring(LunchInTime,18,2) 					
	end LunchIn,
	case	when (@TimeFormat)=''hh:mm'' then 
					CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,LunchOutTime,0)), 114)
			else	substring(LunchOutTime,13,5)+'' '' + substring(LunchOutTime,18,2) 					
	end LunchOut
	,FirstSession,SecondSession ,Employee_Id,empName,BranchName,Designation,
	case when cast(@dateFormat as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
	else CONVERT(VARCHAR, Date, @dateFormat) end AS
	Date,
	InTime,OutTime,HrsWork,SupposedWorkHours,
	Status,convert(int,isnull(TotalMinsWorked,''0''))TotalMinsWorked,CASE WHEN Shift_ShortName=''Weekly Off'' THEN ''Off'' ELSE #TempMonthlyAttendance.Shift_ShortName END Shift_ShortName,
	shift_TotalWorkingHours,Gender,EarlyOut,LateIn,overtime,NormOTMin,OffOTMin,HolOTMin,NormOT,OffOT,HolOT,
	convert(int,lateinMin)as lateinMin,
	convert(int,EarlyOutMin)as EarlyOutMin,TotDefWorkHrs,TotSupWorkHrs,overtimeStatus,BreakHoursMins,
	BreakHours=isnull(BreakHours,''-''),LunchHoursMins,LunchHours=isnull(LunchHours,''-''),
	Shift_StartTime,Shift_EndTime
	from #TempMonthlyAttendance
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #EmpProcessedData  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployee  
	drop table #TempMonthlyAttendance	 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Proc_TA_RptMonthlyAttendance_Ardlysis @MINWORKHOURS=N'''',@FROMDAT=''2019-12-11 00:00:00'',@TODAT=''2019-12-11 00:00:00'',
@EMPLOYEENAME=N'''',@LEVELID=N''1'',@EMPLOYEEID=N'''',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N''SUPERADMIN'',
@GRADELEVEL=N''0'',@EMPSWIPECARD=N'''',@PARENTID=1,@DESIGNATIONID=0,@GENDER=N''BOTH'',@SHIFT=0,@DATALOADING=0,@EMPAUTOID=0,@EXPORT=0
,@FromDashboard=0
*/

--for attendance summary and reports menu monthly @FromDashboard = 0
-- for dashboard present tile click @FromDashboard = 1

CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance_Ardlysis]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
	,@FromDashboard  INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT))   
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10)
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
    INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
	IF not(@local_GENDER=''BOTH'')  
	BEGIN  
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND EMP.GENDER = '''''' + CAST(@local_GENDER AS NVARCHAR(8)) + '''''' ''  
	END	
	IF(@ISREPORTINGTO > 0)
    BEGIN
		SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	END
	--IF(@EMPAUTOID > 0)
 --   BEGIN
	--	SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
	--END
	SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@local_TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@local_EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	IF NOT (@local_EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.EMPLOYEE_CODE_ID ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			vp.INTIME,
			vp.OUTTIME,
			vp.SHIFT_ID,
			vp.HRSWORK,
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		((@local_DATALOADING=0 or 
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY'') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY''))))
		AND ((INTIME IS NOT NULL OR not(INTIME=''00:00'')) OR (OUTTIME IS NOT NULL OR not(OUTTIME=''00:00''))))
		or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))
	)
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE=''CL'' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''PM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''AM'' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''AM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''PM'' AND PD.OUTTIME>''00:00 AM'' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	DECLARE @POS AS INT  
	SET @POS = CHARINDEX('':'',@local_MINWORKHOURS)  
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = SUBSTRING(@local_MINWORKHOURS,0,@POS)*60 + SUBSTRING(@local_MINWORKHOURS,@POS+1,2)  
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(10),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)		
	)
	CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_INNOTATION_OUTNOTATION] ON [DBO].#TEMPMONTHLYATTENDANCE(FIRSTSESSION,SECONDSESSION,INNOTATION,OUTNOTATION) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_FIRSTSESSION_SECONDSESSION_DATE] ON [DBO].#TEMPMONTHLYATTENDANCE(FIRSTSESSION,SECONDSESSION,DATE) ON [PRIMARY]  
	IF (@local_MINWORKHOURS<>'''')  
		BEGIN  
			DECLARE @SQLQUERYTEMP AS VARCHAR(MAX)    
			SET @SQLQUERYTEMP=''''   
			SET @SQLQUERYTEMP =  ''SELECT PD.EMPLOYEE_CODE_ID AS SWIPECARDNO,PD.DATE AS DATE,((SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),0,CHARINDEX('''':'''',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),(LEN(PD.HRSWORK)-1),2))) AS TOTALWORKMINS FROM TA_TBL_EMPLOYEE E ''
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPDESIGNATION EDESIG ON E.EMPLOYEE_ID = EDESIG.EMPLOYEEID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''  
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' LEFT JOIN TA_TBL_SHIFT SH ON SH.SHIFT_ID = PD.SHIFT_ID ''
			SET @SQLQUERYTEMP = @SQLQUERYTEMP + '' WHERE  (	(E.EMPLOYEE_STATUS = 1) OR 	
			(E.EMPLOYEE_STATUS = 0 AND  CONVERT(NVARCHAR(11), E.INACTIVEDATE,102) >= CONVERT(NVARCHAR(11),PD.DATE,102)
			)) AND (E.ISDELETED = 0) AND (E.REPORT_EXCLUDE = 0)''
			INSERT INTO #EMPPROCESSEDDATA EXEC(@SQLQUERYTEMP)  
		END
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''''PRESENT'''' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''FN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END 
			ELSE PD.FNATTENDANCECODE
	END
	AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''''PRESENT'''' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''''AN'''',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''''''' ELSE ''''(BL)'''' END  
			ELSE PD.ANATTENDANCECODE
	END
	AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''''''') AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&'''') AS BRANCHNAME,REPLACE(T.TITLENAME,''''&AMP;'''',''''&'''') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''''WEEKLY OFF'''' AND ANATTENDANCECODE=''''WEEKLY OFF'''' THEN	''''-'''' 
	WHEN PD.FNATTENDANCECODE=''''HOLIDAY''''OR ANATTENDANCECODE=''''HOLIDAY'''' THEN ''''-''''
	ELSE PD.SUPPOSEDWORKHOURS END ''''SUPPOSEDWORKHOURS'''',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + ISNULL(PD.STATUS,'''''''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),0,CHARINDEX('''':'''',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED''  
	SET @SQLQUERY = @SQLQUERY + '' ,(CASE PD.SHIFT_ID WHEN ''''-1'''' THEN ''''WEEKLY OFF'''' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN ''''-'''' 
						 WHEN PD.SHIFT_ID=-1 THEN ''''-''''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''''00:00''''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.OFFOT IS NOT NULL	THEN
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
						CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
								ELSE CAST(OTMINS AS VARCHAR(50)) 
						END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,''''00:00'''')=''''00:00''''	THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''NORMOTMINS'''',
	CASE WHEN ISNULL(OFFOT,''''00:00'''')=''''00:00''''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''WEEKOFFOTMINS'''',
	CASE WHEN ISNULL(HOLOT,''''00:00'''')=''''00:00''''		THEN 0 ELSE CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
																		ELSE CAST(OTMINS AS VARCHAR(50)) 
																END
		 END AS ''''HOLIDAYOTMINS'''',
	CASE WHEN ISNULL(NORMOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(NORMOT AS VARCHAR(50)) 
																		END 
		 END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																				ELSE CAST(OFFOT AS VARCHAR(50)) 
																		END
		 END,
	CASE WHEN ISNULL(HOLOT,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
																			ELSE CAST(HOLOT AS VARCHAR(50)) 
																	END
		 END,
	LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''''-'''' ELSE OVERTIMESTATUS END,NIGHTORMORN,''''00:00'''',''''00:00'''',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CATEGORYNAME,WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),FNATTENDANCECODE,ANATTENDANCECODE,
	Case when FNATTENDANCECODE=ANATTENDANCECODE then 
					case	when ANATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(ANATTENDANCECODE,1,1)
							else ANATTENDANCECODE
					end
		 else 
				case	when FNATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(FNATTENDANCECODE,1,1)
						else FNATTENDANCECODE
				end
				+''''/''''+
				case	when ANATTENDANCECODE in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''') then substring(ANATTENDANCECODE,1,1)
						else ANATTENDANCECODE
				end
		end,
	CASE WHEN ISNULL(SPEC_NormOT1,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
																			END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
																					ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
																			END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,''''00:00'''')=''''00:00''''	THEN ''''00:00'''' ELSE	CASE	WHEN OVERTIMESTATUS!=''''Approved'''' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
																					ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
																			END
		 END''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     
	SET @SQLQUERY = @SQLQUERY + '' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID ''
	IF (@local_MINWORKHOURS<>'''')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID''  
		END   
		SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
	
		AND((PD.DATE >= CONVERT(DATETIME, '''''' + CAST(@local_FROMDAT AS NVARCHAR(11)) + '''''', 102) AND 
		PD.DATE <= CONVERT(DATETIME, '''''' + CAST(@local_TODAT AS NVARCHAR(11)) + '''''', 102)))
		''    
	--IF(@FromDashboard<>0)
	--	Begin
	--		SET @SQLQUERY = @SQLQUERY + '' AND (PD.FNATTENDANCECODE=''''Present'''' or PD.FNATTENDANCECODE=''''Present'''') ''  
	--	End
	IF(@local_USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @local_GRADELEVEL + ''''  
		END	
	IF (@local_MINWORKHOURS<>'''')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + ''AND #EMPPROCESSEDDATA.TOTALWORKMINS >= '' + CAST(@TOTALMIN AS NVARCHAR(8))    
		END	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	

	UPDATE #TEMPMONTHLYATTENDANCE SET 
	FIRSTSESSION=
		CASE	WHEN FIRSTSESSION IN(''PRESENT'',''*PRESENT'',''HOLIDAY'',''*HOLIDAY'',''WEEKLY OFF'',''*WEEKLY OFF'') AND INNOTATION=''M'' THEN  FIRSTSESSION+'' #''	
				ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION 
		END,
	SECONDSESSION=
		CASE	WHEN SECONDSESSION IN(''PRESENT'',''*PRESENT'',''HOLIDAY'',''*HOLIDAY'',''WEEKLY OFF'',''*WEEKLY OFF'') AND OUTNOTATION=''M'' THEN  SECONDSESSION+'' #''
				ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION 
		END
	FROM #TEMPMONTHLYATTENDANCE
		DECLARE @DATEFORMAT AS INT
		DECLARE @TIMEFORMAT AS NVARCHAR(10)
		SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()

		Create table #ClockDetailsPivot(
		EmpCodeId nvarchar(40),EmployeeAutoId int, Clockdate datetime, clk_Id int, Clocktime datetime, timename varchar(20)
		)

		insert into #ClockDetailsPivot
		select E.Employee_Code_Id,E.Employee_Id as EmployeeAutoId,Clk_Date,[Clk_Id],cast([Clk_InTime] as time(0)) as Clk_InTime,
		''intime''+ convert(varchar, ROW_NUMBER() over(partition by Clk_EmpId,clk_date order by Clk_InTime,Clk_EmpId)) as timename
		from TA_Tbl_ClockDetails 
		inner join TA_Tbl_Employee E on E.SwipeCardNo = TA_Tbl_ClockDetails.Clk_EmpId
		left join #TEMPMONTHLYATTENDANCE PD on PD.EMPLOYEE_ID = E.Employee_Code_Id  and Date = TA_Tbl_ClockDetails.Clk_Date

		where 
		ta_tbl_clockdetails.IsVoid=0 and 
		ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102)
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,CAST( @local_TODAT AS NVARCHAR(50)), 102)
		and Clk_InPunchType is not null 
		--and Clk_OutPunchType is not null
		
	    order by E.[Employee_Id]

		insert into #ClockDetailsPivot
		select E.Employee_Code_Id,E.Employee_Id as EmployeeAutoId,Clk_Date,[Clk_Id],cast([Clk_OutTime] as time(0)) as Clk_OutTime,
		''outtime''+ convert(varchar, ROW_NUMBER()over(partition by Clk_EmpId,clk_date order by Clk_InTime,Clk_EmpId)) as timename
		 from TA_Tbl_ClockDetails 
		inner join TA_Tbl_Employee E on E.SwipeCardNo = TA_Tbl_ClockDetails.Clk_EmpId		
		left join #TEMPMONTHLYATTENDANCE PD on PD.EMPLOYEE_ID = E.Employee_Code_Id and Date = TA_Tbl_ClockDetails.Clk_Date
		
		where 
		ta_tbl_clockdetails.IsVoid=0 and
		ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102)
		and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,CAST( @local_TODAT AS NVARCHAR(50)), 102)
		--and Clk_InPunchType is not null 
		and Clk_OutPunchType is not null	

		order by E.[Employee_Id]

	    --Pivot table

		create table #MonthlyDataset2 (EmpCodeId nvarchar(40),EmployeeAutoId int, Clockdate datetime, 
		intime1 datetime, outtime1 datetime,
		intime2 datetime, outtime2 datetime,
		intime3 datetime, outtime3 datetime,
		intime4 datetime, outtime4 datetime,
		intime5 datetime, outtime5 datetime
		)
		insert into #MonthlyDataset2 
		SELECT EmpCodeId,EmployeeAutoId,convert(date,Clockdate)Clockdate, 
		intime1,outtime1,intime2,outtime2,intime3,outtime3,intime4,outtime4,intime5,outtime5 
		 FROM   
		(SELECT EmpCodeId, EmployeeAutoId,Clockdate, Clocktime,timename FROM #ClockDetailsPivot) as Tab1  
		PIVOT  
		(  
		Max(Clocktime) FOR timename IN (intime1,intime2,intime3,intime4,intime5,outtime1,outtime2,outtime3,outtime4,outtime5)) AS Tab2 

	--select * from #TEMPMONTHLYATTENDANCE

	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		Format(ds2.intime1,''hh:mm tt'') as Intime1,
		Format(ds2.outtime1,''hh:mm tt'') as OutTime1,		 
		Format(ds2.intime2,''hh:mm tt'') as Intime2,
		Format(ds2.outtime2,''hh:mm tt'') as OutTime2,
		Format(ds2.intime3,''hh:mm tt'') as Intime3,
		Format(ds2.outtime3,''hh:mm tt'') as OutTime3,
		Format(ds2.intime4,''hh:mm tt'') as Intime4,
		Format(ds2.outtime4,''hh:mm tt'') as OutTime4,
		Format(ds2.intime5,''hh:mm tt'') as Intime5,
		Format(ds2.outtime5,''hh:mm tt'') as OutTime5,
		HRSWORK,
		dbo.ConvertMinsToHours(case when ds2.intime1 is not null and ds2.outtime1 is not null then DATEDIFF(MINUTE, ds2.intime1 , ds2.outtime1) else 0 end 
		+ case when ds2.intime2 is not null and ds2.outtime2 is not null then DATEDIFF(MINUTE, ds2.intime2 , ds2.outtime2)else 0 end 
		+ case when ds2.intime3 is not null and ds2.outtime3 is not null then DATEDIFF(MINUTE, ds2.intime3 , ds2.outtime3)else 0 end 
		+ case when ds2.intime4 is not null and ds2.outtime4 is not null then DATEDIFF(MINUTE, ds2.intime4 , ds2.outtime4)else 0 end 
		+ case when ds2.intime5 is not null and ds2.outtime5 is not null then DATEDIFF(MINUTE, ds2.intime5 , ds2.outtime5)else 0 end 
		)
		AS AcutalWorkedHours,
		LATEIN,
		EARLYOUT,
		NORMOT,
		LUNCHHOURS ,
		BREAKHOURS,
		FIRSTSESSION,
		SECONDSESSION,	
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,	
		CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
		StatusCode,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		FROM #TEMPMONTHLYATTENDANCE 

		left join  #MonthlyDataset2 ds2 on (ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
		and ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID)
		--where ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID and ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
		where ((@FromDashboard = 1 and (FIRSTSESSION=''Present'' or SECONDSESSION=''Present'')) or (@FromDashboard = 0))
		ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	ELSE
	BEGIN
		SELECT			
				EMPLOYEE_ID AS [EMPLOYEE ID],
				EMPNAME AS [EMPLOYEE NAME],		
				CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
						ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) 
				END AS DATE,	
				CASE	WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' 
						ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME 
				END [SHIFT SHORTNAME],
				INTIME AS [IN TIME],
				OUTTIME AS [OUT TIME],
				Format(ds2.intime1,''hh:mm tt'') as Intime1,
				Format(ds2.outtime1,''hh:mm tt'') as OutTime1,		 
				Format(ds2.intime2,''hh:mm tt'') as Intime2,
				Format(ds2.outtime2,''hh:mm tt'') as OutTime2,
				Format(ds2.intime3,''hh:mm tt'') as Intime3,
				Format(ds2.outtime3,''hh:mm tt'') as OutTime3,
				Format(ds2.intime4,''hh:mm tt'') as Intime4,
				Format(ds2.outtime4,''hh:mm tt'') as OutTime4,
				Format(ds2.intime5,''hh:mm tt'') as Intime5,
				Format(ds2.outtime5,''hh:mm tt'') as OutTime5,
				HRSWORK AS [HOURS WORKED],					
			    dbo.ConvertMinsToHours(case when ds2.intime1 is not null and ds2.outtime1 is not null then DATEDIFF(MINUTE, ds2.intime1 , ds2.outtime1) else 0 end 
				+ case when ds2.intime2 is not null and ds2.outtime2 is not null then DATEDIFF(MINUTE, ds2.intime2 , ds2.outtime2)else 0 end 
				+ case when ds2.intime3 is not null and ds2.outtime3 is not null then DATEDIFF(MINUTE, ds2.intime3 , ds2.outtime3)else 0 end 
				+ case when ds2.intime4 is not null and ds2.outtime4 is not null then DATEDIFF(MINUTE, ds2.intime4 , ds2.outtime4)else 0 end 
				+ case when ds2.intime5 is not null and ds2.outtime5 is not null then DATEDIFF(MINUTE, ds2.intime5 , ds2.outtime5)else 0 end 
				)
				 AS AcutalWorkedHours,
				LATEIN,
				EARLYOUT,				
				NORMOT,
				BREAKHOURS,
				LUNCHHOURS ,
				FIRSTSESSION AS [FIRST SESSION],
				SECONDSESSION AS [SECOND SESSION],
				SHIFT_TOTALWORKINGHOURS AS [DEFINED WORK HOURS],			
				SPEC_NormOT1,
				SPEC_NormOT2,		
				SPEC_OffOT1,
				SPEC_OffOT2,
				SPEC_HOLOT1,
				SPEC_HOLOT2,
				SUPPOSEDWORKHOURS,
				CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
				Case when FNATTENDANCECODE in(''Present'',''Present #'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Present'',''Present #'') then 0.5 else 0.0 end as present,
				Case when FNATTENDANCECODE in(''Absent'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Absent'') then 0.5 else 0.0 end as Absent,
				Case when FNATTENDANCECODE in(''Weekly Off'') then 0.5 else 0.0 end + case when ANATTENDANCECODE IN(''Weekly Off'') then 0.5 else 0.0 end as WeeklyOff,
				Case when FNATTENDANCECODE in(''Holiday'',''RH'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Holiday'',''RH'') then 0.5 else 0.0 end as Holiday,
				Case when FNATTENDANCECODE not in(''Present'',''Present #'',''Absent'',''Weekly Off'',''Holiday'',''RH'') then 0.5 else 0.0 end + case when ANATTENDANCECODE not in(''Present'',''Present #'',''Absent'',''Weekly Off'',''Holiday'',''RH'')then 0.5 else 0.0 end as Leave
				,StatusCode,
				OVERTIME,
				NORMOTMIN,
				OFFOTMIN,
				HOLOTMIN,				
				OFFOT,
				HOLOT,
				LATEINMIN,
				EARLYOUTMIN,
				TOTDEFWORKHRS,
				TOTSUPWORKHRS,
				OVERTIMESTATUS,
				NIGHTORMORN,
				LUNCHINTIME,
				LUNCHOUTTIME
				,INNOTATION,
				OUTNOTATION,			
				BREAKHOURSMINS,
				LUNCHHOURSMINS,
				SHIFT_STARTTIME,
				SHIFT_ENDTIME,
				WEEKDAY_WORKHRS,
				WEEKNUMBER ,
				FNATTENDANCECODE,
				ANATTENDANCECODE,
				DESIGNATION,
				DATEPART(D,DATE) as processDay,
				left(datename(MONTH,DATE),3) as processMonth,
				DENSE_RANK()OVER(ORDER BY EMPLOYEE_ID) AS [SL.NO],
				BRANCHNAME AS LEVEL,
				DESIGNATION,
				CATEGORYNAME AS [EMPLOYEE CATEGORY],
				GENDER,
				BRANCHNAME,
				DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth	
		        FROM #TEMPMONTHLYATTENDANCE 
			    left join  #MonthlyDataset2 ds2 on (ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
			    and ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID)
				--where ds2.EmpCodeId = #TEMPMONTHLYATTENDANCE.EMPLOYEE_ID and ds2.Clockdate =  #TEMPMONTHLYATTENDANCE.DATE 
				where ((@FromDashboard = 1 and (FIRSTSESSION=''Present'' or SECONDSESSION=''Present'')) or (@FromDashboard = 0))
		        ORDER BY EMPLOYEE_ID,processDate,WEEKNUMBER
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END	

	drop table #ClockDetailsPivot

	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyAttendance]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyAttendance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Proc_TA_RptMonthlyAttendance @MINWORKHOURS=N'''',@FROMDAT=''2020-01-01 00:00:00'',@TODAT=''2020-07-30 00:00:00'',
@EMPLOYEENAME=N'''',@LEVELID=N'''',@EMPLOYEEID=N'''',@EMPLOYEECATEGORY=0,@EMPLOYEETYPE=0,@USERGROUPNAME=N''SUPERADMIN'',
@GRADELEVEL=N'''',@EMPSWIPECARD=N'''',@PARENTID=0,@DESIGNATIONID=0,@GENDER=N''both'',@SHIFT=2,@DATALOADING=0,@EMPAUTOID=2,@EXPORT=7
*/
CREATE  PROCEDURE [dbo].[Proc_TA_RptMonthlyAttendance]
(   
	@MINWORKHOURS AS NVARCHAR(10)=null,
	@FROMDAT DATETIME=null,
	@TODAT DATETIME=null,
	@EMPLOYEENAME NVARCHAR(MAX)=null,
	@LEVELID NVARCHAR(MAX)=null,
	@EMPLOYEEID NVARCHAR(MAX)=null,
	@EMPLOYEECATEGORY INT=null,
	@EMPLOYEETYPE INT=0,
	@USERGROUPNAME NVARCHAR(250)=null,
	@GRADELEVEL NVARCHAR(20)=null,
	@EMPSWIPECARD NVARCHAR(20)=null,
	@PARENTID INT=0,
	@DESIGNATIONID INT=0,
	@GENDER NVARCHAR(10)=null,
	@SHIFT INT=0,
	@DATALOADING INT=0,
	@EMPAUTOID BIGINT=0,
	@EXPORT INT=0
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	DECLARE @local_MINWORKHOURS AS NVARCHAR(10)
	DECLARE @local_FROMDAT DATETIME
	DECLARE @local_TODAT DATETIME
	DECLARE @local_EMPLOYEENAME NVARCHAR(MAX)
	DECLARE @local_LEVELID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEEID NVARCHAR(MAX)
	DECLARE @local_EMPLOYEECATEGORY INT
	DECLARE @local_EMPLOYEETYPE INT
	DECLARE @local_USERGROUPNAME NVARCHAR(250)
	DECLARE @local_GRADELEVEL NVARCHAR(20)
	DECLARE @local_EMPSWIPECARD NVARCHAR(20)
	DECLARE @local_PARENTID INT
	DECLARE @local_DESIGNATIONID INT
	DECLARE @local_GENDER NVARCHAR(10)
	DECLARE @local_SHIFT INT
	DECLARE @local_DATALOADING INT
	DECLARE @local_EMPAUTOID BIGINT
	DECLARE @local_EXPORT INT
	SET @local_MINWORKHOURS		= LTRIM(RTRIM(@MINWORKHOURS))
    SET @local_FROMDAT			= LTRIM(RTRIM(@FROMDAT))
    SET @local_TODAT			= LTRIM(RTRIM(@TODAT))
    SET @local_EMPLOYEENAME		= LTRIM(RTRIM(@EMPLOYEENAME))
    SET @local_LEVELID			= LTRIM(RTRIM(@LEVELID))
    SET @local_EMPLOYEEID		= LTRIM(RTRIM(@EMPLOYEEID))    
    SET @local_EMPLOYEECATEGORY	= LTRIM(RTRIM(@EMPLOYEECATEGORY))
    SET @local_EMPLOYEETYPE     = LTRIM(RTRIM(@EMPLOYEETYPE))
    SET @local_USERGROUPNAME    = LTRIM(RTRIM(@USERGROUPNAME))
    SET @local_GRADELEVEL		= LTRIM(RTRIM(@GRADELEVEL))
    SET @local_EMPSWIPECARD		= LTRIM(RTRIM(@EMPSWIPECARD))
    SET @local_PARENTID			= LTRIM(RTRIM(@PARENTID))    
    SET @local_DESIGNATIONID	= LTRIM(RTRIM(@DESIGNATIONID))
    SET @local_GENDER			= LTRIM(RTRIM(@GENDER))
    SET @local_SHIFT			= LTRIM(RTRIM(@SHIFT))
    SET @local_DATALOADING		= LTRIM(RTRIM(@DATALOADING))
    SET @local_EMPAUTOID		= LTRIM(RTRIM(@EMPAUTOID))
    SET @local_EXPORT			= LTRIM(RTRIM(@EXPORT)) 
     
	DECLARE @SQLTEMPPROCESSEDDATA	VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1	VARCHAR(8000)
	DECLARE @SQLEMPLEVEL			NVARCHAR(4000)
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))		
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(15),
		FNATTENDANCECODE NVARCHAR(15),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS decimal(18,0),
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		ActNormOTmins int,
		ActNormOTHrs varchar(5),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOTMins1	int,
		SPEC_NormOT2	varchar(10),
		SPEC_NormOTMins2	int,
		SPEC_OffOT1		varchar(10),
		SPEC_OffOTMins1	int,
		SPEC_OffOT2		varchar(10),
		SPEC_OffOTMins2	int,
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOTMins1	int,
		SPEC_HOLOT2		varchar(10),
		SPEC_HOLOTMins2	int,			
		Modified_Spec_NormOTMins1 int,
		Modified_Spec_NormOTMins2 int,
		Modified_Spec_OffOTMins1 int,
		Modified_Spec_OffOTMins2 int,
		Modified_Spec_HolOTMins1 int,
		Modified_Spec_HolOTMins2 int,
		Modified_Spec_NormOTHrs1 varchar(10),
		Modified_Spec_NormOTHrs2 varchar(10),
		Modified_Spec_OffOTHrs1 varchar(10),
		Modified_Spec_OffOTHrs2 varchar(10),
		Modified_Spec_HolOTHrs1 varchar(10),
		Modified_Spec_HolOTHrs2 varchar(10),
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)
	)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	if(@local_USERGROUPNAME!=''Superadmin'')
	BEGIN
		SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_USERGROUPNAME
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EMPAUTOID) AS EMPAUTOID  
		INSERT INTO #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_SANCAUTHORITY](@local_EMPAUTOID) AS EMPAUTOID
	END
    INSERT INTO #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_USERGROUPNAME,@local_PARENTID) AS LEVELID  
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @local_TODAT,@local_EMPLOYEEID,@local_DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @local_TODAT,@local_EMPLOYEEID,@local_EMPLOYEECATEGORY
	CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
	CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
	
	IF(@local_EMPLOYEEID IS NOT NULL AND @local_EMPLOYEEID <> '''')
		BEGIN			
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@local_EMPLOYEEID)
		END	
	IF(@local_EMPLOYEENAME IS NOT NULL AND @local_EMPLOYEENAME <> '''')
		BEGIN			
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@local_EMPLOYEENAME,'','')
		END	
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
	(
		SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
		INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
		INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
		WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0
		and(@local_GENDER=''BOTH'' or EMP.GENDER = @local_GENDER)
		and((@ISREPORTINGTO=0 or @local_USERGROUPNAME=''Superadmin'')or (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)))
		and(isnull(@local_EMPLOYEEID,'''')='''' or EMP.Employee_Code_Id in(select * from #EMPLOYEEID))
		and(isnull(@local_EMPLOYEENAME,'''')='''' or EMP.Employee_Code_Id in(select * from #EMPLOYEENAME))
		GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,@local_TODAT, 102) AND EL.LEVELID IS NOT NULL	
	INSERT INTO #TEMPPROCESSEDDATA 
	select #EMPLEVEL.EMPLOYEEID,
			vp.DATE,
			vp.EMPLOYEE_CODE_ID,
			--updated by velumani for Abraj Monthly attendance design issue
			--case when vp.INTIME=''00:00'' then '''' else vp.INTIME end,
			--case when vp.OUTTIME=''00:00'' then '''' else vp.OUTTIME end,
			--vp.SHIFT_ID,
			--case when vp.HRSWORK=''00:00'' then '''' else vp.HRSWORK end,
			(case when  vp.INTIME is null or vp.INTIME=''00:00''  then null  else vp.INTIME end) as INTIME,
			(case when  vp.OUTTIME is null or vp.OUTTIME=''00:00'' then null else vp.OUTTIME end) as OUTTIME,
			vp.SHIFT_ID,
			(case when  vp.HRSWORK is null or vp.HRSWORK=''00:00'' then null else vp.HRSWORK end) as HRSWORK,
		-------------------------
			vp.WORKHRS,
			vp.STATUS,
			vp.ATTENDANCE,
			vp.ANATTENDANCECODE,
			vp.FNATTENDANCECODE,
			vp.SHIFT_ID,
			vp.PROCESS_REC_ID,
			vp.SHIFT_STARTTIME,
			CAST(vp.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			vp.NORMOT,
			vp.OFFOT,
			vp.HOLOT,
			round(OtMins,0),
			CASE WHEN CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''.'',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS,
			case	when Shift_Id=-1 then vp.ActOffOTMins
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOTMins
			else ActOTMins end,
			case	when Shift_Id=-1 then vp.ActOffOT
					when FNAttendanceCode=''Holiday'' and ANAttendanceCode=''Holiday'' then vp.ActHolOT
			else ActNormOT end,
			vp.SPEC_NormOT1,
			vp.SPEC_NormOTMins1,
			vp.SPEC_NormOT2,
			vp.SPEC_NormOTMins2,
			vp.SPEC_OffOT1,
			vp.SPEC_OffOTMins1,
			vp.SPEC_OffOT2,
			vp.SPEC_OffOTMins2,
			vp.SPEC_HOLOT1,
			vp.SPEC_HOLOTMins1,
			vp.SPEC_HOLOT2,
			vp.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2,
			vp.InLocation ,
			vp.OutLocation,
			Vp.In_Latitude,
			Vp.In_Longitude,
			Vp.Out_Latitude,
			Vp.Out_Longitude
	from VW_FetchDataFromProcessedData vp
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.SWIPECARD=vp.EMPLOYEE_CODE_ID  
	Left outer join Ta_tbl_specialOvertimeDetails spot on (vp.Employee_Code_Id=spot.Employee_code_id and vp.Date=spot.Date)
	WHERE vp.ProcessFlag=1 AND (vp.DATE >= CONVERT(DATETIME,CAST( @local_FROMDAT AS NVARCHAR(50)), 102))    
	AND (vp.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102)) 
	and (@local_SHIFT=0 or vp.SHIFT_ID=@local_SHIFT)
	and 
	(
		(@local_DATALOADING=0 or 
		((
		(@local_DATALOADING=1 and vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY'') or
		(@local_DATALOADING=2 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))or
		(@local_DATALOADING=3 AND (((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'')OR (vp.SHIFT_ID= -1))
        OR (vp.FNATTENDANCECODE= ''HOLIDAY'' AND vp.ANATTENDANCECODE= ''HOLIDAY''))))
		AND ((INTIME IS NOT NULL OR not(INTIME=''00:00'')) OR (OUTTIME IS NOT NULL OR not(OUTTIME=''00:00'')))))
			or
		(@local_DATALOADING=4 AND ((vp.FNATTENDANCECODE= ''WEEKLY OFF'' AND vp.ANATTENDANCECODE= ''WEEKLY OFF'') OR (vp.SHIFT_ID= -1)))
	)
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE=''CL'' 	
	------------------------------------------------------CURRENT DATE IS WEEKLY OFF, TO GET THE PREVIOUS DATE SHIFT--------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-1,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE SHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	--------------------------------------------------------AGAIN THE PREVIOUS DATE IS ALSO WEEKLY OFF MEANS, TO GET THE PREVIOUS DATE SHIFT---------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET PREVSHIFT_ID=B.SHIFT_ID FROM #TEMPPROCESSEDDATA T INNER JOIN
	(
		SELECT P.EMPLOYEE_CODE_ID,A.DATE,P.SHIFT_ID FROM TA_TBL_PROCESSEDDATA P INNER JOIN
		(
			SELECT EMPLOYEE_CODE_ID,DATEADD(D,-2,DATE) AS PREVDATE,DATE
			FROM #TEMPPROCESSEDDATA WHERE PREVSHIFT_ID=-1 	
		)
		AS A ON A.EMPLOYEE_CODE_ID=P.EMPLOYEE_CODE_ID AND P.DATE=A.PREVDATE
		WHERE
		(P.DATE >= CONVERT(DATETIME,CAST(@local_FROMDAT AS NVARCHAR(50)), 102))    
		AND (P.DATE <= CONVERT(DATETIME,CAST(@local_TODAT AS NVARCHAR(50)), 102))
	)AS B ON T.EMPLOYEE_CODE_ID=B.EMPLOYEE_CODE_ID AND T.DATE=B.DATE
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	UPDATE #TEMPPROCESSEDDATA SET NIGHTORMORN= CASE WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''PM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''AM'' THEN 1 
													WHEN SUBSTRING(S.SHIFT_STARTTIME,7,8)=''AM'' AND SUBSTRING(S.SHIFT_ENDTIME,7,8)=''PM'' AND PD.OUTTIME>''00:00 AM'' THEN 1
													ELSE 0 END 
	FROM #TEMPPROCESSEDDATA PD INNER JOIN TA_TBL_SHIFT S ON PD.PREVSHIFT_ID=S.SHIFT_ID
	
	DECLARE @TOTALMIN AS INT  
	SET @TOTALMIN = dbo.ConvertHoursToMinites(ISNULL(@local_MINWORKHOURS,''00:00''))
	if(@TOTALMIN='''') set @TOTALMIN=0
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		FIRSTSESSION VARCHAR(250),
		SECONDSESSION VARCHAR(250),
		ATTENDANCE VARCHAR(50),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),
		SUPPOSEDWORKHOURS VARCHAR(30),
		STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),
		SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),
		GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		OVERTIME INT,
		NORMOTMIN INT,
		OFFOTMIN INT,
		HOLOTMIN INT,
		NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),
		HOLOT NVARCHAR(20),
		LATEINMIN INT,
		EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,
		TOTSUPWORKHRS INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,
		LUNCHINTIME NVARCHAR(20),
		LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CATEGORYNAME 	NVARCHAR(100),
		WEEKDAY_WORKHRS NVARCHAR(100),
		WEEKNUMBER INT,
		FNATTENDANCECODE varchar(100),
		ANATTENDANCECODE varchar(100),
		StatusCode varchar(50),
		-----
		SPEC_NormOT1	varchar(10),
		SPEC_NormOT2	varchar(10),
		SPEC_OffOT1		varchar(10),
		SPEC_OffOT2		varchar(10),
		SPEC_HOLOT1		varchar(10),
		SPEC_HOLOT2		varchar(10)	,	
		InLocation varchar(500),
		OutLocation varchar(500),
		InLatitude varchar(20),
		InLongitude varchar(20),
		OutLatitude varchar(20),
		OutLongitude varchar(20)
	)	
	INSERT INTO #TEMPMONTHLYATTENDANCE 
	SELECT 
	CASE	WHEN PD.FNATTENDANCECODE=''PRESENT'' THEN PD.FNATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.FNATTENDANCECODE,E.EMPLOYEE_CODE_ID,''FN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END 
			ELSE PD.FNATTENDANCECODE
	END + case when INNOTATION=''M'' then '' #'' else '''' end AS FIRSTSESSION,
	CASE	WHEN PD.ANATTENDANCECODE =''PRESENT'' THEN PD.ANATTENDANCECODE + [DBO].[FUNC_TA_ONDUTY](PD.DATE,PD.ANATTENDANCECODE,E.EMPLOYEE_CODE_ID,''AN'',SHF.SHIFT_STARTTIME,SHF.SHIFT_SECONDHALF_STARTTIME,SHF.SHIFT_ENDTIME,E.ISFLEXIBLE,SHF.SHIFT_ID,PD.HRSWORK) + CASE  WHEN STATUS IS NULL THEN '''' ELSE ''(BL)'' END  
			ELSE PD.ANATTENDANCECODE
	END + case when OUTNOTATION=''M'' then '' #'' else '''' end AS SECONDSESSION, 
	PD.ATTENDANCE,
	E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''') AS EMPNAME,
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''&AMP;'',''&'') AS BRANCHNAME,
	REPLACE(T.TITLENAME,''&AMP;'',''&'') AS DESIGNATION,
	CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,
	PD.OUTTIME,
	PD.HRSWORK,
	CASE	WHEN PD.FNATTENDANCECODE=''WEEKLY OFF'' AND ANATTENDANCECODE=''WEEKLY OFF'' THEN	''-'' 
			WHEN PD.FNATTENDANCECODE=''HOLIDAY''OR ANATTENDANCECODE=''HOLIDAY'' THEN ''-''
			ELSE PD.SUPPOSEDWORKHOURS 
	END ''SUPPOSEDWORKHOURS'',
	(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''BL'' THEN '' - '' ELSE '''' END + ISNULL(PD.STATUS,'''')) AS STATUS,
	((SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),0,CHARINDEX('':'',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''00:00''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED ,
	(CASE PD.SHIFT_ID WHEN ''-1'' THEN ''WEEKLY OFF'' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL
	(
		(
			CASE WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN ''-'' 
				 WHEN PD.SHIFT_ID=-1 THEN ''-''
				 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
		),''00:00''
	) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,
	PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.OFFOT IS NOT NULL	THEN
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 WHEN PD.HOLOT IS NOT NULL	THEN 
			CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
					ELSE CAST(OTMINS AS VARCHAR(50)) 
			END
		 ELSE 0
	END OVERTIME,
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00'' THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''NORMOTMINS'',
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''WEEKOFFOTMINS'',
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN 0 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTmins AS VARCHAR(50)) 
						ELSE CAST(OTMINS AS VARCHAR(50)) 
				END
	END AS ''HOLIDAYOTMINS'',
	CASE WHEN ISNULL(NORMOT,''00:00'')=''00:00'' THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(NORMOT AS VARCHAR(50)) 
				END 
	END AS HRSOT,
	CASE WHEN ISNULL(OFFOT,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(OFFOT AS VARCHAR(50)) 
				END
	END,
	CASE WHEN ISNULL(HOLOT,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' and isnull(ActNormOTmins,0)!=0 then CAST(ActNormOTHrs AS VARCHAR(50)) 
						ELSE CAST(HOLOT AS VARCHAR(50)) 
				END
	END,
	LATEINMIN,
	EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('':'',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
	END AS TOTDEFWORKHRS,
	CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''HOLIDAY'') OR (PD.ANATTENDANCECODE = ''HOLIDAY'')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('':'',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,
	CASE WHEN OVERTIMESTATUS IS NULL THEN ''-'' 
		 ELSE OVERTIMESTATUS 
	END,
	NIGHTORMORN,
	''00:00'',
	''00:00'',
	INNOTATION,
	OUTNOTATION,
	PD.BREAKHOURS,
	LUNCHHOURS,
	BREAKHOURSMINS,
	LUNCHHOURSMINS,
	SHIFT_STARTTIME,
	SHIFT_ENDTIME,
	CATEGORYNAME,
	WEEKDAY_WORKHRS,
	DATEPART(WEEK,DATE),
	FNATTENDANCECODE,
	ANATTENDANCECODE,
	CASE WHEN FNATTENDANCECODE=ANATTENDANCECODE THEN
			CASE	WHEN ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		 ELSE 
			CASE	WHEN FNATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(FNATTENDANCECODE,1,1)
					ELSE FNATTENDANCECODE
			END
			+''/''+
			CASE	WHEN ANATTENDANCECODE in(''Present'',''Absent'',''Weekly Off'',''Holiday'') then substring(ANATTENDANCECODE,1,1)
					ELSE ANATTENDANCECODE
			END
		END,
	CASE WHEN ISNULL(SPEC_NormOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT1 AS VARCHAR(50)) 
				END
		 END,	
	CASE WHEN ISNULL(SPEC_NormOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_NormOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_NormOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_OffOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_OffOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_OffOT2 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT1,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs1 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT1 AS VARCHAR(50)) 
				END
		 END,
	CASE WHEN ISNULL(SPEC_HOLOT2,''00:00'')=''00:00''	THEN ''00:00'' 
		 ELSE	CASE	WHEN OVERTIMESTATUS!=''Approved'' then CAST(Modified_Spec_HolOTHrs2 AS VARCHAR(50))
						ELSE CAST(SPEC_HOLOT2 AS VARCHAR(50)) 
				END
		 END,
	InLocation,
	OutLocation,
	InLatitude ,
	InLongitude ,
	OutLatitude ,
	OutLongitude   
	FROM TA_TBL_EMPLOYEE E  
	INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID 
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID 
	INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID 
	INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID 
	LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID 
	INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID  
	INNER JOIN TA_TBL_CATEGORY CAT ON #EMPCATEGORY.CATEGORYID = CAT.CATEGORYID  
	Left JOIN #EMPPROCESSEDDATA ON #EMPPROCESSEDDATA.PROCESSDATE=PD.DATE AND #EMPPROCESSEDDATA.SWIPECARDNO=PD.EMPLOYEE_CODE_ID
	WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND
	((E.EMPLOYEE_STATUS=1) OR (E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)))
	and (@USERGROUPNAME=''Superadmin'' or TA_TBL_GRADE.GRADE_LEVEL>=@local_GRADELEVEL)
	and (isnull(@local_MINWORKHOURS,'''')='''' or dbo.ConvertHoursToMinites(isnull(HRSWORK,''00:00''))>=@TOTALMIN)
	
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	IF(@EXPORT=0)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'''' as Intime1,
		'''' as OutTime1,		 
		'''' as Intime2,
		'''' as OutTime2,
		'''' as Intime3,
		'''' as OutTime3,
		'''' as Intime4,
		'''' as OutTime4,
		'''' as Intime5,
		'''' as OutTime5,
		'''' as AcutalWorkedHours,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ '' : '' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	else IF(@EXPORT=8)
	BEGIN
		SELECT	
		EMPLOYEE_ID,
		EMPNAME,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
						REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) END AS DATE,
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END SHIFT_SHORTNAME,	
		INTIME,
		OUTTIME,		
		HRSWORK,
		LATEIN,
		EARLYOUT,
		NORMOT,
		SPEC_NormOT1,
		SPEC_NormOT2,		
		OFFOT,
		SPEC_OffOT1,
		SPEC_OffOT2,		
		HOLOT,
		SPEC_HOLOT1,
		SPEC_HOLOT2,
		SUPPOSEDWORKHOURS,		
		FIRSTSESSION,
		SECONDSESSION,		
		CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
		StatusCode,
		EARLYOUT,
		LATEIN,
		OVERTIME,
		NORMOTMIN,
		OFFOTMIN,
		HOLOTMIN,
		NORMOT,
		OFFOT,
		HOLOT,
		LATEINMIN,
		EARLYOUTMIN,
		TOTDEFWORKHRS,
		TOTSUPWORKHRS,
		OVERTIMESTATUS,
		NIGHTORMORN,
		LUNCHINTIME,
		LUNCHOUTTIME
		,INNOTATION,
		OUTNOTATION
		,BREAKHOURS,
		LUNCHHOURS ,
		BREAKHOURSMINS,
		LUNCHHOURSMINS,
		SHIFT_STARTTIME,
		SHIFT_ENDTIME,
		WEEKDAY_WORKHRS,
		WEEKNUMBER ,
		FNATTENDANCECODE,
		ANATTENDANCECODE,
		DESIGNATION,
		BRANCHNAME,
		DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth
		,'''' as Intime1,
		'''' as OutTime1,		 
		'''' as Intime2,
		'''' as OutTime2,
		'''' as Intime3,
		'''' as OutTime3,
		'''' as Intime4,
		'''' as OutTime4,
		'''' as Intime5,
		'''' as OutTime5,
		'''' as AcutalWorkedHours,
		InLocation,
		OutLocation ,
		InLatitude,
		InLongitude,
		OutLatitude ,
		OutLongitude,
		MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ '' : '' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,CONVERT(datetime,date)desc
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END
	ELSE
	BEGIN
		SELECT	DATE processDate,DATEPART(D,DATE) as processDay,left(datename(MONTH,DATE),3) as processMonth,DENSE_RANK()OVER(ORDER BY EMPLOYEE_ID) AS [SL.NO],
				BRANCHNAME AS LEVEL,
				EMPLOYEE_ID AS [EMPLOYEE ID],
				EMPNAME AS [EMPLOYEE NAME],
				DESIGNATION,
				CATEGORYNAME AS [EMPLOYEE CATEGORY],
				GENDER,
				CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
						ELSE CONVERT(VARCHAR, DATE, @DATEFORMAT) 
				END AS DATE,	
				CASE	WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' 
						ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME 
				END [SHIFT SHORTNAME],
				INTIME AS [IN TIME],
				OUTTIME AS [OUT TIME],
				HRSWORK AS [HOURS WORKED],	
				SHIFT_TOTALWORKINGHOURS AS [DEFINED WORK HOURS],
				FIRSTSESSION AS [FIRST SESSION],
				SECONDSESSION AS [SECOND SESSION],
				SPEC_NormOT1,
				SPEC_NormOT2,		
				SPEC_OffOT1,
				SPEC_OffOT2,
				SPEC_HOLOT1,
				SPEC_HOLOT2,
				SUPPOSEDWORKHOURS,
				CONVERT(INT,ISNULL(TOTALMINSWORKED,''0''))TOTALMINSWORKED,
				Case when FNATTENDANCECODE in(''Present'',''Present #'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Present'',''Present #'') then 0.5 else 0.0 end as present,
				Case when FNATTENDANCECODE in(''Absent'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Absent'') then 0.5 else 0.0 end as Absent,
				Case when FNATTENDANCECODE in(''Weekly Off'') then 0.5 else 0.0 end + case when ANATTENDANCECODE IN(''Weekly Off'') then 0.5 else 0.0 end as WeeklyOff,
				Case when FNATTENDANCECODE in(''Holiday'',''RH'') then 0.5 else 0.0 end + case when ANATTENDANCECODE in(''Holiday'',''RH'') then 0.5 else 0.0 end as Holiday,
				Case when FNATTENDANCECODE not in(''Present'',''Present #'',''Absent'',''Weekly Off'',''Holiday'',''RH'') then 0.5 else 0.0 end + case when ANATTENDANCECODE not in(''Present'',''Present #'',''Absent'',''Weekly Off'',''Holiday'',''RH'')then 0.5 else 0.0 end as Leave
				,StatusCode,
				EARLYOUT,
				LATEIN,
				OVERTIME,
				NORMOTMIN,
				OFFOTMIN,
				HOLOTMIN,
				NORMOT,
				OFFOT,
				HOLOT,
				LATEINMIN,
				EARLYOUTMIN,
				TOTDEFWORKHRS,
				TOTSUPWORKHRS,
				OVERTIMESTATUS,
				NIGHTORMORN,
				LUNCHINTIME,
				LUNCHOUTTIME
				,INNOTATION,
				OUTNOTATION
				,BREAKHOURS,
				LUNCHHOURS ,
				BREAKHOURSMINS,
				LUNCHHOURSMINS,
				SHIFT_STARTTIME,
				SHIFT_ENDTIME,
				WEEKDAY_WORKHRS,
				WEEKNUMBER ,
				FNATTENDANCECODE,
				ANATTENDANCECODE,
				DESIGNATION,
				BRANCHNAME,DATE processDate
				,'''' as Intime1,
				'''' as OutTime1,		 
				'''' as Intime2,
				'''' as OutTime2,
				'''' as Intime3,
				'''' as OutTime3,
				'''' as Intime4,
				'''' as OutTime4,
				'''' as Intime5,
				'''' as OutTime5,
				'''' as AcutalWorkedHours,
				MonthNo=CONVERT(varchar(20),datepart(MONTH,DATE))+ '' : '' +left(datename(MONTH,DATE),15)
		FROM #TEMPMONTHLYATTENDANCE ORDER BY EMPLOYEE_ID,MonthNo,WEEKNUMBER
		--processDate added in order clause by mahendren.S
		--Reason: reports showing incorrectly in cross month taking
	END	
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE	 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthClosure]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name : Proc_TA_RptMonthClosure  '''',''1'',''1'',''787,788'',0,0,''SuperAdmin'',''0'','''',1,0,''Both'',1
Tables  : TA_Tbl_Employee,TA_Tbl_MonthClosure,TA_Tbl_PayrollProcessDetails,  
TA_Tbl_PayrollProcessLeaveDetails,Ta_Tbl_LeaveType, TA_Tbl_Title,TA_Tbl_LevelDetails  
Created By : Prabakaran    
Created on : 15-Oct-07    
Modified by : sashma
Modified on : 12-May-2011 
Modified By		:	Gopinath.K
Modified Date	:	18-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
Descriptions	:	SQL Query OPtimazation. 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthClosure]    
(  
 @EmployeeName varchar(max),    
 @LevelID varchar(8000),
 @MonthClosureId varchar(500),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoID int	
)
AS    
BEGIN 
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId] ,[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @toDate datetime
	set @toDate=GETDATE()
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @toDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @toDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @toDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @toDate,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)    
	set @sqlQuery=''''
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as EmployeeName,
	Convert(varchar,MonthClosure_StartDate,106) + '''' - '''' + Convert(varchar,MonthClosure_EndDate,106) as Duration,
	ppd.HrsWork,ppd.HrsOT,ppd.NormOT,ppd.OFFOT,ppd.HolOT,ppd.EarlyOut,ppd.LateIn,ppd.WorkHrs as TotWorkHrs,
	ppd.HrsLess,ppd.HrsExtra,isnull(ppd.LeaveDays,0) as LeaveDays,isnull(ppd.PresentDays,0) as PresentDays,
	isnull(ppd.AbsentDays,0) as AbsentDays,isnull(ppd.Holidays,0) as Holidays,isnull(ppd.LOPDays,0) as LOPDays,
	replace(T.TitleName,''''&amp;'''',''''&'''') as TitleName,e.Gender,ppd.TotalPermissionHours,
	SPEC_NormOT1=isnull(ppd.SPEC_NormOT1,''''00:00''''),
	SPEC_NormOT2=isnull(ppd.SPEC_NormOT2,''''00:00''''),
	SPEC_OffOT1=isnull(ppd.SPEC_OffOT1,''''00:00''''),
	SPEC_OffOT2=isnull(ppd.SPEC_OffOT2,''''00:00''''),
	SPEC_HOLOT1=isnull(ppd.SPEC_HOLOT1,''''00:00''''),
	SPEC_HOLOT2=isnull(ppd.SPEC_HOLOT2,''''00:00'''')
	from TA_Tbl_MonthClosure mc inner join TA_Tbl_PayrollProcessDetails 
	ppd on ppd.MonthClosure_Id=mc.MonthClosure_Id''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_Employee e on e.SwipeCardNo=ppd.Employee_Id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel Lev on Lev.employeeid = e.Employee_Id ''
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_LevelDetails L ON  Lev.LevelID = L.Id ''	
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''
	Set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON  T.TitleId = EDesig.DesignationId ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = Lev.levelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id ''
		End
				If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and mc.IsDeleted=0''    
	if not(@MonthClosureId='''' or @MonthClosureId=''0'')    
		begin    
			set @sqlQuery = @sqlQuery + '' And (mc.MonthClosure_Id In ('' + @MonthClosureId + ''))''    
		End 
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName''
	exec(@sqlQuery) 
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptManualTimeEntry]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptManualTimeEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Proc_TA_RptManualTimeEntry '''','''',''2020/06/01'',''2020/07/27'',''0'',0,0,''SuperAdmin'',''0'',''all'','''',0,0,''Male'',0
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptManualTimeEntry] 
(
	-- Add the parameters for the stored procedure here
	@employeeName nvarchar(500),
	@employeeId nvarchar(50),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint
)
AS 
BEGIN
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(max)  
	set @sqlQuery = '''' 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Temporary table''s creation
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	--Employee Level insert in Temporary table
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDate,@EmployeeId	
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	Declare @sqlTempProcessedData varchar(max) 
	set @sqlTempProcessedData=
	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''
	Execute(@sqlTempProcessedData)
	
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	SET @TimeFormat=(Select TimeFormat from Func_TA_GetDateTimeFormat())
	
	SELECT distinct  dbo.TA_Tbl_Employee.Employee_Code_Id as ManualTimeEntry_Employee_Id, 
									ISNULL(TA_Tbl_Employee.Employee_FirstName, '' '') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, '' '') AS Employee_Name,TA_Tbl_Employee.Gender,replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name, case when E.Employee_Id=1 then (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) else (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,''''))+''-''+E.Employee_code_id end as ''Created_By'' , 
	case when @dateFormat=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.TimeStamp,101),'' '',''-'') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.TimeStamp, 101) end 
	+ 
	case	when @TimeFormat=''hh:mm'' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,TA_Tbl_ManualTimeEntry.TimeStamp,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),13,2),'' '',''''))=1 then '' 0''+ replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),12,6),'' '','''')
					else substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),12,6) end
			+'' '' + substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.TimeStamp),18,2)
	end 
	as ''Created_DateTime'',
	case	when IsDiscrepancyEntry=1 then ''D'' 
			when TA_Tbl_ManualTimeEntry.IsImported=0 then ''M'' 
			when TA_Tbl_ManualTimeEntry.IsImported=1 then ''I'' 
			when TA_Tbl_ManualTimeEntry.IsImported=2 then ''Mo'' end as IsDiscrepancyEntry,
	case	when @dateFormat=106 then 
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_InDate,101),'' '',''-'') 
	else  CONVERT(VARCHAR, ManualTimeEntry_InDate, 101) 
		end 
	AS ManualTimeEntry_InDate, 
	case	when @TimeFormat=''hh:mm'' then 
	 			substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,ManualTimeEntry_InTime,0)), 114),0,6)	 			
			else	substring(ManualTimeEntry_InTime,0,6)+'' '' + substring(ManualTimeEntry_InTime,10,2) 					
	end ManualTimeEntry_InTime,
	
	case when Latitude_value is not null and Longitude_value is not null then ''M - '' + ManualTimeEntry_InPunchType
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_InPunchType end ManualTimeEntry_InPunchType,
	
	case	when @dateFormat=106 then 
				REPLACE(CONVERT(VARCHAR, ManualTimeEntry_OutDate,101),'' '',''-'') 
	else  CONVERT(VARCHAR, ManualTimeEntry_OutDate, 101) 
		end AS ManualTimeEntry_OutDate,
	case	when @TimeFormat=''hh:mm'' then 
	 			substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,ManualTimeEntry_OutTime,0)), 114),0,6)
			else	substring(ManualTimeEntry_OutTime,0,6)+'' '' + substring(ManualTimeEntry_OutTime,10,2) 					
	end ManualTimeEntry_OutTime,
	case when Latitude_value is not null and Longitude_value is not null then ''M - '' + ManualTimeEntry_OutPunchType
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutPunchType end ManualTimeEntry_OutPunchType,
	TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status,
	
	case when Latitude_value is not null and Longitude_value is not null then Clock_Address else 
	replace(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Reason,''&amp;'',''&'') end as ManualTimeEntry_Reason,  TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id,
	Convert(varchar, TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date, 
	TA_Tbl_Title.TitleName,
	
	
	case when E.Employee_Id=1 then
	(E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''')) else (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,''''))+''-''+E.Employee_code_id end as ''Modified_By'' 
	,
	case when cast(101 as varchar(100))=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.modify_date,101),'' '',''-'') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.modify_date, 101) end 
	+ 
	case	when @TimeFormat=''hh:mm'' then 
	 			space(1)+substring(CONVERT(varchar(20),DATEADD(minute,0,convert(datetime,TA_Tbl_ManualTimeEntry.modify_date,0)), 114),0,6)
			else	case when len(replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),13,2),'' '',''''))=1 then '' 0''+ replace(substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),12,6),'' '','''')
					else substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),12,6) end
			+'' '' + substring(CONVERT(varchar(20),TA_Tbl_ManualTimeEntry.modify_date),18,2)
	end 
	Modified_DateTime,
	[Process Status]=case when Clk_Process=''N'' then ''Not Processed'' else ''Processed'' end  
	FROM TA_Tbl_Employee INNER JOIN TA_Tbl_ManualTimeEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id 
	Left outer join Ta_tbl_Employee E On E.Employee_id=TA_Tbl_ManualTimeEntry.Emp_Id  
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id  
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId  
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_Employee.SwipeCardNo 
	WHERE ((TA_Tbl_Employee.Employee_Status = 1) 
	or(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)
	>= 
	convert(varchar(11),TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,102))) 
	AND (TA_Tbl_Employee.Isdeleted = 0) AND 
	(TA_Tbl_Employee.report_exclude = 0) AND 
	(TA_Tbl_ManualTimeEntry.IsOnDuty=0) AND 
	((TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate >= CONVERT(DATETIME, @fromdate, 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate <= CONVERT(DATETIME, @toDate, 102) ) or (TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate >= CONVERT(DATETIME, @fromdate, 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate <= CONVERT(DATETIME, @toDate, 102) ))
	And(@Gender=''Both'' or TA_Tbl_Employee.Gender=@Gender)
	And(@UserGroupName=''Superadmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	And((ISNULL(@Status,''All'')=''All'' or @Status='''') or TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status=@Status)
	and(@isReportingto=0 or (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)))
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLessHoursWorked]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLessHoursWorked]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*     
Procedure Name : Proc_TA_RptMonthlyAttendance     
Tables  : TA_Tbl_Employee and TA_Tbl_ProcessedData     
Created By : Manikandan.R     
Created on : 30-Sep-2011
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description : Absentess reports (SQL Query Optimization is done here)
Proc_TA_RptLessHoursWorked ''2019/01/01'',''2019/12/17'','''','''',0,0,''SuperAdmin'','''','''',0,0,''Both'',0,''d'',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptLessHoursWorked]    
(
 @fromDat datetime,
 @ToDat datetime,
 @EmployeeName varchar(max),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @Shift int,
 @TypeOfReport varchar(20),
 @EmpAutoId bigint
)    
AS     
BEGIN
	SET NOCOUNT ON;   	
	
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_EmployeeName varchar(max)
	Declare @local_EmployeeId varchar(max)
	Declare @local_employeeCategory int
	Declare @local_employeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_Shift int
	Declare @local_TypeOfReport varchar(20)
	Declare @local_EmpAutoId bigint
	
	set @local_fromDat=@fromDat
	set @local_ToDat=@ToDat
	set @local_EmployeeName=@EmployeeName
	set @local_EmployeeId=@EmployeeId
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_Shift=@Shift
	set @local_TypeOfReport=@TypeOfReport
	set @local_EmpAutoId=@EmpAutoId	
	
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	--Temporary table''s creation   
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)   
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #LevelRights(LevelId int)   
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId   
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(50),InTime nvarchar(25),OutTime nvarchar(25),
	Shift_Id int,HrsWork nvarchar(10),anAttendanceCode nvarchar(15), 
	fnAttendanceCode nvarchar(15),wrkhrs nvarchar(10),LessFlag bit default(0),TotalLessHrs varchar(20))
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]    
	(   
		[Employee_Code_Id] ASC
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]    
	(   
		[EffectiveDate],[LevelId],[EmployeeId] ASC   
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]    
	(   
		[EffectiveDate],[DesignationId],[EmployeeId] ASC   
	)ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]    
	(   
		[EffectiveDate],[TypeId],[EmployeeId] ASC   
	) ON [PRIMARY]   
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]    
	(   
		[EffectiveDate],[CategoryId],[EmployeeId] ASC   
	)ON [PRIMARY]   
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_EmployeeId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_EmployeeId,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_EmployeeId,@local_employeeCategory	
	create table #EmployeeID(EmployeeID varchar(25))
	--To split up the comma separated values
	if(@local_EmployeeId is not null and @local_EmployeeId <> '''')
		begin
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeId)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@local_EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))   
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData=''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee   
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	If Not (@local_EmployeeId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0 and TA_Tbl_Employee.report_exclude=0 ''
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@local_Gender<>''Both'') 
		begin 
			set @sqlTempProcessedData = @sqlTempProcessedData + '' and TA_Tbl_Employee.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' '' 
		end 
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=''
	insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,
	TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.HrsWork, 
	TA_Tbl_ProcessedData.anAttendanceCode,
	TA_Tbl_ProcessedData.fnAttendanceCode,WorkHrs,''''''''
	,HrsLess
	as TotalLessHrs       
	from TA_Tbl_ProcessedData    
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id   
	where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,''''''+cast( @local_fromDat as nvarchar(50))+'''''', 102))     
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''''''+cast(@local_ToDat as nvarchar(50))+'''''', 102))
	and anAttendanceCode not in(''''Weekly Off'''',''''Holiday'''')and fnAttendanceCode not in(''''Weekly Off'''',''''Holiday'''')''
	if(@local_Shift<>0) 
		begin 
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND TA_Tbl_ProcessedData.shift_id= ''+  cast (@local_Shift as nvarchar(50))
		end 
	Execute(@sqlTempProcessedData1)
	update #TempProcessedData set LessFlag=1  where TotalLessHrs is not null and TotalLessHrs<>''00:00'' and TotalLessHrs<>''''
	declare @sqlQuery as varchar(max)   
	set @sqlQuery=''''           
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,
							isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,
							replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,
							replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,
							CASE	WHEN ''+ CONVERT(varchar,@dateFormat) +''=106 THEN REPLACE(CONVERT(VARCHAR, DATE,''+ CONVERT(varchar,@dateFormat) +''),'''' '''',''''-'''') 
									ELSE CONVERT(VARCHAR, DATE, ''+ CONVERT(varchar,@dateFormat) +'') END AS DATE,
							pd.InTime,
							pd.OutTime,
							isnull(pd.wrkhrs,''''00:00'''') as shift_TotalWorkingHours,
							pd.HrsWork, 
							pd.TotalLessHrs,
							((substring(isnull(pd.HrsWork,''''00:00''''),0,charindex('''':'''',pd.HrsWork))*60) + (substring(isnull(pd.HrsWork,''''00:00''''),(len(pd.HrsWork)-1),2))) as TotalMinsWorked,
							((substring(isnull(pd.wrkhrs,''''00:00''''),0,charindex('''':'''',pd.wrkhrs))*60) + (substring(isnull(pd.wrkhrs,''''00:00''''),(len(pd.wrkhrs)-1),2))) as TotalMinsAllocated,
							((substring(isnull(pd.TotalLessHrs,''''00:00''''),0,charindex('''':'''',pd.TotalLessHrs))*60) + (substring(isnull(pd.TotalLessHrs,''''00:00''''),(len(pd.TotalLessHrs)-1),2))) as TotalLessMins '' 
	set @sqlQuery = @sqlQuery + '' ,(CASE pd.Shift_Id WHEN ''''-1'''' THEN ''''Weekly Off'''' ELSE shf.Shift_ShortName END) as Shift_ShortName ,
							e.Gender''
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e '' 
	set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id '' 
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id'' 
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id '' 
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId'' 
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''    
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id'' 
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id '' 
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id '' 
	set @sqlQuery = @sqlQuery + '' where pd.LessFlag=1 
	and ((e.employee_Status=1)
	or
	(e.employee_Status=0 and convert(nvarchar(11),e.InActiveDate,102)>=convert(nvarchar(11),pd.date,102))
	) ''   
	if(@local_UserGroupName<>''SuperAdmin'') 
		begin 
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel + '''' 
		end
	DECLARE @sqlquery1 varchar(max)
	set @sqlquery1=@sqlQuery
	set @sqlQuery = @sqlQuery + '' order by e.Employee_Code_Id,e.Employee_FirstName,cast(pd.date as datetime)''
	---For Detailed LessHours Report
	if(@local_TypeOfReport=''D'')
		begin
			exec(@sqlQuery)  
		end
	---For Summary LessHours Report
	else if @local_TypeOfReport=''s''
		begin
			Create table #LessHrsWorkingDaysCount(Employee_id varchar(20),empName varchar(200),BranchName varchar(50),Designation varchar(50),Gender varchar(10),
			TotalLessHrsCountDays varchar(20),TotalMinsAllocated varchar(20),TotalLessHrs varchar(20),WorkingDays varchar(10) default 0)
			set @sqlquery1=''select p.Employee_Id,p.empName,p.BranchName,p.Designation,p.Gender,count(Employee_id) as TotalLessHrsCountDays,
			case when len(sum(p.TotalMinsAllocated)/60)=1 then ''''0''''+ convert(varchar(20),sum(p.TotalMinsAllocated)/60) 
				 else convert(varchar(20),sum(p.TotalMinsAllocated)/60)
			end
			+'''':''''+ 
			case when len(sum(p.TotalMinsAllocated)%60)=1 then ''''0''''+ convert(varchar(20),sum(p.TotalMinsAllocated)%60)  
				 else convert(varchar(20),sum(p.TotalMinsAllocated)%60)
			end
			as TotalMinsAllocated
			,
			case when len(convert(varchar(20),sum(p.TotalLessMins)/60))=1 then ''''0''''+convert(varchar(20),sum(p.TotalLessMins)/60)
			else
			convert(varchar(20),sum(p.TotalLessMins)/60) end +'''':''''+ 
			case when len(convert(varchar(20),sum(p.TotalLessMins)%60))=1 then ''''0''''+ convert(varchar(20),sum(p.TotalLessMins)%60)
			else convert(varchar(20),sum(p.TotalLessMins)%60) end
			as TotalLessHrs,''''0'''' as workingdays from('' + @sqlquery1 +'')as p
			Group by Employee_Id,empName,
			p.BranchName,p.Designation,p.Gender order by Employee_Id''
			insert into #LessHrsWorkingDaysCount exec(@sqlQuery1)
			--For Counting Working Days from selected durations
			create table #LessHrsUpdateWorkingDays(WorkingDays varchar(10),Employee_id varchar(20))
			set @sqlQuery =''select * from(select Count(convert(int,datepart(D,[Date])))as Workingday,e.Employee_Code_Id 
			from TA_Tbl_Employee  e inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId  group by e.Employee_Code_Id)as a''
			insert into #LessHrsUpdateWorkingDays exec(@sqlQuery)
			Update #LessHrsWorkingDaysCount set WorkingDays=LHU.WorkingDays from #LessHrsWorkingDaysCount inner join
			#LessHrsUpdateWorkingDays LHU on #LessHrsWorkingDaysCount.Employee_id=LHU.Employee_id
			
			select	Employee_id,
					empName,
					Designation,					
					TotalMinsAllocated,					
					TotalLessHrs,
					WorkingDays,
					TotalLessHrsCountDays,					
					Gender,
					BranchName
			from #LessHrsWorkingDaysCount                        
		end
	--Remove the temporary tables here      
	drop table #EmpLevel   
	drop table #EmpDesignation   
	drop table #EmpType   
	drop table #EmpCategory                
	drop table #EmpProcessedData   
	drop table #LevelRights   
	drop table #TempProcessedData   
	drop table #TempEmployee  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptLeavePolicyNotAllocated]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptLeavePolicyNotAllocated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptLeavePolicyNotAllocated ''01/Jan/2016'',''31/Aug/2016'','''',''0,1'','''',0,0,''SuperAdmin'',''0'','''',0,0,''Both'',0
Created By : Sashma  
Created on : 10-May-2011  
Modified By		:	Gopinath.K
Modified Date	:	21-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
Descriptions	:	SQL Query OPtimazation.
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptLeavePolicyNotAllocated] 
(
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000), 
	 @EmployeeId varchar(max),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(20),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @EmpAutoId bigint
)			
AS  
BEGIN
	SET NOCOUNT ON;
	--Temporary table''s creation
	--Get the Current date time format
	DECLARE @dateFormat as int
	set @dateFormat =(Select DateFormat from Func_TA_GetDateTimeFormat())
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select e.Employee_Code_Id,e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') as EmpName,T.TitleName,Cat.CategoryName,e.Gender,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as LevelName, case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, e.DateOfJoining,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, e.DateOfJoining, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''DateOfJoining'''' from TA_Tbl_Employee e ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join TA_Tbl_Category Cat on #EmpCategory.CategoryId = Cat.CategoryId ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where e.Employee_Id not in (select EmployeeID from TA_Tbl_Emp_LeavePolicy ''
	set @sqlQuery = @sqlQuery + '' where (FromDate<= case when (CONVERT(DATETIME, ''''''+cast(@fromDat as nvarchar(20))+'''''', 102) <= e.DateOfJoining) then e.DateOfJoining else CONVERT(DATETIME, ''''''+cast(@fromDat as nvarchar(20))+'''''', 102) end  and ToDate>=CONVERT(DATETIME, ''''''+cast(@ToDat as nvarchar(20))+'''''', 102)))  ''
	set @sqlQuery = @sqlQuery + '' and e.DateOfJoining<=CONVERT(DATETIME, ''''''+cast(@ToDat as nvarchar(20))+'''''', 102) and e.Isdeleted=0  and e.Report_exclude=0 ''
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>='' + @GradeLevel  
		end
		if(@isReportingto > 0)
			BEGIN
			   set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
	exec(@sqlQuery)  
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_RptMovementsEntryWithMatchedPunches ''787'',''0,1'',''2014/09/01'',''2014/10/01'','''',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''07:01 Am'',''11:59 PM'',2,1,1
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntryWithMatchedPunches]
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@Type int,
	@EmpAutoId bigint,
	@ExportType int
)	
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_Type int
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_Type=@Type
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel = @sqlEmpLevel +'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int,lateInMins int,EarlyExitMin int)
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	)ON [PRIMARY]
	Create table #TempOutPunches
	(
		[tempId] int identity(1,1),
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_OutPunchType] [nvarchar](25) NULL,
		[Clk_Date] [datetime] NULL,
		[Clk_OutDate] [datetime] NULL,
		[Clk_OutDeviceId] [nvarchar](20) NULL
	)
	Create table #TempMatchedPunches
	(		
		[Clk_EmpId] [nvarchar](20) NULL,
		[Clk_InDeviceId] [nvarchar](20) NULL,
		[Clk_InDate] [datetime] NULL,
		[Clk_InTime] [datetime] NULL,
		[Clk_InPunchType] [nvarchar](25) NULL,		
		[Clk_OutDeviceId] [nvarchar](20) NULL,
		[Clk_OutDate] [datetime] NULL,
		[Clk_OutTime] [datetime] NULL,
		[Clk_OutPunchType] [nvarchar](25) NULL,
		[Clk_Date] [datetime] NULL,
		[TempIdFromOutPunches] int default 0,
		OrderBy int
	)
	if(@Type!=4)
		begin
			insert into #TempMatchedPunches(Clk_EmpId,Clk_InTime,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,OrderBy)
			select Clk_EmpId,min(Clk_InDate+'' ''+ Clk_InTime),Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,
			case when Clk_InPunchType=''In'' then 1 else 2 end from TA_Tbl_ClockDetails 
			inner join #EmpLevel on Clk_EmpId=SwipeCard
			where ta_tbl_clockdetails.IsVoid=0
			and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
			and Clk_InPunchType in(''In'',''Shift In'')
			--and Clk_EmpId=''787''
			group by Clk_EmpId,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId
		end
	insert into #TempMatchedPunches(Clk_EmpId,Clk_InTime,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId,OrderBy)
	select Clk_EmpId,min(Clk_OutDate+'' ''+Clk_OutTime),Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId,3 from TA_Tbl_ClockDetails 
	inner join #EmpLevel on Clk_EmpId=SwipeCard
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	and Clk_OutPunchType in(''Lunch Out'')
	--and Clk_EmpId=''787''
	group by Clk_EmpId,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId
	if(@Type!=4)
		begin
			insert into #TempOutPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId)
			select Clk_EmpId,max(Clk_OutDate+'' ''+Clk_OutTime),Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId from TA_Tbl_ClockDetails 
			inner join #EmpLevel on Clk_EmpId=SwipeCard
			where ta_tbl_clockdetails.IsVoid=0
			and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
			and Clk_OutPunchType in(''Out'',''Shift Out'')
			--and Clk_EmpId=''787''
			group by Clk_EmpId,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId
		end
	insert into #TempOutPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,Clk_OutDate,Clk_OutDeviceId)
	select Clk_EmpId,max(Clk_InDate+'' ''+Clk_InTime),Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId from TA_Tbl_ClockDetails 
	inner join #EmpLevel on Clk_EmpId=SwipeCard
	where ta_tbl_clockdetails.IsVoid=0
	and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	and Clk_InPunchType in(''Lunch In'')
	--and Clk_EmpId=''787''
	group by Clk_EmpId,Clk_Date,Clk_InPunchType,Clk_InDate,Clk_InDeviceId 
	if(@Type!=4)
		begin
			update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType=''In'' then OP.Clk_OutTime end,
			Clk_OutPunchType=case when MP.Clk_InPunchType=''In'' then OP.Clk_OutPunchType end, 
			TempIdFromOutPunches=case when MP.Clk_InPunchType=''In'' then tempId else TempIdFromOutPunches end,
			[Clk_OutDeviceId]=case when MP.Clk_InPunchType=''In'' then OP.Clk_OutDeviceId end,
			Clk_OutDate=case when MP.Clk_InPunchType=''In'' then OP.Clk_OutDate end
			from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
			where OP.Clk_OutPunchType=''Out''
			update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType=''Shift In'' then OP.Clk_OutTime end, 
			Clk_OutPunchType=case when MP.Clk_InPunchType=''Shift In'' then OP.Clk_OutPunchType end,
			TempIdFromOutPunches=case when MP.Clk_InPunchType=''Shift In'' then tempId else TempIdFromOutPunches end,
			[Clk_OutDeviceId]=case when MP.Clk_InPunchType=''Shift In'' then OP.Clk_OutDeviceId end,
			Clk_OutDate=case when MP.Clk_InPunchType=''Shift In'' then OP.Clk_OutDate end
			from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
			where OP.Clk_OutPunchType=''Shift Out''
		end
	update #TempMatchedPunches set Clk_OutTime=case when MP.Clk_InPunchType=''Lunch Out'' then OP.Clk_OutTime else MP.Clk_OutTime end,
	Clk_OutPunchType=case when MP.Clk_InPunchType=''Lunch Out'' then OP.Clk_OutPunchType else MP.Clk_OutPunchType end ,
	TempIdFromOutPunches=case when MP.Clk_InPunchType=''Lunch Out'' then tempId else TempIdFromOutPunches end,
	[Clk_OutDeviceId]=case when MP.Clk_InPunchType=''Lunch Out'' then OP.Clk_OutDeviceId else MP.Clk_OutDeviceId end,
	Clk_OutDate=case when MP.Clk_InPunchType=''Lunch Out'' then OP.Clk_OutDate else MP.Clk_OutDate end
	from #TempMatchedPunches MP inner join #TempOutPunches OP on MP.Clk_Date=OP.Clk_Date and MP.Clk_EmpId=OP.Clk_EmpId
	where OP.Clk_OutPunchType=''Lunch In'' and OP.Clk_OutPunchType is not null
	insert into #TempMatchedPunches(Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,TempIdFromOutPunches)
	select Clk_EmpId,Clk_OutTime,Clk_Date,Clk_OutPunchType,0
	from #TempOutPunches OP where tempId not in(
	select isnull(TempIdFromOutPunches,0) from #TempOutPunches OP inner join #TempMatchedPunches MP on MP.Clk_EmpId=OP.Clk_EmpId
	and MP.Clk_Date=OP.Clk_Date
	)
	insert into #TempMatchedPunches
	select Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Date,0,4
	from ta_tbl_MatchedPunches
	where clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102)
	--and Clk_EmpId=''787''
	DECLARE @dateFormat as int
	SELECT @dateFormat = DateFormat FROM dbo.Func_TA_GetDateTimeFormat()
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,'''',LateInMins,EarlyOutMins
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	Declare @SelectSQL As Varchar(8000)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = '' ''        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + ''SELECT ED.Employee_code_id as ''''Employee ID'''', ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',ED.Gender,''      
		Set @SelectSQL = @SelectSQL + ''				
		case when	''+cast(@dateFormat as varchar(100))+''=106 then
						REPLACE(CONVERT(VARCHAR, Clk_Date,106),'''' '''',''''-'''')
				else	convert(varchar(20),Clk_Date,''+convert(varchar(5),@dateFormat)+'') 
			end as ''''Date'''',ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,		
		case	when (((PD.Clk_InPunchType = ''''I'''') OR (TPD.PrevShiftType = 1)) and (PD.Clk_InTime IS NOT NULL)) then ''''F_In'''' 			
				else PD.Clk_InPunchType end as ''''In Punch Type'''',
		case when [Clk_InDate] IS null then '''''''' else 	
			case when	''+cast(@dateFormat as varchar(100))+''=106 then
						REPLACE(CONVERT(VARCHAR, Clk_InDate,106),'''' '''',''''-'''')
				else	convert(varchar(20),Clk_InDate,''+convert(varchar(5),@dateFormat)+'') 
			end			
		end as ''''In Date'''',
		convert(varchar(20),[Clk_InTime],108) ''''In Time'''' , 
		case	when (((PD.Clk_OutPunchType = ''''O'''') OR (TPD.PrevShiftType = 1)) and (PD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' 			
				else pD.Clk_OutPunchType end as ''''Out Punch Type'''',''	
		Set @SelectSQL = @SelectSQL + ''	
		case when [Clk_OutDate]  IS null then '''''''' else 
					case	when	''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Clk_OutDate,106),'''' '''',''''-'''')
							else	convert(varchar(20),[Clk_OutDate],''+convert(varchar(5),@dateFormat)+'')
					end
		end ''''Out Date'''',	
		convert(varchar(20),[Clk_OutTime],108) ''''Out Time''''
		FROM TA_Tbl_Employee ED ''      
		set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''	
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempMatchedPunches PD ON PD.[Clk_EmpId] = ED.SwipeCardNo''   
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData TPD ON TPD.Employee_Code_Id = PD.Clk_EmpId and TPD.Date=PD.Clk_Date''   
		Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = TPD.Shift_ID ''  
		Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and 
		((ED.employee_status=1)
		or
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),PD.Clk_Date,102))
		 ) and Clk_InPunchType is not null and Clk_OutPunchType is not null ''
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + ''SELECT ED.Employee_code_id as CardNo, ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',''      
		Set @SelectSQL = @SelectSQL + ''
		case when [Clk_InDate] IS null then '''''''' else 	
			case when	''+cast(@dateFormat as varchar(100))+''=106 then
						REPLACE(CONVERT(VARCHAR, Clk_InDate,106),'''' '''',''''-'''')
				else	convert(varchar(20),Clk_InDate,''+convert(varchar(5),@dateFormat)+'') 
			end			
		end as InDate,	
		convert(varchar(20),[Clk_InTime],108)InTime ,	
		case	when (((PD.Clk_InPunchType = ''''I'''') OR (TPD.PrevShiftType = 1)) and (PD.Clk_InTime IS NOT NULL)) then ''''F_In'''' 			
				else PD.Clk_InPunchType end as Clk_InPunchType,''	
		Set @SelectSQL = @SelectSQL + ''	
		case when [Clk_OutDate]  IS null then '''''''' else 
					case	when	''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Clk_OutDate,106),'''' '''',''''-'''')
							else	convert(varchar(20),[Clk_OutDate],''+convert(varchar(5),@dateFormat)+'')
					end
		end OutDate,	
		convert(varchar(20),[Clk_OutTime],108) OutTime,	
		case	when (((PD.Clk_OutPunchType = ''''O'''') OR (TPD.PrevShiftType = 1)) and (PD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' 			
				else pD.Clk_OutPunchType end as Clk_OutPunchType,			
		case when	''+cast(@dateFormat as varchar(100))+''=106 then
						REPLACE(CONVERT(VARCHAR, Clk_Date,106),'''' '''',''''-'''')
				else	convert(varchar(20),Clk_Date,''+convert(varchar(5),@dateFormat)+'') 
			end as ClockDate,ED.Gender, 		 
		TPD.lateInMins as InReaderID,'''''''' as InTerminalName,EarlyExitMin as OutReaderID,'''''''' as OutTerminalName,
		ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName
		FROM TA_Tbl_Employee ED ''      
		set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
		set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''	
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempMatchedPunches PD ON PD.[Clk_EmpId] = ED.SwipeCardNo''   
		Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData TPD ON TPD.Employee_Code_Id = PD.Clk_EmpId and TPD.Date=PD.Clk_Date''   
		Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = TPD.Shift_ID ''  
		Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and 
		((ED.employee_status=1)
		or
		(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),PD.Clk_Date,102))
		 ) and Clk_InPunchType is not null and Clk_OutPunchType is not null ''
	end
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)=''PM'' and substring(@local_OutTime,7,8)=''AM'')
		begin
			Set @SelectSQL = @SelectSQL + ''And Clk_Date>=''''''+@local_FromDate+'''''' and Clk_Date<=dateadd(d,1,''''''+@local_ToDate+'''''')
							and clk_intime>=''''''+@local_InTime+'''''' or clk_outtime<=''''''+@local_OutTime+''''''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + ''And (PD.Clk_Date between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_intime between ''''''+@local_FromDate+space(1)+ @local_InTime+'''''' and ''''''+@local_ToDate+space(1)+@local_OutTime+''''''''
			Set @SelectSQL = @SelectSQL + ''or PD.Clk_Date between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_Outtime between ''''''+@local_FromDate+space(1)+@local_InTime+'''''' and ''''''+@local_ToDate+space(1)+@local_OutTime+'''''')''
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  TPD.Shift_Id = '' +  cast(@local_shift  as nvarchar(20))   
		end       
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Set @SelectSQL = @SelectSQL + '' order by Clk_EmpId,clk_date,OrderBy''
	Exec (@SelectSQL)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	 
	drop table #TempProcessedData   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_NotMatched]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry_NotMatched]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
	Modified By		:	A.K.T.MOORTHI
	Modified Date	:	09-Oct-2013
	Description		:	Dispaly In/Out Punch Type For ''F_In'' And ''F_Out'' When Emplopyee Shift IS Free Scan Shift Type.(Reg Bug No : 0019304)
	Modified By		:	K.Gopinath
	Modified Date	:	18-Dec-2013 & 11-Jan-2014
	Description		:	SQL Query Optimazation & Emp name filtering
*/
-- Proc_TA_RptMovementsEntry ''emp1'',''1'',''01/01/2013'',''07/22/2013'','''',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''00:01 Am'',''12:59 PM''
-- [Proc_TA_RptMovementsEntry_NotMatched] '''',''1'',''11/01/2016'',''11/24/2016'','''',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''07:01 Am'',''11:59 PM'',0,1
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_NotMatched]      
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@EmpAutoId bigint,
	@ExportType int
)      
AS      
BEGIN
	SET NOCOUNT ON;
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	--Get current date time format.
	DECLARE @dateFormat as int
	select @dateFormat = DateFormat from dbo.Func_TA_GetDateTimeFormat()
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,[Clk_CompId] varchar(10) ,[Clk_EmpId] nvarchar(20) ,
		[Clk_InDeviceId] nvarchar(20) ,[Clk_InDate] datetime,
		[Clk_InTime] datetime,[Clk_InPunchType] nvarchar(25) ,[Clk_OutDeviceId] nvarchar(20) ,
		[Clk_OutDate] datetime,[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,[Clk_Process] nvarchar(1) ,
		[Clk_Remarks] nvarchar(255) ,[Clk_User] nvarchar(20) ,
		[Clk_Date] datetime,[Clk_Status] char(1) ,[IsVoid] bit
	)
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].#TempClockDetails 
	(
		[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],	[Clk_InTime] ,	[Clk_InPunchType],
		[Clk_OutDeviceId],	[Clk_OutDate],	[Clk_OutTime],	[Clk_OutPunchType],[Clk_Date] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_levelid ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_swipecard ON [dbo].[#EmpLevel] 
	(
		swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_DesignationId ON [dbo].[#EmpDesignation] 
	(
		EmployeeId,DesignationId ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end	
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end	
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)	
	set @sqlTempProcessedData1=
	''insert into #TempClockDetails
	select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
	[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid]
	from TA_Tbl_ClockDetails
	where ta_tbl_clockdetails.IsVoid=0
	and (ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,''''''+cast(@local_FromDate as nvarchar(20))+'''''', 102) 
	and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(20))+'''''', 102))and (clk_Indate is null or  clk_outdate is null)''
	Execute(@sqlTempProcessedData1)	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime)
	CREATE NONCLUSTERED INDEX IDX_Employee_Code_Id
	ON [dbo].[#TempProcessedData] ([Employee_Code_Id])
	INCLUDE ([Shift_ID],[Date])
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date 
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	Declare @SelectSQL As Varchar(8000)      	
	Set @SelectSQL = '' ''        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id AS ''''Employee ID'''', ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',ED.Gender,case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_Date, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''Date'''',ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,''      
		Set @SelectSQL = @SelectSQL + ''case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else ITer.Terminal_Name end as ''''In Reader ID'''',case when (((CD.Clk_InPunchType = ''''I'''') OR (SH.ShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''''F_In'''' else CD.Clk_InPunchType end as ''''In Punch Type'''',case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_InDate, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''In Date'''',Convert(varchar(10),CD.Clk_InTime,108) as InTime ,''      
		Set @SelectSQL = @SelectSQL + '' case when CD.Clk_OutDeviceId=''''788'''' then ''''-'''' else 
		OTer.Terminal_Name end as ''''Out Reader ID'''',case when (((CD.Clk_OutPunchType = ''''O'''') OR (SH.ShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' else CD.Clk_OutPunchType end as ''''Out Punch Type'''',
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_OutDate, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''Out Date'''', Convert(varchar(10),CD.Clk_OutTime,108) as ''''Out Time''''
		 FROM TA_Tbl_Employee ED ''      
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id AS CardNo, ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',''      
		Set @SelectSQL = @SelectSQL + ''CD.Clk_InDeviceId as InReaderID,
		case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else ITer.Terminal_Name end as InTerminalName,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_InDate, ''+CONVERT(varchar,@dateFormat)+'') end AS InDate,
		Convert(varchar(10),CD.Clk_InTime,108) as InTime ,case when (((CD.Clk_InPunchType = ''''I'''') OR (SH.ShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''''F_In'''' else CD.Clk_InPunchType end as Clk_InPunchType,''      
		Set @SelectSQL = @SelectSQL + ''CD.Clk_OutDeviceId as OutReaderID,
		case when CD.Clk_OutDeviceId=''''788'''' then ''''-'''' else 
		OTer.Terminal_Name end as OutTerminalName,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_OutDate, ''+CONVERT(varchar,@dateFormat)+'') end AS OutDate, 
		Convert(varchar(10),CD.Clk_OutTime,108) as OutTime,
		case when (((CD.Clk_OutPunchType = ''''O'''') OR (SH.ShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' else CD.Clk_OutPunchType end as Clk_OutPunchType,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_Date, ''+CONVERT(varchar,@dateFormat)+'') end AS ClockDate,
		ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,ED.Gender FROM TA_Tbl_Employee ED ''   
	end
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date''   
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID ''  
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID 
	LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID ''       
	Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) ''	
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)=''PM'' and substring(@local_OutTime,7,8)=''AM'')
		begin
			Set @SelectSQL = @SelectSQL + ''And clk_indate>=''''''+@local_FromDate+'''''' and clk_outdate<=dateadd(d,1,''''''+@local_ToDate+'''''')
							and clk_intime>=''''''+@local_InTime+'''''' or clk_outtime<=''''''+@local_OutTime+''''''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + ''And (CD.Clk_InDate between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_intime between ''''''+@local_InTime+'''''' and ''''''+@local_OutTime+''''''''
			Set @SelectSQL = @SelectSQL + ''or CD.Clk_OutDate between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_Outtime between ''''''+@local_InTime+'''''' and ''''''+@local_OutTime+'''''')''
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  PD.Shift_Id = '' +  cast(@local_shift  as nvarchar(20))   
		end       
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Set @SelectSQL = @SelectSQL + '' Order By ED.employee_code_id,CD.Clk_Date,Clk_Id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc''      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempClockDetails 
	drop table #TempProcessedData   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
--	Author:		R.Manikandan
--	Create date: 17-02-2014
--	Description:	To get the first and last punch details from clock details
--	Proc_TA_RptMovementsEntry_FirstAndLast '''',''1'',''11/01/2016'',''11/24/2016'','''',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''07:01 Am'',''11:59 PM'',0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry_FirstAndLast]
	-- Add the parameters for the stored procedure here
(
	@EmployeeID VarChar(max), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(max),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@EmpAutoId bigint,
	@ExportType int 		
)
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType
	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoId
	CREATE TABLE #TempClockDetails
	(	
		[Clk_EmpId] nvarchar(20) ,		
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25) ,		
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,	
		[Clk_Date] datetime,
		[Clk_InDeviceId] nvarchar(20),
		[Clk_OutDeviceId] nvarchar(20),
		[Clk_InDate] datetime,
		[Clk_OutDate] datetime	
	)
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].#TempClockDetails 
	(
		[Clk_EmpId],		
		[Clk_InTime],
		[Clk_InPunchType],				
		[Clk_OutTime],
		[Clk_OutPunchType],
		[Clk_Date],
		[Clk_InDeviceId],
		[Clk_OutDeviceId],
		[Clk_InDate],
		[Clk_OutDate]
		ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_swipecard] ON [dbo].[#EmpLevel] 
	(
		swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IDX_EmployeeId_swipecard ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],swipecard ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		EmployeeId,designationid ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory	
	--To split up the comma separated values
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel = @sqlEmpLevel +'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
	Declare @sqlTempProcessedData1 varchar(8000)
	create table #TempPunchtypes
	(		
		id int identity(1,1),
		clk_CardId nvarchar(25),
		clk_InDeviceId nvarchar(25),
		Clk_InPunchType nvarchar(15),
		clk_InDate datetime ,
		clk_intime datetime,
		clk_Date datetime,
		Clk_OutDeviceId nvarchar(25),
		Clk_OutPunchType nvarchar(15),
		Clk_OutDate datetime,
		Clk_OutTime datetime,
		Shiftid int,
		PMorAm bit
	)
	CREATE NONCLUSTERED INDEX IDX_Clk_InPunchType_Clk_OutPunchType
	ON [dbo].[#TempPunchtypes] ([Clk_InPunchType],[Clk_OutPunchType])
	INCLUDE ([clk_CardId],[clk_InDeviceId],[clk_intime],[clk_Date],[Clk_OutDeviceId],[Clk_OutTime])
	CREATE NONCLUSTERED INDEX IDX_clk_CardId_Clk_InPunchType_Clk_OutPunchType
	ON [dbo].[#TempPunchtypes] ([clk_CardId],[Clk_InPunchType],[Clk_OutPunchType])
	INCLUDE ([clk_InDeviceId],[clk_intime],[clk_Date],[Clk_OutDeviceId],[Clk_OutTime])
	insert into #TempPunchtypes(clk_CardId,clk_Date,Shiftid,clk_intime)
	select TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,InTime
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id	
	where ((TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102)) 
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)))and(InTime is not null or OutTime is not null)	
	Create table #tempNightShift_CurrentdateInpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	Create table #tempNightShift_CurrentdateOutpunches(clk_outtime datetime,clk_empid nvarchar(30),clk_date datetime)
	insert into #tempNightShift_CurrentdateInpunches
	select	CAST(CONVERT(CHAR(17),C.clk_intime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date=C.Clk_InDate)	
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	insert into #tempNightShift_CurrentdateOutpunches
	select	CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date=C.Clk_OutDate)	
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	--select * from #tempNightShift_CurrentdateInpunches
	--select * from #tempNightShift_CurrentdateOutpunches
	update #TempPunchtypes set clk_intime=
				case when T.clk_intime IS not null then 
								case when a.intime<T.clk_intime then a.intime 
									 else T.clk_intime 
								end 
					 else a.intime end
				,Clk_OutTime= case when T.clk_intime IS not null then a.outtime
									end 
					 from #TempPunchtypes T inner join 
	(		
			select	case when min(I.clk_Intime) IS not null then 
								case	when min(I.clk_Intime)<min(O.clk_outtime)then min(I.clk_Intime)
										else min(O.clk_outtime)
								end 
						 else min(O.clk_outtime)
					end as intime,
					case when max(O.clk_outtime) IS not null then 
								case	when Max(O.clk_outtime)<max(I.clk_Intime)then max(I.clk_Intime)
										else max(O.clk_outtime)
								end 
						 else max(I.clk_Intime)
					end as outtime
			,O.clk_date,O.clk_empid from #tempNightShift_CurrentdateOutpunches O
			Left outer join #tempNightShift_CurrentdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by O.clk_date,O.clk_empid 
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	Create table #tempNightShift_NextdateInpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	Create table #tempNightShift_NextdateOutpunches(clk_Intime datetime,clk_empid nvarchar(30),clk_date datetime)
	insert into #tempNightShift_NextdateInpunches
	select	C.clk_intime,C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date!=C.Clk_InDate)
	--and T.PMorAm=1
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	insert into #tempNightShift_NextdateOutpunches
	select	CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime),C.Clk_EmpId,C.Clk_Date from TA_Tbl_ClockDetails C	
	inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
	and (T.clk_Date!=C.Clk_OutDate)
	--and T.PMorAm=1
	and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
	and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))		
	update #TempPunchtypes set [Clk_OutTime]=case when T.clk_intime IS not null then a.Outime end,
	clk_intime=case when T.clk_intime IS null then a.Outime else T.clk_intime  end from #TempPunchtypes T inner join 
	(		
			select	case when MAX(I.clk_Intime) IS not null then 
								case	when MAX(I.clk_Intime)<MAX(O.clk_Intime)then MAX(O.clk_Intime)
										else MAX(I.clk_Intime)
								end 
						 else MAX(O.clk_Intime)
					end as Outime	
			,O.clk_date,O.clk_empid from #tempNightShift_NextdateOutpunches O
			Left outer join #tempNightShift_NextdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by O.clk_date,O.clk_empid 
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	update #TempPunchtypes set [Clk_OutTime]=a.Outime from #TempPunchtypes T inner join 
	(		
			select	case when MAX(I.clk_Intime) IS not null then 
								case	when MAX(I.clk_Intime)<MAX(O.clk_Intime)then MAX(O.clk_Intime)
										else MAX(I.clk_Intime)
								end 
						 else MAX(O.clk_Intime)
					end as Outime	
			,I.clk_date,I.clk_empid from #tempNightShift_NextdateOutpunches O
			right outer join #tempNightShift_NextdateInpunches I on O.clk_empid=I.clk_empid and O.clk_date=I.clk_date
			group by I.clk_date,I.clk_empid
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date
	update #TempPunchtypes set clk_InDeviceId=a.clk_InDeviceId,Clk_InPunchType=a.clk_InPunch
	from #TempPunchtypes T inner join 
	(		
		select	case when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)   then C.Clk_InPunchType 
					 when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime)  then C.Clk_OutPunchType
					 end as clk_InPunch,
				case when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InDeviceId 
					 when T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutDeviceId
					 end as clk_InDeviceId,				
				C.Clk_EmpId,C.Clk_Date
		from TA_Tbl_ClockDetails C	
		inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
		and (T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime) or T.clk_intime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime))
		and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
		and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date	
	update #TempPunchtypes set Clk_OutDeviceId=a.clk_OutDeviceId,Clk_OutPunchType=a.clk_OutPunch
	from #TempPunchtypes T inner join 
	(		
		select	case when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InDeviceId 
					 when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutDeviceId
					 end as clk_OutDeviceId,
				case when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime)  then C.Clk_InPunchType 
					 when T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime) then C.Clk_OutPunchType
					 end as clk_OutPunch,
				C.Clk_EmpId,C.Clk_Date
		from TA_Tbl_ClockDetails C	
		inner join #TempPunchtypes T on C.Clk_EmpId=T.clk_CardId and C.Clk_Date=T.clk_Date 
		and (T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_InTime,113)AS datetime) or T.Clk_OutTime=CAST(CONVERT(CHAR(17),C.Clk_OutTime,113)AS datetime))
		and (C.clk_Date >= CONVERT(DATETIME,cast(@local_FromDate as nvarchar(20)), 102) 
		and C.clk_Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(20)), 102))
	)as a 
	on T.clk_CardId=a.Clk_EmpId and T.clk_Date=a.Clk_Date	
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int)
	CREATE NONCLUSTERED INDEX IDX_Employee_Code_Id_Date
	ON [dbo].[#TempProcessedData] ([Employee_Code_Id],[Date])
	INCLUDE ([Shift_ID],[PrevShiftType])
	CREATE NONCLUSTERED INDEX IDX_PrevShift_ID_PrevShiftType
	ON [dbo].[#TempProcessedData] (PrevShift_ID,PrevShiftType)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,''''
	from TA_Tbl_ProcessedData inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)			
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END	
	Declare @SelectSQL As Varchar(8000)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = '' ''        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + ''	SELECT ED.employee_code_id AS ''''Employee ID'''', ''      
		Set @SelectSQL = @SelectSQL + ''	ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',ED.Gender,case when ''+cast(@dateFormat as varchar(100))+''=106 then			
									REPLACE(CONVERT(VARCHAR, CD.Clk_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, CD.Clk_Date, ''+cast(@dateFormat as varchar(100))+'') end as Date,ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,''      
		Set @SelectSQL = @SelectSQL + ''	case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else  CD.Clk_InDeviceId end as ''''In Reader ID'''',	
		Convert(varchar(10),CD.Clk_InTime,108)
		as InTime,
		case when (((CD.Clk_InPunchType = ''''I'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) 
		then case	when CD.Clk_InPunchType=''''Shift In'''' then ''''F_In'''' 
					when CD.Clk_InPunchType=''''Shift Out'''' then ''''F_Out'''' 
					else ''''F_In'''' 
			end
		else CD.Clk_InPunchType end as Clk_InPunchType,''      
		Set @SelectSQL = @SelectSQL + ''case when CD.Clk_OutDeviceId=''''788'''' then ''''-'''' else  CD.Clk_OutDeviceId end	as ''''Out Reader ID'''',
			Convert(varchar(10),CD.Clk_OutTime,108)
		as OutTime,	
		case when (((CD.Clk_OutPunchType = ''''O'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then 
			case	when CD.Clk_OutPunchType=''''Shift In'''' then ''''F_In'''' 
					when CD.Clk_OutPunchType=''''Shift Out'''' then ''''F_Out'''' 
					else ''''F_Out'''' 
			end
		else CD.Clk_OutPunchType end as Clk_OutPunchType FROM TA_Tbl_Employee ED ''   
	end
	else
	begin
		Set @SelectSQL = @SelectSQL + ''	SELECT ED.employee_code_id AS CardNo, ''      
		Set @SelectSQL = @SelectSQL + ''	ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',''      
		Set @SelectSQL = @SelectSQL + ''	case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else  CD.Clk_InDeviceId end as InReaderID,	
		ITer.Terminal_Name as InTerminalName,	
		Convert(varchar(10),CD.Clk_InTime,108)
		as InTime,
		case when (((CD.Clk_InPunchType = ''''I'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) 
		then case	when CD.Clk_InPunchType=''''Shift In'''' then ''''F_In'''' 
					when CD.Clk_InPunchType=''''Shift Out'''' then ''''F_Out'''' 
					else ''''F_In'''' 
			end
		else CD.Clk_InPunchType end as Clk_InPunchType,''      
		Set @SelectSQL = @SelectSQL + ''case when CD.Clk_OutDeviceId=''''788'''' then ''''-'''' else  CD.Clk_OutDeviceId end	as OutReaderID,OTer.Terminal_Name as OutTerminalName,
			Convert(varchar(10),CD.Clk_OutTime,108)
		as OutTime,	
		case when (((CD.Clk_OutPunchType = ''''O'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then 
			case	when CD.Clk_OutPunchType=''''Shift In'''' then ''''F_In'''' 
					when CD.Clk_OutPunchType=''''Shift Out'''' then ''''F_Out'''' 
					else ''''F_Out'''' 
			end
		else CD.Clk_OutPunchType end as Clk_OutPunchType,									
										case when ''+cast(@dateFormat as varchar(100))+''=106 then			
									REPLACE(CONVERT(VARCHAR, CD.Clk_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, CD.Clk_Date, ''+cast(@dateFormat as varchar(100))+'') end as ClockDate,									
										ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,ED.Gender,
										PD.Shift_ID FROM TA_Tbl_Employee ED ''   
	end
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempPunchtypes CD ON ED.SwipeCardNo = CD.clk_CardId''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.clk_CardId and PD.Date=CD.Clk_Date''   
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID ''  
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID ''       
	Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and clk_inpunchtype is not null and clk_outpunchtype is not null and 
									((ED.employee_status=1)
									or
									(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
									)
								  ''	
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  PD.Shift_Id = '' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Set @SelectSQL = @SelectSQL + '' Order By CD.clk_cardid,CD.clk_date''      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails 
	drop table #TempProcessedData   
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMovementsEntry]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMovementsEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
	Modified By		:	A.K.T.MOORTHI
	Modified Date	:	09-Oct-2013
	Description		:	Dispaly In/Out Punch Type For ''F_In'' And ''F_Out'' When Emplopyee Shift IS Free Scan Shift Type.(Reg Bug No : 0019304)
	Modified By		:	K.Gopinath
	Modified Date	:	18-Dec-2013 & 11-Jan-2014
	Description		:	SQL Query Optimazation & Emp name filtering
*/
-- Proc_TA_RptMovementsEntry '''',''0,1'',''01/Nov/2016'',''24/Nov/2016'','''',0,0,0,''SuperAdmin'',''0'','''',0,0,''Both'',''12:00:00 Am'',''11:59:59 PM'',''all'',0,0
CREATE PROCEDURE [dbo].[Proc_TA_RptMovementsEntry]      
(
	@EmployeeID VarChar(50), 
	@LevelID VarChar(8000),  
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@EmployeeName varchar(50),
	@shift int,
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@InTime VARCHAR(50),
	@OutTime VARCHAR(20),
	@punchTypeValue varchar(20),
	@EmpAutoId bigint,
	@ExportType int
)      
AS      
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @local_EmployeeID VarChar(50)
	DECLARE @local_LevelID VarChar(8000)
	DECLARE @local_FromDate VarChar(50) 
	DECLARE @local_ToDate VarChar(50)
	DECLARE @local_EmployeeName varchar(50)
	DECLARE @local_shift int
	DECLARE @local_employeeCategory int
	DECLARE @local_employeeType int
	DECLARE @local_UserGroupName varchar(250)
	DECLARE @local_GradeLevel varchar(20)
	DECLARE @local_EmpSwipeCard varchar(20)
	DECLARE @local_ParentId int
	DECLARE @local_DesignationID int
	DECLARE @local_Gender varchar(10)
	DECLARE @local_InTime VARCHAR(50)
	DECLARE @local_OutTime VARCHAR(20)
	DECLARE @local_punchTypeValue varchar(20)
	DECLARE @local_EmpAutoId bigint
	DECLARE @local_ExportType int
	
	set @local_EmployeeID=@EmployeeID
	set @local_LevelID=@LevelID
	set @local_FromDate=@FromDate
	set @local_ToDate=@ToDate
	set @local_EmployeeName=@EmployeeName
	set @local_shift=@shift
	set @local_employeeCategory=@employeeCategory
	set @local_employeeType=@employeeType
	set @local_UserGroupName=@UserGroupName
	set @local_GradeLevel=@GradeLevel
	set @local_EmpSwipeCard=@EmpSwipeCard
	set @local_ParentId=@ParentId
	set @local_DesignationID=@DesignationID
	set @local_Gender=@Gender
	set @local_InTime=@InTime
	set @local_OutTime=@OutTime
	set @local_punchTypeValue=@punchTypeValue
	set @local_EmpAutoId=@EmpAutoId
	set @local_ExportType=@ExportType	
	
	
	DECLARE @dateFormat as int
	select @dateFormat=DateFormat from dbo.Func_TA_GetDateTimeFormat();
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoId) as EmpAutoIdD
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	CREATE TABLE #TempClockDetails
	(
		[Clk_Id] int,
		[Clk_CompId] varchar(10) ,
		[Clk_EmpId] nvarchar(20) ,
		[Clk_InDeviceId] nvarchar(20) ,
		[Clk_InDate] datetime,
		[Clk_InTime] datetime,
		[Clk_InPunchType] nvarchar(25) ,
		[Clk_OutDeviceId] nvarchar(20) ,
		[Clk_OutDate] datetime,
		[Clk_OutTime] datetime,
		[Clk_OutPunchType] nvarchar(25) ,
		[Clk_Process] nvarchar(1) ,
		[Clk_Remarks] nvarchar(255) ,
		[Clk_User] nvarchar(20) ,
		[Clk_Date] datetime,
		[Clk_Status] char(1) ,
		[IsVoid] bit,
		PunchType_Remarks nvarchar(max)
	)
	Declare @sqlEmpLevel nvarchar(4000)
	if(@local_EmployeeID is not null and @local_EmployeeID <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@local_EmployeeID)
		end
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDate,@local_EmployeeID,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDate,@local_EmployeeID,@local_employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDate,@local_EmployeeID,@local_employeeCategory
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		where SwipeCardNo is not null and emp.Isdeleted=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlEmpLevel = @sqlEmpLevel + '' and emp.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	set @sqlEmpLevel=@sqlEmpLevel+'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''
	If Not (@local_EmployeeID = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End	
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=
		''insert into #TempClockDetails
		select [Clk_Id],[Clk_CompId],[Clk_EmpId],[Clk_InDeviceId],[Clk_InDate],[Clk_InTime],[Clk_InPunchType],[Clk_OutDeviceId],[Clk_OutDate],
		[Clk_OutTime],[Clk_OutPunchType],[Clk_Process],[Clk_Remarks],[Clk_User],[Clk_Date],[Clk_Status],[IsVoid],PunchType_Remarks
		from TA_Tbl_ClockDetails Inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ClockDetails.clk_empid
		where ta_tbl_clockdetails.IsVoid=0 and ta_tbl_clockdetails.clk_Date >= CONVERT(DATETIME,''''''+cast(@local_FromDate as nvarchar(20))+'''''', 102) 
			and ta_tbl_clockdetails.clk_Date <= CONVERT(DATETIME,''''''+cast(@local_ToDate as nvarchar(20))+'''''', 102)''
	if(@local_punchTypeValue=''Break In'')
		begin
			set @sqlTempProcessedData1=@sqlTempProcessedData1+ '' and clk_InpunchType=''''Break In''''''
		end
	if(@local_punchTypeValue=''Shift In'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+'' and clk_InpunchType=''''Shift In''''''
		end
	if(@local_punchTypeValue=''In'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_InpunchType=''''In''''''
		end
	if(@local_punchTypeValue=''Lunch In'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_InpunchType=''''Lunch In''''''
		end
	if(@local_punchTypeValue=''Out Duty'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_InpunchType=''''out Duty''''''
		end
	if(@local_punchTypeValue=''Official Out'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_InpunchType=''''Official Out''''''
		end
	if(@local_punchTypeValue=''Break Out'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''Break Out''''''
		end	
	if(@local_punchTypeValue=''Shift Out'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''Shift Out''''''
		end	
	if(@local_punchTypeValue=''Out'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''Out''''''
		end	
	if(@local_punchTypeValue=''Lunch Out'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''Lunch Out''''''
		end	
	if(@local_punchTypeValue=''in Duty'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''in Duty''''''
		end	
	if(@local_punchTypeValue=''official In'')
		begin
			set @sqlTempProcessedData1= @sqlTempProcessedData1+ '' and clk_OutpunchType=''''Official In''''''
		end
	Execute(@sqlTempProcessedData1)	
	if(@local_punchTypeValue in(''Break In'',''Shift In'',''In'',''Lunch In'',''Official Out'',''Out Duty''))
		begin
			update #TempClockDetails set Clk_OutDate=null,Clk_OutDeviceId=null,Clk_OutTime=null,Clk_OutPunchType=null
		end
	else if(@local_punchTypeValue in(''Break Out'',''Shift Out'',''Out'',''Lunch Out'',''Official In'',''In Duty''))
		begin
			update #TempClockDetails set Clk_InDate=null,Clk_InDeviceId=null,Clk_InTime=null,Clk_InPunchType=null
		end	
	--select * from #TempClockDetails 
	create table #TempProcessedData(EmpAutoId bigint,Employee_Code_Id nvarchar(20) ,Shift_ID int,Date datetime,PrevShift_ID int,PrevShiftType int)
	insert into #TempProcessedData 
	select #EmpLevel.EmployeeId,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Shift_Id,''''
	from TA_Tbl_ProcessedData 
	inner join #EmpLevel on #EmpLevel.SwipeCard=TA_Tbl_ProcessedData.Employee_Code_Id
	where (TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,cast( @local_FromDate as nvarchar(50)), 102))  
	AND (TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,cast(@local_ToDate as nvarchar(50)), 102)) 
	------------------------------------------------------Current date is Weekly off, to get the previous date shift--------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-1,Date) as prevdate,Date
			from #TempProcessedData where Shift_Id=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	--------------------------------------------------------Again the previous date is also Weekly off means, to get the previous date shift---------------------------------------------------
	update #TempProcessedData set PrevShift_ID=b.Shift_Id from #TempProcessedData T inner join
	(
		select P.Employee_Code_Id,a.date,P.Shift_Id from TA_Tbl_ProcessedData P inner join
		(
			select Employee_Code_Id,DATEADD(D,-2,Date) as prevdate,Date
			from #TempProcessedData where PrevShift_ID=-1 	
		)
		as a on a.Employee_Code_Id=P.Employee_Code_Id and p.Date=a.prevdate
	)as b on T.Employee_Code_Id=b.Employee_Code_Id and T.Date=b.date
	------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	update #TempProcessedData set PrevShiftType=S.ShiftType from #TempProcessedData T
	inner join TA_Tbl_Shift S on T.PrevShift_ID=S.Shift_Id and S.Isdeleted=0	
	Declare @SelectSQL As Varchar(max)      
	Set @EmployeeName = @local_EmployeeName      
	Set @SelectSQL = '' ''        
	if(@local_ExportType=1)
	begin
		Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id AS ''''Employee ID'''', ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',ED.Gender,case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_Date, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''Date'''',''      
		Set @SelectSQL = @SelectSQL + ''case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else ITer.Terminal_Name end as ''''In Reader ID'''',case when (((CD.Clk_InPunchType = ''''I'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''''F_In'''' else CD.Clk_InPunchType end as ''''In Punch Type'''',
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_InDate, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''In Date'''',
		Convert(varchar(10),CD.Clk_InTime,108) as ''''In Time'''' ,	
		''      
		Set @SelectSQL = @SelectSQL + ''case when CD.Clk_OutDeviceId=''''788'''' or CD.Clk_OutDeviceId=''''787''''  then ''''-'''' else 
		OTer.Terminal_Name end as ''''Out Reader ID'''',
		case when (((CD.Clk_OutPunchType = ''''O'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' else CD.Clk_OutPunchType end as ''''Out Punch Type'''',
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_OutDate, ''+CONVERT(varchar,@dateFormat)+'') end AS ''''Out Date'''', 
		Convert(varchar(10),CD.Clk_OutTime,108) as ''''Out Time'''',ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,	
		case when CD.PunchType_Remarks!='''''''' then PunchType_Remarks else Clk_Remarks end Remarks
		FROM TA_Tbl_Employee ED ''  
	end
	else
	begin
	    Set @SelectSQL = @SelectSQL + ''SELECT ED.employee_code_id AS CardNo, ''      
		Set @SelectSQL = @SelectSQL + ''ED.Employee_FirstName + ''      
		Set @SelectSQL = @SelectSQL + '' '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''Employee Name'''', ''      
		Set @SelectSQL = @SelectSQL + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS Designation, ''      
		set @SelectSQL = @SelectSQL + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS ''''Level Name'''',''      
		Set @SelectSQL = @SelectSQL + ''CD.Clk_InDeviceId as InReaderID,	
		case when CD.Clk_InDeviceId=''''787'''' then ''''-'''' else ITer.Terminal_Name end as InTerminalName,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_InDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_InDate, ''+CONVERT(varchar,@dateFormat)+'') end AS InDate,
		Convert(varchar(10),CD.Clk_InTime,108) as InTime ,	
		case when (((CD.Clk_InPunchType = ''''I'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_InTime IS NOT NULL)) then ''''F_In'''' else CD.Clk_InPunchType end as Clk_InPunchType,''      
		Set @SelectSQL = @SelectSQL + ''CD.Clk_OutDeviceId as OutReaderID,
		case when CD.Clk_OutDeviceId=''''788'''' then ''''-'''' else 
		OTer.Terminal_Name end as OutTerminalName,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_OutDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_OutDate, ''+CONVERT(varchar,@dateFormat)+'') end AS OutDate, 
		Convert(varchar(10),CD.Clk_OutTime,108) as OutTime,	
		case when (((CD.Clk_OutPunchType = ''''O'''') OR (PD.PrevShiftType = 1)) and (CD.Clk_OutTime IS NOT NULL)) then ''''F_Out'''' else CD.Clk_OutPunchType end as Clk_OutPunchType,
		case when cast(''+CONVERT(varchar,@dateFormat) +''as varchar(100))=106 then
		REPLACE(CONVERT(VARCHAR, Clk_Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
		else CONVERT(VARCHAR, Clk_Date, ''+CONVERT(varchar,@dateFormat)+'') end AS ClockDate,ISNULL(SH.Shift_ShortName,''''Off'''') as Shift_ShortName,ED.Gender 
		,case when CD.PunchType_Remarks!='''''''' then PunchType_Remarks else Clk_Remarks end Remarks
		FROM TA_Tbl_Employee ED ''  
	end
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid = ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid = ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempProcessedData PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date''   
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID ''  
	Set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID ''       
	Set @SelectSQL = @SelectSQL + '' Where ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and 
	((ED.employee_status=1)
	or
	(ED.employee_status=0 and convert(nvarchar(11),ED.InActiveDate,102)>=convert(nvarchar(11),CD.Clk_Date,102))
	 ) ''
	if(@local_Gender<>''Both'')
		begin
			set @SelectSQL = @SelectSQL + '' and ED.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	if(substring(@local_InTime,7,8)=''PM'' and substring(@local_InTime,7,8)=''AM'')
		begin
			Set @SelectSQL = @SelectSQL + ''And Clk_Date>=''''''+@local_FromDate+'''''' and Clk_Date<=dateadd(d,1,''''''+@local_ToDate+'''''')
							and clk_intime>=''''''+@local_InTime+'''''' or clk_outtime<=''''''+@local_OutTime+''''''''
		end
	else
		begin
			Set @SelectSQL = @SelectSQL + ''And (CD.Clk_Date between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_intime between ''''''+@local_InTime+'''''' and ''''''+@local_OutTime+''''''''
			Set @SelectSQL = @SelectSQL + ''or CD.Clk_Date between '''''' + @local_FromDate + '''''' And '''''' + @local_ToDate + '''''' and clk_Outtime between ''''''+@local_InTime+'''''' and ''''''+@local_OutTime+'''''')''
		end 
	if(@local_shift<>0)
		begin
			set @SelectSQL = @SelectSQL +  '' And  PD.Shift_Id = '' +  cast(@local_shift  as nvarchar(20))   
		end
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Set @SelectSQL = @SelectSQL + '' Order By ED.employee_code_id,ED.Employee_FirstName,ED.Employee_LastName,CD.Clk_Date,CD.Clk_InDate,cast(CD.Clk_Intime as datetime),CD.Clk_outDate,cast(CD.Clk_OutTime as dateTime) Asc''      
	Exec (@SelectSQL)
	--Drop the Temporary tables
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights  	
	drop table #TempClockDetails 
	drop table #TempProcessedData
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOverTimewithAmountDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOverTimewithAmountDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_leveldetails where parentid=0
-- proc_OtCalculation ''03/01/2011'',''03/1/2011'','''','''','''','''','''','''',''SuperAdmin'','''','''','''',323,0,''Both''
CREATE PROCEDURE [dbo].[Proc_TA_RptOverTimewithAmountDetails] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @Amount numeric(18,2),
    @EmpAutoID int
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--select * from #LevelRights
CREATE TABLE #TempProcessedData
(
	[Process_Rec_ID] bigint,
	[Employee_Code_Id] nvarchar(20),
	[Date] datetime,
	[Shift_Id] int,
	[InTime] nvarchar(25),
	[OutTime] nvarchar(25),
	[HrsWork] nvarchar(10),
	[HrsOT] nvarchar(10),
	[NormOT] nvarchar(10),
	[OffOT] nvarchar(10),
	[HolOT] nvarchar(10),
	[EarlyOut] nvarchar(10),
	[LateIn] nvarchar(10),
	[Attendance] nvarchar(20),
	[WorkHrs] nvarchar(10),
	[HrsLess] nvarchar(10),
	[HrsExtra] nvarchar(10),
	[LateInMins] float,
	[EarlyOutMins] float,
	[ExtraMins] float,
	[OtMins] float,
	[OvertimeStatus] nvarchar(50),
	[TotalDays] numeric(18, 1),
	[LeaveCode] nvarchar(20),
	[LateEntryReason] nvarchar(260),
	[EarlyOutReason] nvarchar(260),
	[ProcessFlag] bit,
	[Status] nvarchar(50),
	[FNAttendanceCode] nvarchar(15),
	[ANAttendanceCode] nvarchar(15)
)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
insert into #TempProcessedData
select PD.Process_Rec_ID,PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.InTime,PD.OutTime,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.OffOT,PD.HolOT,PD.EarlyOut,
PD.LateIn,PD.Attendance,PD.WorkHrs,PD.HrsLess,PD.HrsExtra,PD.LateInMins,PD.EarlyOutMins,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.TotalDays,
PD.LeaveCode,PD.LateEntryReason,PD.EarlyOutReason,PD.ProcessFlag,PD.Status,PD.FNAttendanceCode,PD.ANAttendanceCode
from TA_Tbl_ProcessedData as PD 
--inner join ta_tbl_employee e on e.SwipeCardNo=PD.Employee_Code_Id
--inner join #EmpLevel el on el.employeeid=e.employee_id
where
Employee_Code_Id in (
select SwipeCardNo from ta_tbl_employee e
inner join #EmpLevel el on el.employeeid=e.employee_id
) and
(PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)) and PD.OTMins<>0
--select * from #TempProcessedData where OtMins <>0
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + '' select * from (''
	set @sqlQuery = @sqlQuery + ''select TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,''
	set @sqlQuery = @sqlQuery + ''ISNULL(ta_tbl_shift.Shift_ShortName,''''Off'''') as ShiftName, #TempProcessedData.OtMins,CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''NormOTMins'''',CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''WeekOffOTMins'''',CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END as ''''HolidayOTMins'''',''
	set @sqlQuery = @sqlQuery + '' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT,#TempProcessedData.OffOT,#TempProcessedData.HolOT, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''''''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],ISNULL(#TempProcessedData.OverTimeStatus,''''Pending'''') as OverTimeStatus,0 as SelectedRecords,Ta_Tbl_Employee.SwipeCardNo,replace(Ta_tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender, 0 as Amount from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''	 
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on  #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.employeeid=TA_Tbl_Employee.Employee_Id ''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
	--set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	--set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' where #TempProcessedData.OtMins <> 0 ''
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end
	if(@shift<>0) 
	begin
		set @sqlQuery = @sqlQuery + '' And #TempProcessedData.Shift_Id='' + cast (@shift as nvarchar(50))  
	end 
	set @sqlQuery = @sqlQuery + '' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1''
	if not(@EmployeeName='''')
	begin
		--set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
				set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End 
	if not (@empId='''')
	begin
		set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
	end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	 if(@Gender<>''Both'')
		begin
		   set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
        BEGIN
         set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
        END
	if not(@status='''' or @status=''All'')
	begin
	 	IF(@status = ''Pending'')
			BEGIN
				set @sqlQuery = @sqlQuery + '' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = '''''' + @status + '''''')''
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + '' AND #TempProcessedData.OvertimeStatus = '''''' + @status + ''''''''
			END
    end 
	set @sqlQuery = @sqlQuery + '' ) OverTime order by OverTime.Employee_Code_Id , OverTime.Date''
	exec (@sqlQuery)
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptOnDutyEntry]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptOnDutyEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*   
Procedure Name : Proc_TA_RptOnDutyEntry    
Description : select OnDuty entry details
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : K.Gopinath
Created On : 01-Feb-2014  
Modified for BUg no.21817 on 12Aug14 by GOpinath
Proc_TA_RptOnDutyEntry '''','''',''02/01/2016'',''12/19/2020'','''',0,0,''SuperAdmin'','''','''','''',0,0,''Both'',0
*/  


CREATE PROCEDURE [dbo].[Proc_TA_RptOnDutyEntry] 
(
	@employeeName nvarchar(max),
	@employeeId nvarchar(max),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)
AS  
BEGIN	
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery = ''''
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec [Proc_TA_Emplevel] @ToDate,@EmployeeId	
	create table #EmployeeName(EmployeeID varchar(25))
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	DECLARE @dateFormat as int
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	
	SELECT	distinct dbo.TA_Tbl_Employee.Employee_Code_Id as Onduty_Employee_Id,
			ISNULL(TA_Tbl_Employee.Employee_FirstName, '' '') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, '' '') AS Employee_Name,
			replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as name,
			TA_Tbl_Title.TitleName,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate,106),'' '',''-'') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_EntryDate, 106)
			end  AS Onduty_EntryDate, 
			TA_Tbl_Employee.Gender,   
			case	when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate,106),'' '',''-'') 
					else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_FromDate, 106)
			end AS Onduty_FromDate, 
			TA_Tbl_OndutyEntry.Onduty_FromTime,
			case when @dateFormat=106 then REPLACE(CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate,106),'' '',''-'') 
				 else CONVERT(VARCHAR, TA_Tbl_OndutyEntry.Onduty_ToDate, 106)
			end AS Onduty_ToDate, 
			TA_Tbl_OndutyEntry.Onduty_ToTime,
			replace(TA_Tbl_OndutyEntry.Onduty_Reason,''&amp;'',''&'') as Onduty_Reason,
			TA_Tbl_OndutyEntry.Onduty_Status,
			
			TA_Tbl_OndutyEntry.Onduty_ID 
	FROM TA_Tbl_Employee 
	INNER JOIN TA_Tbl_OndutyEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_OndutyEntry.Onduty_EmployeeID 
	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id  
	inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
	Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id  
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId 
	Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id  
	Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId  	
	WHERE 
	(
		(TA_Tbl_Employee.Employee_Status = 1) 
		or 
		(
			TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)>= convert(varchar(11),TA_Tbl_OndutyEntry.Onduty_EntryDate,102)
		)
	)
	AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) AND
	(isnull(@EmployeeName,'''')='''' or TA_Tbl_Employee.Employee_Code_Id in(select EmployeeID from #EmployeeName))
	and(isnull(@Gender,''Both'')=''Both'' or TA_Tbl_Employee.Gender=@Gender)
	and(isnull(@UserGroupName,''Superadmin'')=''Superadmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)and
	(isnull(@isReportingto,0)=0 or TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds))and
	(ISNULL(@Status,''All'')=''All'' or @Status='''' or TA_Tbl_OndutyEntry.Onduty_Status = @Status)and
	(((CONVERT(DATETIME, @fromdate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate) or 
	(CONVERT(DATETIME, @toDate, 102) between TA_Tbl_OndutyEntry.Onduty_FromDate and TA_Tbl_OndutyEntry.Onduty_ToDate)) or 
	(TA_Tbl_OndutyEntry.Onduty_FromDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102)) or 
	(TA_Tbl_OndutyEntry.Onduty_ToDate between CONVERT(DATETIME, @fromdate, 102) and CONVERT(DATETIME, @toDate, 102))) 
	order by TA_Tbl_Employee.Employee_Code_Id,Onduty_FromDate
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyWithApprovalSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_SelectCompanyWithApprovalSettings
Description	:	select the companies
Tables Included	:	TA_Tbl_LevelDetails,TA_Tbl_Level
Created By	:	Christopher S
Created On	:	10-Jan-09
Modified By	:
Modified On	:
[Proc_TA_SelectCompanyWithApprovalSettings] ''SuperAdmin'',''70'',0,''P''
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompanyWithApprovalSettings]
	-- Add the parameters for the stored procedure here
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int,
	@Type varchar(2)	
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(7000)
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- R = Shift Roaster
	if(@Type=''R'')
		BEGIN
			set @Query = ''select ld.id as CompanyId,replace(ld.name,''''&amp;'''',''''&'''') as CompanyName'' 
			set @Query= @Query +'' from TA_Tbl_LevelDetails ld''
			set @Query= @Query +'' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId''
			set @Query= @Query +'' inner join TA_Tbl_ApprovalSettings aps on aps.CompanyId=ld.Id''
			set @Query= @Query +'' inner join #LevelRights on #LevelRights.LevelId=ld.id''
			--set @Query= @Query +'' where aps.PatternRoster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in (''+ @UserLevels +'')''
			set @Query= @Query +'' where aps.Roster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0''
		END
		-- P = Shift pattern
       ELSE if(@Type=''P'')
		BEGIN
			set @Query = ''select ld.id as CompanyId,replace(ld.name,''''&amp;'''',''''&'''') as CompanyName'' 
			set @Query= @Query +'' from TA_Tbl_LevelDetails ld''
			set @Query= @Query +'' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId''
			set @Query= @Query +'' inner join TA_Tbl_ApprovalSettings aps on aps.CompanyId=ld.Id''
			set @Query= @Query +'' inner join #LevelRights on #LevelRights.LevelId=ld.id''
			--set @Query= @Query +'' where aps.PatternRoster=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in (''+ @UserLevels +'')''
			set @Query= @Query +'' where aps.Pattern=1 and l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0''
		END
		exec (@Query)
		drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttendanceXtraGrid]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAttendanceXtraGrid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectAttendanceXtraGrid]
	-- Add the parameters for the stored procedure here
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LevelRights varchar(1000),
	@ParentId int,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
			set @sqlQuery = ''''
			set @sqlQuery = @sqlQuery + ''SELECT TA_Tbl_EmployeeLevel.LevelID, TA_Tbl_EmployeeDesignation.DesignationId, TA_Tbl_Employee.Employee_Code_Id AS [Employee Code Id],'' 
			set @sqlQuery = @sqlQuery + '' convert(varchar(10),TA_Tbl_ProcessedData.Date,103) AS [Date], TA_Tbl_ProcessedData.InTime, TA_Tbl_ProcessedData.OutTime, TA_Tbl_ProcessedData.LateIn, TA_Tbl_ProcessedData.EarlyOut, ta_tbl_processedData.NormOt as OverTime, isnull(TA_Tbl_Employee.Employee_FirstName,'''''''') + SPACE(1)+ isnull(TA_Tbl_Employee.Employee_LastName,'''''''') AS [Employee Name],'' 
			set @sqlQuery = @sqlQuery + '' TA_Tbl_ProcessedData.Attendance, replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as [Designation],'' 
			set @sqlQuery = @sqlQuery + '' replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as [Level Name], ta_tbl_shift.Shift_ShortName AS [Shift Short Name]''
			set @sqlQuery = @sqlQuery + '' FROM TA_Tbl_ProcessedData'' 
			set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Employee ON dbo.TA_Tbl_ProcessedData.Employee_Code_Id = dbo.TA_Tbl_Employee.SwipeCardNo''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
			set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		    set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID'' 
			set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_EmployeeDesignation.DesignationId = TA_Tbl_Title.TitleId''
			set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
			set @sqlQuery = @sqlQuery + '' inner JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = TA_Tbl_ProcessedData.Shift_ID'' 	
			set @sqlQuery = @sqlQuery + '' inner JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId'' 	
	        set @sqlQuery = @sqlQuery + '' WHERE (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0)AND (TA_Tbl_Employee.Report_Exclude = 0)''					
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
			--set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
			if(@UserGroupName<>''SuperAdmin'')
				begin
					set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
				end
			if(@EmpAutoId = 0)
				BEGIN 
				  set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
				END
			ELSE
			   BEGIN
				  set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
			   END
			If (@FromDate <> '''')      
			 Begin      
				Set @sqlQuery = @sqlQuery + ''And TA_Tbl_ProcessedData.Date >= '''''' + @FromDate + '''''' ''      
			 End      
		 If (@ToDate <> '''')      
			Begin      
				Set @sqlQuery = @sqlQuery + ''And TA_Tbl_ProcessedData.Date <= '''''' + @ToDate + '''''' ''      
			End   
			EXEC (@sqlQuery)
			drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAttandanceCode]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAttandanceCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectAttandanceCode 5,''No'','''',''''
CREATE PROCEDURE [dbo].[Proc_TA_SelectAttandanceCode]
	@AttandanceID as int,
	@All as varchar(3),
	@UserGroup as varchar(250),
	@UserLevels as varchar(2000),
	@ParentID int		
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroup,@ParentID) as LevelId   
declare @Query as varchar(7000)
BEGIN	
	if (@All=''All'')
		Begin	
			if (@UserGroup=''SuperAdmin'')
				BEGIN
					--select * from TA_Tbl_AttandanceCode order by AttandanceCode
					set @Query= ''select TA_Tbl_AttandanceCode.AttandanceID, TA_Tbl_AttandanceCode.CompanyID, TA_Tbl_AttandanceCode.AttandanceCode, TA_Tbl_AttandanceCode.AttandanceValue, TA_Tbl_AttandanceCode.EmpID,case when TA_Tbl_AttandanceCode.IsDeleted=1 then ''''True'''' else ''''False'''' end isDeleted, TA_Tbl_AttandanceCode.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode''
					set @Query=@Query + '' inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id''
					set @Query=@Query + '' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_AttandanceCode.CompanyId''
					--set @Query=@Query + '' where TA_Tbl_AttandanceCode.CompanyId in ('' +@UserLevels+ '')''
					set @Query=@Query + '' order by ta_tbl_leveldetails.name''
				End
			Else
				Begin
					--select * from TA_Tbl_AttandanceCode where isdeleted=0 order by AttandanceCode
					set @Query= ''select TA_Tbl_AttandanceCode.AttandanceID, TA_Tbl_AttandanceCode.CompanyID, TA_Tbl_AttandanceCode.AttandanceCode, TA_Tbl_AttandanceCode.AttandanceValue, TA_Tbl_AttandanceCode.EmpID,case when TA_Tbl_AttandanceCode.IsDeleted=1 then ''''True'''' else ''''False'''' end isDeleted, TA_Tbl_AttandanceCode.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode''
					set @Query=@Query + '' inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id''
					set @Query=@Query + '' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_AttandanceCode.CompanyId''
					--set @Query=@Query + '' where TA_Tbl_AttandanceCode.isdeleted=0 and TA_Tbl_AttandanceCode.CompanyId in ('' +@UserLevels+ '')''
					set @Query=@Query + '' where TA_Tbl_AttandanceCode.isdeleted=0''
					set @Query=@Query + '' order by ta_tbl_leveldetails.name''
				End
		End
	Else
		Begin
			set @Query= ''select * from TA_Tbl_AttandanceCode where AttandanceId='' +cast(@AttandanceID as varchar(100))+ '' order by AttandanceCode''
		End
END
exec(@Query)
drop table #LevelRights
/*ALTER PROCEDURE [dbo].[Proc_TA_SelectAttandanceCode]
	@AttandanceID as int,
	@All as varchar(3),
	@UserGroup as varchar(25)	
AS
BEGIN	
	if (@All=''All'')
		Begin	
			if (@UserGroup=''SuperAdmin'')
				BEGIN
					--select * from TA_Tbl_AttandanceCode order by AttandanceCode
						select TA_Tbl_AttandanceCode.*,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode
						inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id
						order by ta_tbl_leveldetails.name
				End
			Else
				Begin
					--select * from TA_Tbl_AttandanceCode where isdeleted=0 order by AttandanceCode
						select TA_Tbl_AttandanceCode.*,ta_tbl_leveldetails.name  from TA_Tbl_AttandanceCode
						inner join ta_tbl_leveldetails on  TA_Tbl_AttandanceCode.CompanyId = ta_tbl_leveldetails.id
						where TA_Tbl_AttandanceCode.isdeleted=0
						order by ta_tbl_leveldetails.name
				End
		End
	Else
		Begin
			select * from TA_Tbl_AttandanceCode where AttandanceId=@AttandanceID order by AttandanceCode
		End
END
*/
' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectAbsentRecords]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_SelectAbsentRecords]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
-- [proc_ta_SelectAbsentRecords] ''02/Jan/2000'',''14/Mar/2020'','''',0,'''',''0'',0,0,''SuperAdmin'',''0'','''',1,1
CREATE PROCEDURE [dbo].[proc_ta_SelectAbsentRecords]  
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @empId varchar(100),  
	 @shift int,  
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000),  
	 @employeeCategory int,  
	 @employeeType int,  
	 @UserGroupName varchar(250),  
	 @GradeLevel varchar(20) ,  
	 @EmpSwipeCard varchar(20),
	 @CompanyId int,
	 @ParentId int  
)  
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),InReaderId varchar(20),OutReaderId varchar(20))
			
	--Employee Level insert in Temporary table  
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId) ELevel  
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId  
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null  
	--select * from #EmpLevel  
	--Employee Designation insert in Temporary table  
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EDesig  
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null  
	--select * from #EmpDesignation  
	--Employee Type insert in Temporary table  
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EmpType  
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null  
	--select * from #EmpType  
	--Employee Category insert in Temporary table  
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
	--select * from #EmpCategory  
	create table #TempFinal
	(
		Employee_Code_Id nvarchar(15),
		EmployeeAutoId int,
		EmpName nvarchar(150),
		InReaderID nvarchar(20),
		InTerminalName nvarchar(50),
		InDate nvarchar(20),
		InTime nvarchar(20),
		InPunchType nvarchar(25) null,
		OutReaderID nvarchar(20),
		OutTerminalName nvarchar(50),
		OutDate nvarchar(20),
		OutTime nvarchar(20),
		OutPunchType nvarchar(25) null,
		ClockDate varchar(20),
		CLK_EmpID nvarchar(20),
		CLK_ID int,
		DiscrepancyType varchar(2),
		Reason varchar(255),
		MaxHoursBeforeShift nvarchar(50),
		Shift_Id int,
		WeeklyOffStartHours nvarchar(5),
		ShiftInDateTime nvarchar(20),
		Shift_StartTime nvarchar(10),
		Shift_EndTime nvarchar(10),
		--ShiftOutDateTime nvarchar(20),
		ManualEntryAlreadyExists varchar(5)
	)
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	
	insert into  #TempProcessedData 
	select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.FNAttendanceCode,TA_Tbl_ProcessedData.ANAttendanceCode,'''',''''
	from #TempEmployee  
	INNER JOIN TA_Tbl_ProcessedData ON  TA_Tbl_ProcessedData.Shift_Id <>0 and (TA_Tbl_ProcessedData.InTime is null or TA_Tbl_ProcessedData.InTime=''00:00'')
	and (TA_Tbl_ProcessedData.OutTime is null or TA_Tbl_ProcessedData.OutTime=''00:00'') and TA_Tbl_ProcessedData.FNAttendanceCode=''Absent'' 
	and TA_Tbl_ProcessedData.ANAttendanceCode=''Absent'' and #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id 
	and Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
	
	create table #EmpSwipeCardNo(EmpSwipeCardNo nvarchar(20),ReaderId varchar(20),OutReaderId varchar(20))
	insert into #EmpSwipeCardNo select SwipeCardNo,dbo.Func_TA_SelectInReaderId(SwipeCardNo,''In''),dbo.Func_TA_SelectInReaderId(SwipeCardNo,''Out'') from TA_Tbl_Employee where SwipeCardNo in(select distinct Employee_Code_Id from #TempProcessedData)
	
	update #TempProcessedData set InReaderId=T1.ReaderId,OutReaderID=T1.OutReaderId from #EmpSwipeCardNo T1
	inner join #TempProcessedData on #TempProcessedData.Employee_Code_Id=T1.EmpSwipeCardNo
	
	Declare @InReaderAutoID nvarchar(10)
	Declare @OutReaderAutoID nvarchar(10)
	set @InReaderAutoID =''''
	set @OutReaderAutoID =''''
	---added this condition newly on 13-Feb-2020
	if exists(select Terminal_ReaderID from TA_Tbl_Terminal where Terminal_ReaderID=''787'')
	begin
		select @InReaderAutoID=Terminal_Id from TA_Tbl_Terminal where Terminal_ReaderID=''787''
		Declare @CountReader int
		select @CountReader =COUNT(*) from TA_Tbl_Entrance_INOUTDetails where Reader_Id=@InReaderAutoID
		if(@CountReader>1)
		begin
			set @InReaderAutoID=787
			set @OutReaderAutoID=787
		end
		else
		begin
			set @InReaderAutoID=787
			set @OutReaderAutoID=788
		end
	end
	--select * from #TempProcessedData
	declare @sqlQuery as varchar(8000) 
	declare @sqlQuery1 as varchar(8000)  
	set @sqlQuery = '''' 
	set @sqlQuery1 = ''''
	SET @sqlQuery = @sqlQuery + ''insert into #TempFinal SELECT ta_tbl_Employee.employee_code_id AS Employee_Code_Id,ta_tbl_Employee.employee_id AS EmployeeAutoId, ''        
	SET @sqlQuery = @sqlQuery + ''ta_tbl_Employee.Employee_FirstName + ''        
	SET @sqlQuery = @sqlQuery + '' '''' '''' + isnull(ta_tbl_Employee.Employee_LastName,'''''''') AS ''''EmpName'''', '' 
	SET @sqlQuery = @sqlQuery + '' case when ''''''+CONVERT(varchar(20),@InReaderAutoID) +''''''!='''''''' then ''''''+CONVERT(varchar(20),@InReaderAutoID) +'''''' else #TempProcessedData.InReaderID end as InReaderID,CONVERT(nvarchar(50),'''''''') as InTerminalName,CONVERT(varchar(1),'''''''') as InDate,#TempProcessedData.InTime as InTime, '''''''', '' 
	SET @sqlQuery = @sqlQuery + '' case when ''''''+CONVERT(varchar(20),@OutReaderAutoID) +''''''!='''''''' then ''''''+CONVERT(varchar(20),@OutReaderAutoID) +'''''' else #TempProcessedData.InReaderID end as OutReaderID,CONVERT(nvarchar(50),'''''''') as OutTerminalName,CONVERT(varchar(1),'''''''') as OutDate,#TempProcessedData.OutTime as OutTime,'''''''',CONVERT(VARCHAR,#TempProcessedData.Date,101) as ClockDate,ta_tbl_Employee.SwipeCardNo AS CLK_EmpId,CONVERT(int,'''''''') as CLK_ID'' 
	SET @sqlQuery = @sqlQuery + '',CONVERT(varchar(1),''''A'''') as DiscrepancyType,CONVERT(varchar(255),'''''''') as Reason'' 
	SET @sqlQuery = @sqlQuery + '',TA_Tbl_ShiftSettings.MaxHoursBeforeShift,#TempProcessedData.Shift_Id''
	SET @sqlQuery = @sqlQuery + '',TA_Tbl_ShiftSettings.WeeklyOffStartHours'' 
	SET @sqlQuery = @sqlQuery + '' ,((CONVERT(VARCHAR,#TempProcessedData.Date,101)) + CONVERT(varchar(1),'''' '''') + TA_Tbl_Shift.Shift_StartTime) AS ShiftInDateTime''  
	set @sqlQuery = @sqlQuery + '' ,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime,''''No'''' as ManualEntryAlreadyExists from TA_Tbl_Employee''  
	SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''  
	SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''  
	SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'' 
	set @sqlQuery = @sqlQuery + '' INNER JOIN #TempProcessedData ON TA_Tbl_Employee.Employee_Id =#TempProcessedData.EmpAutoId''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id'' 
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_ShiftSettings on Ta_Tbl_ShiftSettings.CompanyId = '''''' + cast(@CompanyId as nvarchar(11)) + ''''''''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''  
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''  
	set @sqlQuery1 = @sqlQuery1 + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0)''  
	if(@UserGroupName<>''SuperAdmin'')  
	begin  
		SET @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''  
	end  
	if not(@EmployeeName='''')  
	begin  
		set @sqlQuery1 = @sqlQuery1 + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''  
	end  
	if not (@empId='''')  
	begin  
		set @sqlQuery1 = @sqlQuery1 + '' And (TA_Tbl_Employee.Employee_code_id= '''''' + @empId + '''''' )''  
	end  
	If Not (@EmpSwipeCard = '''')    
	Begin    
		Set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
	End   
	if(@employeeCategory<>0)  
	begin  
		set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))   
	end  
	if(@employeeType<>0)  
	begin  
		set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))   
	end  
	if(@shift<>0)  
	begin  
		Set @sqlQuery1 = @sqlQuery1 + '' And #TempProcessedData.shift_id= ''+  cast (@shift as nvarchar(50))  
	end 
	exec(@sqlQuery + @sqlQuery1) 
	print(@sqlQuery + @sqlQuery1) 
	select * from #TempFinal order by Employee_Code_Id,EmpName,ClockDate asc  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpType  
	drop table #EmpCategory  
	drop table #LevelRights   
	drop table #TempProcessedData
	drop table #TempEmployee
	drop table #EmpSwipeCardNo
	drop table #TempFinal
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ScriptEntryForDiscrepancy]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ScriptEntryForDiscrepancy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-------------
CREATE procedure [dbo].[Proc_TA_ScriptEntryForDiscrepancy]
as 
Begin
	declare @YearID as int
	set @YearID = (select YearSettings_Id from Ta_Tbl_Yearsetting where IsActive=1)
---------Out Entry--------------
	insert into Ta_Tbl_ManualTimeEntry (
						ManualTimeEntry_Date,
						ManualTimeEntry_Employee_Id,					
						ManualTimeEntry_OutDate,
						ManualTimeEntry_OutTime,
						ManualTimeEntry_OutPunchType,
						ManualTimeEntry_OutReaderID,
						ManualTimeEntry_Reason,
						Clk_Process,
						ManualTimeEntry_Status,
						YearSettings_Id,
						Isdeleted
				)
	select Convert(varchar(15),getDate(),101) as manualEntryDate,emp.employee_code_id,	
	OutClockDate=
	case 
		when right (shf.Shift_StartTime,2)=''PM'' then
			case 
				when right (shf.Shift_EndTime,2)=''AM'' then  dateadd(day,1,clk.clk_date)
			end
		else 
			clk.clk_indate
	end,
	shf.Shift_EndTime as OutClockTime,
	''Out'' as PunchType,
	dbo.Func_TA_SelectMatchingDevice(clk.clk_IndeviceID , ''Out'') as OutDevice,
	''Script Entry''  as Remarks,
	''N''as Clk_ProcessFlag,
	''Approved'' as status,
	@YearID as YearSettingID,
	0 as Isdeleted
	from ta_tbl_clockdetails clk
	inner join ta_tbl_processeddata pd 
		on clk.clk_empid= pd.employee_code_id    and
		   clk_date = pd.date
	inner join ta_tbl_shift shf 
			on shf.shift_Id=pd.shift_ID
	inner join ta_tbl_employee emp
		on emp.swipecardno = clk.clk_empId
	where clk.clk_Outdate is null and clk.clk_Outtime is null
	and
		clk.clk_Indate is not null and clk.clk_Intime is not null
	and
		emp.isdeleted=0 and emp.employee_status=1
	and
		datediff(mi,clk.clk_intime, cast(shf.shift_starttime as datetime))<=30
	and
		datediff(mi,clk.clk_intime, cast(shf.shift_starttime as datetime))>=-30
---------Out Entry--------------
insert into Ta_Tbl_ManualTimeEntry (
						ManualTimeEntry_Date,
						ManualTimeEntry_Employee_Id,					
						ManualTimeEntry_InDate,
						ManualTimeEntry_InTime,
						ManualTimeEntry_InPunchType,
						ManualTimeEntry_InReaderID,
						ManualTimeEntry_Reason,
						Clk_Process,
						ManualTimeEntry_Status,
						YearSettings_Id,
						Isdeleted
				)
	select 
		Convert(varchar(15),getDate(),101) as manualEntryDate,emp.employee_code_id,	
		clk.clk_date as InClockDate,
		shf.Shift_StartTime as InClockTime,
		''In'' as PunchType,
		dbo.Func_TA_SelectMatchingDevice(clk.clk_OutdeviceID , ''In'') as InDevice,
		''Script Entry''  as Remarks,
		''N''as Clk_ProcessFlag,
		''Approved'' as status,
		@YearID as YearSettingID,
		0 as Isdeleted
		from ta_tbl_clockdetails clk
		inner join ta_tbl_processeddata pd 
			on clk.clk_empid= pd.employee_code_id    and
			   clk_date = pd.date
		inner join ta_tbl_shift shf 
				on shf.shift_Id=pd.shift_ID
		inner join ta_tbl_employee emp
			on emp.swipecardno = clk.clk_empId
		where clk.clk_Outdate is not null and clk.clk_Outtime is not null
		and
			clk.clk_Indate is null and clk.clk_Intime is null
		and
			emp.isdeleted=0 and emp.employee_status=1
		and
			datediff(mi,
				cast (convert (varchar(15),clk.clk_outdate,101) + '' ''+  convert(varchar(8),clk.clk_outtime ,108) as datetime), 		
				cast (convert (varchar(15),clk.clk_outdate,101) + '' ''+  convert(varchar(8),shf.Shift_EndTime ,108) as datetime)	
			)<=30
		and
			datediff(mi,
				cast (convert (varchar(15),clk.clk_outdate,101) + '' ''+  convert(varchar(8),clk.clk_outtime ,108) as datetime), 
				cast (convert (varchar(15),clk.clk_outdate,101) + '' ''+  convert(varchar(8),shf.Shift_EndTime ,108) as datetime)
			)>=-30
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWeeklyWorkHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
exec Proc_TA_RptWeeklyWorkHours @FromDate=N''01/Nov/2016'',@ToDate=N''20/Nov/2016'',@EmployeeName=N'''',
@LevelID=N''0'',@EmployeeID=N'''',@EmployeeCategory=0,@EmployeeType=0,@DesignationID=0,@Gender=N''BOTH'',@UserGroupName=N''SuperAdmin'',
@GradeLevel=N''0'',@EmpSwipeCard=N'''',@ParentId=0,@shift=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours] 
@EmployeeId varchar(50),
@FromDate datetime, 
@ToDate datetime, 
@EmployeeName varchar(50), 
@LevelID varchar(8000),
@employeeCategory int,
@employeeType int,
@DesignationID INT,
@Gender VARCHAR(10),
@UserGroupName varchar(200),
@GradeLevel varchar(20), 
@EmpSwipeCard varchar(20),
@ParentId int,
@shift int = 0,
@EmpAutoID int
AS 
BEGIN 
	set nocount on
	IF(@EmployeeId IS NOT NULL AND @EmployeeId <> '''')
	BEGIN
		CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
		INSERT INTO #EMPLOYEEID
		SELECT * FROM SPLITUPEMPLOYEECODE(@EmployeeId)
	END 
	IF(@EmployeeName IS NOT NULL AND @EmployeeName <> '''')
	BEGIN
		CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
		INSERT INTO #EMPLOYEENAME
		SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EmployeeName,'','')
	END	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID 
	insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType 
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory 
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @ToDate,@EmployeeId 
		declare @GetLevelID as int
		set @GetLevelID=(select top 1 LevelId from #EmpLevel)
		declare @Highlevel int
		DECLARE @childID INT 
		 ;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
			WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
		SELECT TOP 1 @Highlevel=p.id
		FROM ParentLevel r
		inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
		ORDER BY lvl DESC
		if(@Highlevel is null)
		begin
			set @Highlevel=@GetLevelID
		end
	create table #TempAttendanceDetails
	(
		SlNo int identity(1,1),
		WeekOrder nvarchar(50),
		WeekOrder1 nvarchar(50),
		WeekDayOrder int,
		Day nvarchar(50),
		FNAttendanceCode nvarchar(15),
		ANAttendanceCode nvarchar(15),
		Employee_Code_Id nvarchar(10),
		EmployeeName nvarchar(250),
		LevelName nvarchar(250),
		Designation nvarchar(250),
		Date datetime,
		InTime varchar(20),
		OutTime varchar(20),
		HrsWork varchar(20),
		TotalMinsWorked decimal(18,1),
		Shift_ShortName varchar(100),
		ShiftId int,
		shift_TotalWorkingHours nvarchar(50),
		Shift_FirstHalfWorkingHours nvarchar(50),
		Shift_SecondHalfWorkingHours nvarchar(50),
		LateIn varchar(50),
		LateInMins decimal(18,2),
		EarlyExit varchar(50),
		EarlyOutMins decimal(18,2),
		LessHrs nvarchar(50),
		DefinedWorkHours decimal(18,1), 
		CategoryId int, 
		CategoryName NVARCHAR(50), 
		MinWorkHours decimal(18,1),
		DailyWorkHrs nvarchar(18)
	)
	declare @sqlQuery_Detailed as nvarchar(MAX) 
	set @sqlQuery_Detailed='''' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ''select 
	case when DATEPART(dw,pd.date)= ss.CumulativeWeekStartDay then 
	convert(varchar(10),DATEPART(WEEK,pd.date)) 
	end ,
	convert(varchar(10),DATEPART(YEAR,date))+ ''''Week''''+convert(varchar(10),DATEPART(WEEK,date)) as ''''WeekOrder'''',DATEPART(dw,date)''''WeekDayOrder'''',DATENAME(DW,date) as ''''Day'''',''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ''pd.fnAttendanceCode + case when Status is null then '''''''' else ''''(BL)'''' end as FNAttendanceCode,pd.anAttendanceCode + case when Status is null then '''''''' else ''''(BL)'''' end as ANAttendanceCode,''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ''e.Employee_Code_Id,isnull(e.Employee_FirstName,'''''''') + space(1) + isnull(e.Employee_LastName,'''''''') as EmployeeName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as LevelName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ''pd.date as Date,CASE when isnull(pd.InTime,''''00:00'''')=''''00:00'''' then ''''-'''' else pd.InTime end as ''''InTime'''',CASE when isnull(pd.OutTime,''''00:00'''')=''''00:00'''' then ''''-'''' else pd.OutTime end as ''''OutTime'''',ISNULL(pd.HrsWork, ''''-'''') as ''''HrsWork'''', ((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))) as TotalMinsWorked ,(shf.Shift_ShortName + '''' ('''' + shf.Shift_StartTime + '''' - '''' + shf.Shift_EndTime + '''')'''') as Shift_ShortName,''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + ''pd.shift_id as ShiftID,shf.shift_TotalWorkingHours,Shift_FirstHalfWorkingHours ,Shift_SecondHalfWorkingHours,pd.LateIn,pd.LateInMins,pd.EarlyOut as EarlyExit,pd.EarlyOutMins,pd.HrsLess,TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours,TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,DATEDIFF(MI, ''''00:00'''',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''''.5'''', ''''.3''''), 0.0)), ''''.'''', '''':'''')) as ''''MinWorkHours'''',TA_Tbl_Category.WeekDay_WorkHrs''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' from Ta_Tbl_Employee e ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id'' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID '' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeCategory on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id''
	Set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner JOIN TA_Tbl_ShiftSettings SS ON ss.CompanyID='' + cast(@Highlevel as nvarchar(2)) + ''''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpType on #EmpType.EffectiveDate=ET.EffectiveDate and #EmpType.employeeid=ET.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
	IF NOT (@EmployeeId = '''') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner Join #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=#EmpLevel.Employee_Code_Id ''
	END
	IF NOT (@EmployeeName = '''') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner Join #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=#EmpLevel.Employee_Code_Id ''
	END
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and ((pd.date >= CONVERT(DATETIME, '''''' + cast(@FromDate as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@ToDate as nvarchar(11)) + '''''', 102)))
	'' 
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel 
	end 
	IF(@GENDER<>''BOTH'') 
	BEGIN 
		SET @sqlQuery_Detailed = @sqlQuery_Detailed + '' AND e.Gender = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' '' 
	END 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery_Detailed = @sqlQuery_Detailed + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If Not (@EmpSwipeCard = '''') 
	Begin 
		Set @sqlQuery_Detailed = @sqlQuery_Detailed + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' '' 
	End
	if(@shift<>0) 
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And pd.Shift_Id='' + cast (@shift as nvarchar(50)) 
	end 
	if(@employeeCategory<>0)
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And ET.TypeId = '' + cast(@employeeType as nvarchar(8)) 
	end
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' and 
	(
	DATEPART(dw,pd.date) between 
	(
	case when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	when ss.CumulativeWeekStartDay<CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	when ss.CumulativeWeekStartDay=CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	end
	) 
	and 
	(
	case 
	when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then 7
	when ss.CumulativeWeekStartDay<CumulativeWeekEndDay then CumulativeWeekEndDay
	when ss.CumulativeWeekStartDay=CumulativeWeekEndDay then ss.CumulativeWeekStartDay
	end
	)
	or 
	DATEPART(dw,pd.date) between 
	(
	case when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then 1
	end
	) 
	and 
	(
	case 
	when ss.CumulativeWeekStartDay>CumulativeWeekEndDay then CumulativeWeekEndDay
	end
	)
	)
	'' 
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' order by e.Employee_FirstName,cast(pd.date as datetime)'' 
	-- exec(@sqlQuery_Detailed) 
	insert into #TempAttendanceDetails 
	exec(@sqlQuery_Detailed) 
	Create table #temptesting(id int identity(1,1),Weekdate int,Startdate datetime)
	insert into #temptesting
	select distinct WeekOrder,Date from #TempAttendanceDetails where WeekOrder is not null 
	Declare @count int
	Declare @StartDate datetime
	Declare @WeekNumber varchar(20)
	Declare @PreviousWeekNumber varchar(20)
	Declare @NextDate datetime
	set @count=(select COUNT(*) from #TempTesting) 
	Declare @i int
	set @i=1
	while @count>=@i
	begin 
		set @StartDate=(select convert(datetime,Startdate) from #TempTesting where id=@i) 
		set @WeekNumber=(select Weekdate from #TempTesting where id=@i) 
		if @i=1
		begin
			set @PreviousWeekNumber=@WeekNumber-1 
		end
		set @NextDate=(select convert(datetime,Startdate) from #TempTesting where id=@i+1) 
		if @StartDate is not null and @NextDate is not null
		begin 
			update #TempAttendanceDetails set WeekOrder=@WeekNumber where convert(datetime,Date) between
			@StartDate and dateadd(d,-1,@NextDate)
		end
		else
		begin 
			update #TempAttendanceDetails set WeekOrder=@WeekNumber from #TempAttendanceDetails where Date>=@StartDate
		end
		set @i=@i+1
	end
	update #TempAttendanceDetails set WeekOrder=@PreviousWeekNumber from #TempAttendanceDetails where WeekOrder is null
	SELECT
	WeekOrder,
	WeekDayOrder,
	Day,
	FNAttendanceCode,
	ANAttendanceCode,
	Employee_Code_Id,
	EmployeeName,
	LevelName,
	Designation,
	Date,
	InTime,
	OutTime,
	HrsWork as WorkingHours,
	TotalMinsWorked,
	Shift_ShortName,
	ShiftId,
	shift_TotalWorkingHours,
	Shift_FirstHalfWorkingHours ,
	Shift_SecondHalfWorkingHours ,
	LateIn,
	LateInMins,
	EarlyExit,
	EarlyOutMins,
	LessHrs,
	DefinedWorkHours, 
	CategoryId, 
	CategoryName, 
	MinWorkHours
	FROM #TempAttendanceDetails where ShiftId<>-1 and (fnAttendanceCode in (''Present'',''Absent'') or anAttendanceCode in (''Present'',''Absent''))
	create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),DurWorkHrs decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATETIME)
	INSERT INTO #TempAttendanceSummary
	SELECT
	TA.Employee_Code_Id,
	TA.EmployeeName,
	TA.DefinedWorkHours,
	0,
	SUM(
	((
	(CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'')) THEN 1 ELSE 0.0 END)*
	((substring(isnull(TA.Shift_FirstHalfWorkingHours,''00:00''),0,3)*60) + (substring(isnull(ta.Shift_FirstHalfWorkingHours,''00:00''),4,2)))
	+ 
	(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'')) THEN 1 ELSE 0.0 END)*
	((substring(isnull(TA.Shift_SecondHalfWorkingHours,''00:00''),0,3)*60) + (substring(isnull(ta.Shift_SecondHalfWorkingHours,''00:00''),4,2)))
	))
	),
	0,
	SUM(CAST(TA.totalMinsWorked AS INT)),0,TA.CategoryName,CAST(MAX(TA.[Date]) AS DATETIME)
	FROM #TempAttendanceDetails TA
	INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
	GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName,C.WeekDay_WorkHrs
	update #TempAttendanceSummary set SupposedToWorkHours = DefinedWorkHours - (Convert(Decimal(18,1),Convert( Varchar(10), (cast(HoursToDeduct as INT)/60))+ ''.'' + Convert( Varchar(10),(cast(HoursToDeduct as INT)%60))))
	update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	select 
	Employee_Code_Id,
	EmployeeName,
	DefinedWorkHours,
	HoursToDeduct,
	SupposedToWorkHours,
	CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN ''0'' + cast((ActualWorkHours/60) as varchar(25)) ELSE cast((ActualWorkHours/60) as varchar(25)) END + '':'' + CASE WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN ''0'' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
	CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN ''0'' + cast((LessHours/60) as varchar(25)) ELSE cast((LessHours/60) as varchar(25)) END + '':'' + CASE WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN ''0'' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
	CategoryName,
	(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END + ''.'' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid
	from #TempAttendanceSummary
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWagesReport]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWagesReport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Senthil
-- Create date: 21-Apr-08
-- Description:	Wages Report
-- Proc_TA_RptWagesReport ''26'','''','''','''','''',''''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptWagesReport]
	@MonthClosureID as nvarchar(5),
	@EmployeeId nvarchar(100),	
	@EmployeeName nvarchar(50),
	@EmpCategory nvarchar(50),
	@EmpType nvarchar(50),
	@LevelID nvarchar(1000)		
AS
BEGIN
	Declare @ToDate as DateTime
	set @ToDate = (select MonthClosure_EndDate from ta_tbl_monthclosure where MonthClosure_ID=@MonthClosureID)
	declare @sqlQuery as varchar(7000)
	set @sqlQuery = ''select TA_Tbl_Title.TitleName,TA_Tbl_PayrollProcessDetails.PayrollProcess_Id, TA_Tbl_PayrollProcessDetails.MonthClosure_Id, Ta_Tbl_Employee.Employee_Code_ID,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as EmployeeName,''
--	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.MonthlyWages + Isnull(TA_Tbl_PayrollProcessDetails.DA,0) as MonthlyWages,TA_Tbl_PayrollProcessDetails.WorkingDays,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.MonthlyWages ,TA_Tbl_PayrollProcessDetails.WorkingDays,''
--	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.AbsentDays + TA_Tbl_PayrollProcessDetails.LeaveDays as AbsentDays , TA_Tbl_PayrollProcessDetails.PaidHolidays, ''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.LeaveDays as AbsentDays , TA_Tbl_PayrollProcessDetails.PaidHolidays, ''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.PresentDays as WorkedDays, TA_Tbl_PayrollProcessDetails.Wages,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.OverTimeDays,TA_Tbl_PayrollProcessDetails.OverTimeWages,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.Incentive,TA_Tbl_PayrollProcessDetails.GrossWages,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.PF, TA_Tbl_PayrollProcessDetails.ESI,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.Mess,TA_Tbl_PayrollProcessDetails.OtherDeductions,''
	set @sqlQuery = @sqlQuery + '' isnull(TA_Tbl_PayrollProcessDetails.Mess,0) + isnull(TA_Tbl_PayrollProcessDetails.OtherDeductions,0) + isnull(TA_Tbl_PayrollProcessDetails.PF,0) + isnull(TA_Tbl_PayrollProcessDetails.ESI,0) as TotalDeduction,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_PayrollProcessDetails.NetWages,''
	set @sqlQuery = @sqlQuery + '' RoundUp = Case (Cast(TA_Tbl_PayrollProcessDetails.NetWages as int)%10) when 0 Then TA_Tbl_PayrollProcessDetails.NetWages Else (TA_Tbl_PayrollProcessDetails.NetWages + (10 - (Cast (TA_Tbl_PayrollProcessDetails.NetWages as int) %10))) End''
	set @sqlQuery = @sqlQuery + '' from Ta_Tbl_employee inner join ta_tbl_payrollprocessDetails on Ta_Tbl_Employee.SwipeCardNo=ta_tbl_payrollprocessDetails.Employee_ID''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on Ta_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' where (TA_Tbl_Employee.Employee_Status = 1) AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0)''
    set @sqlQuery = @sqlQuery + '' And (ta_tbl_payrollprocessDetails.MonthClosure_ID='' + @MonthClosureID + '')''
	set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ta_tbl_Employee.Employee_Id and  EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
    set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
	if not(@EmpCategory='''' or @EmpCategory=''0'')
	begin
		set @sqlQuery = @sqlQuery + ''and TA_Tbl_Employee.EmpCategory ='''''' + @EmpCategory + '''''' ''
	end
	if not(@EmpType='''' or @EmpType=''0'')
	begin
		set @sqlQuery = @sqlQuery + ''and TA_Tbl_Employee.EmpType ='''''' + @EmpType + '''''' ''
	end
	if not(@EmployeeName='''' or @EmployeeName=''0'')
	begin
		set @sqlQuery = @sqlQuery + ''and TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''' ''
	end	
	if not (@EmployeeId='''' or @EmployeeId=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
	end
	if not(@LevelID='''' or @LevelID=''0'')
	begin			
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_EmployeeLevel.levelId IN ('' + @LevelID  + ''))''
	end	
	exec(@sqlQuery)	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalWorkingDays]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalWorkingDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	08-Jan-2014
Descriptions	:	Procedure created for newly genrated report for taking working days count
	Proc_TA_RptTotalWorkingDays '''',''905'',''2014/01/01'',''2014/01/22'',''0'',0,0,''SuperAdmin'',''0'','''',0,0,''Both''
	or FNAttendanceCode=''''RH''''
*/
CREATE proc [dbo].[Proc_TA_RptTotalWorkingDays]
(
@employeeName nvarchar(max),
@EmployeeId varchar(max),
@FromDate datetime,
@ToDate datetime,
@levelId varchar(8000),
@employeeCategory int,
@employeeType int,
@UserGroupName varchar(250),
@GradeLevel varchar(20),
@EmpSwipeCard varchar(20),
@ParentId int,
@DesignationID int,
@Gender varchar(10),
@EmpAutoID int
)
as
begin
	--Declaring variables 
	SET NOCOUNT ON;
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	declare @LeaveType as nvarchar(max)
	SELECT @LeaveType =COALESCE(@LeaveType + '','''''','''''''')+LeaveType+'''''''' FROM TA_Tbl_LeaveType 
	set @LeaveType=COALESCE(@LeaveType + '','''''','''''''')+''Comp Off''+''''''''+'',''''BL''+''''''''+'',''''LOP''+''''''''+'',''''RH''+''''''''
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
	if(@EmployeeId is not null and @EmployeeId <> '''')
	BEGIN
		CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
		INSERT INTO #EmployeeID
		SELECT * from SplitupEmployeeCode(@EmployeeId)
	end
	if(@EmployeeName is not null and @EmployeeName <> '''')
	BEGIN
		CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
		INSERT INTO #EmployeeName
		SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
	end
	if(@Gender<>''Both'')  
	begin  
		set @sqlCommon = @sqlCommon + '' and Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
	end	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId 
	where emp.Isdeleted=0 ''
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +'' group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
	BEGIN  
		SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
	End
	If Not (@EmployeeName = '''')  
	BEGIN  
		SET @sqlEmpLevel = @sqlEmpLevel + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=ELevel.SwipeCardNo ''
	End
	Execute(@sqlEmpLevel)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @ToDate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @ToDate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @ToDate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--Created temp table for getting below dynamic query
	create table #TempTotalWorkingDays
	(
		Employee_Code_Id nvarchar(50),
		UserName nvarchar(50),
		Weekday float,
		WeeklyOff float,
		Holiday float,
		Leave float,
		LeaveType nvarchar(10),
		name nvarchar(500)
	)
	set @sqlQuery=''select E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''' '''') + SPACE(1) + ISNULL(E.Employee_LastName, '''' '''') AS UserName, ''
	--Weekday count
	set @sqlQuery=@sqlQuery+''isnull(
	sum(case
	when  FNAttendanceCode=''''Present'''' and ANAttendanceCode=''''Present'''' and LPD.WeekDays=1 then 1 
	when FNAttendanceCode=''''Present'''' and ANAttendanceCode<>''''Present'''' and LPD.WeekDays=1 then 0.5
	when FNAttendanceCode<>''''Present'''' and ANAttendanceCode=''''Present'''' and LPD.WeekDays=1 then 0.5
	when FNAttendanceCode<>''''Present'''' and ANAttendanceCode<>''''Present'''' and LPD.WeekDays=1 then 0
	end),0) as Weekday,''
	--Weekly Off Count
	set @sqlQuery=@sqlQuery+''isnull(sum(case
	when  FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' and LPD.WeekOff=1 then 1
	when FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode<>''''Weekly Off'''' and LPD.WeekOff=1 then 0.5
	when FNAttendanceCode<>''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' and LPD.WeekOff=1 then 0.5
	when FNAttendanceCode<>''''Weekly Off'''' and ANAttendanceCode<>''''Weekly Off'''' and LPD.WeekOff=1 then 0
	end ),0) as WeeklyOff,''
	--Holiday count
	set @sqlQuery=@sqlQuery+''isnull(sum(case
	when  (FNAttendanceCode=''''Holiday'''' ) and (ANAttendanceCode=''''Holiday'''' ) and LPD.Holidays=1 then 1
	when (FNAttendanceCode=''''Holiday'''' ) and (ANAttendanceCode<>''''Holiday'''')  and LPD.Holidays=1 then 0.5
	when (FNAttendanceCode<>''''Holiday'''' ) and (ANAttendanceCode=''''Holiday'''' )  and LPD.Holidays=1 then 0.5
	when (FNAttendanceCode<>''''Holiday'''' ) and (ANAttendanceCode<>''''Holiday'''')  and LPD.Holidays=1 then 0
	end ),0) as Holiday,''
	--Leave Count
	set @sqlQuery=@sqlQuery+''isnull(sum(case
	when  (FNAttendanceCode in (''+cast(@LeaveType as nvarchar(max))+'') ) and (ANAttendanceCode in (''+cast(@LeaveType as nvarchar(max))+'') )  and LPD.Leave=1 then 1
	when (FNAttendanceCode in (''+cast(@LeaveType as nvarchar(max))+'') ) and (ANAttendanceCode not in (''+cast(@LeaveType as nvarchar(max))+'') )  and LPD.Leave=1 then 0.5
	when (FNAttendanceCode not in (''+cast(@LeaveType as nvarchar(max))+'') ) and (ANAttendanceCode in (''+cast(@LeaveType as nvarchar(max))+'') )   and LPD.Leave=1 then 0.5
	when (FNAttendanceCode not in (''+cast(@LeaveType as nvarchar(max))+'') ) and (ANAttendanceCode not in (''+cast(@LeaveType as nvarchar(max))+'') )  and LPD.Leave=1 then 0
	end ),0) as Leave,''	
	--Leave type and joins tables
	set @sqlQuery=@sqlQuery+''LT.LeaveType,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name from TA_Tbl_ProcessedData P inner join TA_Tbl_Employee E on E.Employee_Code_Id=P.Employee_Code_Id
	inner join TA_Tbl_Emp_LeavePolicy EL on EL.EmployeeId=E.Employee_Id  
	and  CONVERT(DATETIME, '''''' +cast( @FromDate as nvarchar(50))   + '''''', 102) between EL.fromDate and EL.ToDate
	and  CONVERT(DATETIME, '''''' +cast( @ToDate as nvarchar(50))   + '''''', 102) between EL.FromDate and EL.ToDate
	inner join TA_Tbl_Emp_LeavePolicyDetails ELP on ELP.Emp_LeavePolicyId=EL.Emp_LeavePolicyId inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELP.Policy_ID
	inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=LP.Policy_Id and ELP.LeaveType_Id=LPD.LeaveType_Id inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=LPD.LeaveType_Id and LT.CountFactor=1''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' WHERE ((E.Employee_Status = 1)	
	or(E.Employee_Status = 0 and  convert(varchar(11), E.InActiveDate,102)	>= 	convert(varchar(11),P.Date,102)))	AND (E.Isdeleted = 0) AND (E.report_exclude = 0)''
	set @sqlQuery = @sqlQuery + '' and ProcessFlag=1 and Date between  CONVERT(DATETIME, '''''' +cast( @FromDate as nvarchar(50))   + '''''', 102) and  CONVERT(DATETIME, '''''' +cast( @ToDate as nvarchar(50))   + '''''', 102)  '' 
	--Checking whether the gender is both or others (Male,Female)
	if(@UserGroupName<>''SuperAdmin'')
	begin
		set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	--Checking whether the employee code is empty or not  
	set @sqlQuery=@sqlQuery+'' group by E.Employee_Code_Id,E.Employee_FirstName,E.Employee_LastName,LT.LeaveType,Ta_Tbl_levelDetails.name ''
	insert into #TempTotalWorkingDays
	exec(@sqlQuery);
	select Employee_Code_Id,UserName,Weekday,WeeklyOff,Holiday,LeaveType,Leave,(Weekday+WeeklyOff+Holiday+Leave) as TotalWorkingDays,name from #TempTotalWorkingDays
	--group by Employee_Code_Id,UserName,Weekday,WeeklyOff,Holiday,Leave
	drop table #TempTotalWorkingDays
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmployeeIds
	--drop table #EmpPay
	drop table #LevelRights	 
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalHoursList]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalHoursList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- exec Proc_TA_RptTotalHoursList '''',''01/Apr/2014'',''02/May/2014'',''id1'','''',''107'',0,0,''SuperAdmin'',''0'',0,''0'',107
-- exec Proc_TA_RptTotalHoursList @MinWorkHours='''',@FromDate=''01/Apr/2012'',@ToDate=''16/Apr/2013'',@EmployeeID='''',@EmployeeName='''',@LevelID=''3,5,11'',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=''SuperAdmin'',@GradeLevel=''3'',@EmpAutoId=0,@BreakLate = 0
CREATE  PROCEDURE [dbo].[Proc_TA_RptTotalHoursList]
(
@MinWorkHours as varchar(10),
@FromDate VarChar(50), 
@ToDate VarChar(50), 
@EmployeeID VarChar(50), 
@EmployeeName varchar(50),
@LevelID VarChar(1000),
@EmployeeCategory int,
@EmployeeType int,
@UserGroupName varchar(20),
@GradeLevel varchar(20),
@EmpAutoId bigint,
--@LateHrs VARCHAR(5) = ''00:00'',
@BreakLate VARCHAR(1) = ''1'',
@ParentID INT,
--Added newly for PRODUCT Migration by Manjula.P on 06-May-2014
@DesignationID int,
@Gender varchar(10)
)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Adding parentid levelrights by Manjula.P on 30-Apr-2014. -DONT DELETE IT
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level Indexes
--Index was grouped by manikandan.R on 08-05-2014
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	Declare @SelectSQL As Varchar(MAX)
	Set @EmployeeName = @EmployeeName + ''%''
	Set @SelectSQL = '' ''  
--Covert Minimum hours into Minutes
		declare @pos as int
		set @pos = charindex('':'',@MinWorkHours)
		declare @TotalMin as int
		set @TotalMin = substring(@MinWorkHours,0,@pos)*60 + substring(@MinWorkHours,@pos+1,2)
	Set @SelectSQL = @SelectSQL + '' SELECT Process_Rec_ID, CardNo, [Employee Name], Designation, [Level Name], [Date], Shift_StartTime, InTime, OutTime,LateBy, LateInMins, BreakOut, BreakIn, ''
	--Set @SelectSQL = @SelectSQL + '' CAST(CAST((CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''''00:00'''', [LunchHrs]))/ 60 AS VARCHAR)) < 0 THEN ''''0'''' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''''00:00'''', [LunchHrs]))/ 60 AS VARCHAR)) END) + '''':'''' + (CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''''00:00'''', [LunchHrs]))% 60 AS VARCHAR)) < 0 THEN ''''0'''' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(BreakLate,[LunchHrs]),''''00:00'''', [LunchHrs]))% 60 AS VARCHAR)) END) AS TIME) AS VARCHAR(5)) AS BreakLate, ''
	Set @SelectSQL = @SelectSQL + ''  BreakLate,BreakLateMins, ''
	--Set @SelectSQL = @SelectSQL + '' (CASE WHEN BreakLateMins != 0 THEN BreakLateMins 
	--									  WHEN (BreakLateMins - ([LunchHrsMins])) < 0 THEN 0 
	--                                      ELSE (BreakLateMins - ([LunchHrsMins])) END) AS BreakLateMins, ''
	--Set @SelectSQL = @SelectSQL + '' (CASE WHEN BreakLateMins = 0 THEN TotalLate ELSE (CAST(CAST((CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''''00:00'''', [LunchHrs]))/ 60 AS VARCHAR)) < 0 THEN ''''0'''' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''''00:00'''', [LunchHrs]))/ 60 AS VARCHAR)) END) + '''':'''' + (CASE WHEN (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''''00:00'''', [LunchHrs]))% 60 AS VARCHAR)) < 0 THEN ''''0'''' ELSE (CAST(DATEDIFF(MI, [LunchHrs], REPLACE(ISNULL(TotalLate,[LunchHrs]),''''00:00'''', [LunchHrs]))% 60 AS VARCHAR)) END) AS TIME) AS VARCHAR(5))) END) AS TotalLate, ''
	Set @SelectSQL = @SelectSQL + '' (CASE WHEN BreakLateMins = 0 THEN TotalLate ELSE cast(cast(DATEADD(mi, ((TotalLateMins)), ''''00:00'''') as time) as varchar(5)) end) AS TotalLate, ''
	Set @SelectSQL = @SelectSQL + ''  TotalLateMins ''
	Set @SelectSQL = @SelectSQL + '' FROM ( ''
	Set @SelectSQL = @SelectSQL + '' SELECT PD.Process_Rec_ID,ED.SwipeCardNo AS CardNo, ''
	Set @SelectSQL = @SelectSQL + '' ED.Employee_FirstName + ''
	Set @SelectSQL = @SelectSQL + '' case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) else '''' '''' end + ED.Employee_LastName AS ''''Employee Name'''', ''
   	Set @SelectSQL = @SelectSQL + '' T.TitleName AS Designation, ''
	set @SelectSQL = @SelectSQL + '' Ta_Tbl_levelDetails.name AS ''''Level Name'''',''	   	
	Set @SelectSQL = @SelectSQL + '' Date AS Date,Sft.Shift_StartTime,InTime,OutTime,LateIn as LateBy,LateInMins,Right(PD.BreakOut,11) as BreakOut,Right(PD.BreakIn,11) as BreakIn, PD.BreakLate,PD.BreakLateMins, PD.TotalLate, PD.TotalLateMins, PD.LateEntryReason, ''
	Set @SelectSQL = @SelectSQL + '' CAST(CAST(DATEADD(MI, DATEDIFF(MI, CAST(CAST(DATEADD(MI, DATEDIFF(MI, Sft.Shift_BreakStartTime2, Sft.Shift_BreakEndTime2), ''''00:00'''') AS TIME) AS VARCHAR(5)) ,ISNULL(SS.MaxLunchHours, ''''00:40'''')), ''''00:00'''') AS TIME) AS VARCHAR(5)) AS [LunchHrs], ''
	Set @SelectSQL = @SelectSQL + '' DATEDIFF(MI, ISNULL(SS.MaxLunchHours, ''''00:40''''),CAST(CAST(DATEADD(MI, DATEDIFF(MI, Sft.Shift_BreakStartTime2, Sft.Shift_BreakEndTime2), ''''00:00'''') AS TIME) AS VARCHAR(5)) ) AS [LunchHrsMins] ''
	Set @SelectSQL = @SelectSQL + '' FROM TA_Tbl_Employee ED ''
	--Set @SelectSQL = @SelectSQL + '' CONVERT(varchar,Date ,106) AS Date,Sft.Shift_StartTime,InTime,LateIn as LateBy,LateInMins,Right(PD.BreakOut,11) as BreakOut,Right(PD.BreakIn,11) as BreakIn,PD.BreakLate,PD.BreakLateMins,PD.TotalLate,PD.TotalLateMins,PD.LateEntryReason FROM TA_Tbl_Employee ED ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON ED.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON ED.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER JOIN dbo.TA_Tbl_Title T ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = T.TitleId ''
	set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId ''		
	Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_ProcessedData PD ON ED.Employee_code_Id = PD.Employee_Code_Id '' 
	Set @SelectSQL = @SelectSQL + '' INNER JOIN TA_Tbl_Shift Sft ON PD.shift_id = Sft.Shift_Id ''
    Set @SelectSQL = @SelectSQL + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON Sft.Level_Id = SS.CompanyId ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
   --set @sqlQuery = @sqlQuery + '' And (#EmpLevel.levelId In ('' + @LevelID + ''))''  
	set @SelectSQL = @SelectSQL + '' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId ''
	Set @SelectSQL = @SelectSQL + '' Where (ED.Isdeleted = 0) AND (ED.Employee_Code_Id <> ''''18000000'''') and  ED.report_exclude=0 and ED.employee_status=1 ''
	Set @SelectSQL = @SelectSQL + '' AND PD.TotalLate <> ''''00.00'''' And PD.TotalLate <> ''''00:00'''' And PD.TotalLate is not null And PD.TotalLate <> ''''0'''' ''
	Set @SelectSQL = @SelectSQL + '' AND (PD.FNAttendanceCode =''''Present'''' or PD.ANAttendanceCode=''''Present'''') ''
--	set @SelectSQL = @SelectSQL + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
--	set @SelectSQL = @SelectSQL + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
--	set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
--  set @SelectSQL = @SelectSQL + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''	    
	IF (@MinWorkHours <> '''')
	BEGIN
		SET @SelectSQL = @SelectSQL + '' and PD.TotalLateMins >= '' + cast(@TotalMin as nvarchar(8))  
	END
	IF(@UserGroupName <> ''SuperAdmin'')
	BEGIN
		SET @SelectSQL = @SelectSQL + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel 
		--+ '' AND (ED.Reporting_To ='''''' + cast(@EmpAutoId as varchar(30)) + '''''' or ED.Leave_Sanc_Authority='''''' + cast(@EmpAutoId as varchar(30)) +'''''') ''
	END
	IF NOT (@EmployeeId = '''' Or @EmployeeId = ''0'')
	BEGIN
		SET @SelectSQL = @SelectSQL + '' And ED.Employee_code_Id = '''''' + @EmployeeID + '''''' ''
	END
	IF NOT (@EmployeeName = '''') 
	BEGIN
		SET @SelectSQL = @SelectSQL + '' and (ED.Employee_FirstName + isnull(ED.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName + ''%'' as nvarchar(100)) + '''''') ''
	END
	IF NOT (@EmployeeCategory = 0)
	BEGIN
		SET @SelectSQL = @SelectSQL + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))
	END
	IF NOT (@EmployeeType = 0)
	BEGIN
		SET @SelectSQL = @SelectSQL + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))
	END
	--Adding Designationid and Gender filters as like from product : By Manjula.P on 06-May-2014
	if(isnull(@DesignationID,0)<>0)
		begin
			set @SelectSQL = @SelectSQL + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end
	if(isnull(@Gender,''Both'')<>''Both'')
		begin
			set @SelectSQL = @SelectSQL + '' and ED.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
	end
	--**************************************************************
	IF (@FromDate <> '''')
	BEGIN
		SET @SelectSQL = @SelectSQL + '' And PD.Date >= '''''' + @FromDate + '''''' ''
	END
	IF (@ToDate <> '''')
	BEGIN
		SET @SelectSQL = @SelectSQL + '' And PD.Date <= '''''' + @ToDate + '''''' ''
	END
	--IF(@EmpAutoId = 0)
	--BEGIN 
	--	IF  NOT (@LevelID ='''' OR @LevelID = ''0'')  
	--	BEGIN
	--	   SET @SelectSQL = @SelectSQL + '' And (#EmpLevel.levelId In ('' + @LevelID + '')) ''  
	--	END
	--END
	IF(@EmpAutoId > 0)
    BEGIN
		SET @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
    END
	SET @SelectSQL = @SelectSQL + '' ) Tbl ''
	--SET @SelectSQL = (CASE WHEN @BreakLate = ''1'' THEN @SelectSQL + '' WHERE (CASE WHEN (BreakLateMins - [LunchHrsMins]) < 0 THEN 0 ELSE (BreakLateMins - [LunchHrsMins]) END) != 0 '' ELSE @SelectSQL END)
		SET @SelectSQL = (CASE WHEN @BreakLate = ''1'' THEN @SelectSQL + '' WHERE (CASE WHEN (BreakLateMins) > 0 THEN 1 ELSE 0 END) != 0 '' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs != ''00:00'' OR @LateHrs != ''00:00'' THEN @SelectSQL + '' WHERE '' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs = ''00:00'' THEN @SelectSQL ELSE @SelectSQL + '' ((CAST(CAST(DATEADD(MI,DATEDIFF(MI, BreakOut, BreakIn),''''00:00'''') AS TIME) AS VARCHAR(5)))) >= '''''' + @BreakLateHrs + '''''''' END)
	--set @SelectSQL = (CASE WHEN @BreakLateHrs != ''00:00'' AND @LateHrs != ''00:00'' THEN @SelectSQL + '' AND '' ELSE @SelectSQL END)
	--set @SelectSQL = (CASE WHEN @LateHrs = ''00:00'' THEN @SelectSQL ELSE (@SelectSQL + '' LateBy >= '''''' + @LateHrs + '''''''') END)
	SET @SelectSQL = @SelectSQL + '' order by Date , Intime''
	EXEC(@SelectSQL)
	DROP TABLE #EmployeeIds
	drop table #LevelRights
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTotalDaysWorked]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTotalDaysWorked]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_RptTotalDaysWorked ''07/01/2010'',''12/30/2011'','''',''0'','''',''0'',''0'','''',''SuperAdmin'',''0'','''',0,0,''Both'',''ExcludingOD''
-- Proc_TA_RptTotalDaysWorked ''2015/04/01'',''2015/04/30'',''manikandan,'',''0'','''',''0'',''0'','''',''SuperAdmin'',''0'','''',0,0,''Both'',''IncludingOD''
CREATE   PROCEDURE [dbo].[Proc_TA_RptTotalDaysWorked] 
(
    @fromDat datetime,
	@ToDat datetime,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@NoOfDays int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@TotalDays varchar(50),
	@EmpAutoID int
)
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Shift_Id int,Attendance nvarchar(20),TotalDays numeric(18, 1),ANAttendanceCode nvarchar(15),FNAttendanceCode nvarchar(15),HRSWORK nvarchar(25))
--#TempProcessedData Indexes
/****** Object:  Index [IDX_Employee_Code_Id]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
(
	[Employee_Code_Id] ASC
) ON [PRIMARY]
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
		Declare @sqlEmpLevel nvarchar(4000)
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@EmployeeId,@employeeCategory
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end	
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
	where SwipeCardNo is not null
	--select * from #TempEmployee
	 Declare @sqlTempProcessedData varchar(8000)
Declare @sqlTempProcessedData1 varchar(8000)
set @sqlTempProcessedData=	
	''insert into #TempProcessedData select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id,TA_Tbl_ProcessedData.InTime,TA_Tbl_ProcessedData.OutTime,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Attendance,TA_Tbl_ProcessedData.TotalDays,TA_Tbl_ProcessedData.ANAttendanceCode,TA_Tbl_ProcessedData.FNAttendanceCode,TA_Tbl_ProcessedData.HRSWORK 
	from TA_Tbl_ProcessedData 
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=TA_Tbl_ProcessedData.Employee_Code_Id
    where (dbo.TA_Tbl_ProcessedData.Date >= CONVERT(DATETIME,''''''+cast(@fromDat as nvarchar(50))+'''''', 102))  
	AND (dbo.TA_Tbl_ProcessedData.Date <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102)) 
	AND TA_Tbl_ProcessedData.attendance=''''Present''''''
	--select * from #TempProcessedData
	Execute(@sqlTempProcessedData)	
	create table #Tempfinal(Employee_Id nvarchar(15),empName nvarchar(150),BranchName nvarchar(250),Designation nvarchar(250),[Total Days Worked1] decimal(18,1),[Total Days Worked] decimal(18,1),Gender varchar(10))
		Begin
		if(@NoOfDays='''' or @NoOfDays=0)
		set @NoOfDays=1
		End
		declare @sqlQuery as varchar(8000)
		declare @sqlQuery1 as varchar(8000)
		set @sqlQuery=''''
		set @sqlQuery1 = ''''
		set @sqlQuery = ''insert into #Tempfinal select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,sum(pd.TotalDays) as "Total Days Worked1"  '' 
		set @sqlQuery = @sqlQuery + '' ,''''Total Days Worked'''' = sum( CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays end else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),e.Gender''
		set @sqlQuery = @sqlQuery + '' from Ta_Tbl_Employee e inner join #TempProcessedData pd on e.Employee_ID=pd.EmpAutoId''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''
		SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId'' 
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
		--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		--set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''
		--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	    --set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	    --set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	    --set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
		--set @sqlQuery = @sqlQuery + '' inner JOIN dbo.TA_Tbl_EmployeePay ON e.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId ''
		--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		--set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	    set @sqlQuery = @sqlQuery + '' where  (	e.Employee_Status = 1 or 
	(e.Employee_Status = 0 and  convert(varchar(11), e.InActiveDate,102) >= convert(varchar(11),pd.Date,102))) 
	AND (e.Isdeleted = 0) AND (e.report_exclude = 0)'' 
		if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
		--if(@employeeCategory<>0)
		--begin
		--	SET @sqlQuery1 = @sqlQuery1 + '' And #EmpCategory.CategoryId = '' +cast(@employeeCategory as nvarchar(8)) 
		--end
		--if(@employeeType<>0)
		--begin
		--	set @sqlQuery1 = @sqlQuery1 + '' And #EmpType.TypeId = '' +cast(@employeeType as nvarchar(8))
		--end
		--If Not (@EmpSwipeCard = '''')  
		-- Begin  
		--	  Set @sqlQuery1 = @sqlQuery1 + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		-- End
		-- if(@DesignationID<>0)
		--	begin
		--	   set @sqlQuery1 = @sqlQuery1 + '' and EDesig.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		--	end	
		if(@Gender<>''Both'')
			begin
			   set @sqlQuery1 = @sqlQuery1 + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
			end	
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		set @sqlQuery1 = @sqlQuery1 + '' Group by pd.Employee_Code_Id,e.Employee_Code_Id,e.Employee_FirstName,e.Employee_LastName,TA_Tbl_LevelDetails.name,T.TitleName,e.Gender ''
		set @sqlQuery1 = @sqlQuery1 + '' having count(pd.attendance)>= '''''' + cast(@NoOfDays as nvarchar(10)) +  '''''' order by e.Employee_FirstName,TA_Tbl_LevelDetails.name,T.TitleName ASC''	
	exec(@sqlQuery+@sqlQuery1)
	if(@TotalDays = ''IncludingOD'')
	BEGIN
	   select Employee_Id,empName,BranchName,Designation,Gender,[Total Days Worked],[Total Days Worked1] from #Tempfinal
	END
	else if(@TotalDays = ''ExcludingOD'')
	BEGIN
	  create table #Temp_OD 
	  (
		Employee_Code_Id nvarchar(15),
		ManualTimeEntry_InDate datetime,
		ManualTimeEntry_InTime varchar(15),
		ManualTimeentry_OutDate datetime,
		ManualtimeEntry_OutTime varchar(15),
		Shift_FirstHalf_StartTime varchar(15),
		Shift_FirstHalf_Endtime varchar(15),
		Shift_SecondHalf_StartTime varchar(15),
		Shift_SecondHalf_EndTime varchar(15),
		TotalDays decimal(18,1)
	 )
	 set @sqlTempProcessedData1=	
	 ''insert into #Temp_OD select E.Employee_Code_Id,MTE.ManualTimeEntry_InDate,MTE.ManualTimeEntry_InTime,
	 MTE.ManualTimeentry_OutDate,MTE.ManualtimeEntry_OutTime,S.Shift_FirstHalf_StartTime,
	 S.Shift_FirstHalf_Endtime,S.Shift_SecondHalf_StartTime,S.Shift_SecondHalf_EndTime,
	 case [dbo].[Func_TA_OnDuty](pd.date,pd.fnAttendanceCode,e.Employee_Code_Id,''''FN'''',S.Shift_StartTime,S.Shift_SecondHalf_StartTime,S.Shift_Endtime,E.isFlexible,S.Shift_id,pd.HRSWORK)
	 when '''' (On Duty) '''' then 0.5 else 0 end +
	 case [dbo].[Func_TA_OnDuty](pd.date,pd.anAttendanceCode,e.Employee_Code_Id,''''AN'''',S.Shift_StartTime,S.Shift_SecondHalf_StartTime,S.Shift_Endtime,E.isFlexible,S.Shift_id,pd.HRSWORK)
	 when '''' (On Duty) '''' then 0.5 else 0 end
	 from TA_Tbl_ManualTimeEntry MTE
	 inner join TA_Tbl_Employee E  on E.Employee_Code_Id = MTE.ManualTimeEntry_Employee_Id
	 inner join #Tempfinal on #Tempfinal.Employee_Id = E.Employee_Code_Id
	 inner join #TempProcessedData PD on PD.Employee_Code_Id = E.SwipeCardNo and PD.Date = MTE.ManualTimeEntry_InDate
	 inner join TA_Tbl_Shift S on S.Shift_Id = PD.Shift_Id
	 where IsOnDuty=1 and MTE.ManualTimeEntry_Status=''''Approved''''''
	 Execute(@sqlTempProcessedData1)
	 update #Tempfinal set #Tempfinal.[Total Days Worked] = (#Tempfinal.[Total Days Worked] - A.TotalDays)
	 from (select Employee_Code_Id,sum(TotalDays) as TotalDays from #Temp_OD 
     group by employee_Code_Id) as A
     inner join #Tempfinal on A.Employee_Code_Id = #Tempfinal.Employee_Id
     select * from #Tempfinal
     drop table #Temp_OD
	END   
--Remove the temporary tables here   
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
drop table #TempEmployee
drop table #Tempfinal
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTimeSheet]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTimeSheet]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Karthikeyan
-- Create date: <2020-Jun-04>
-- Description:	<Description,,>
--
/*
Proc_TA_RptTimeSheet @fromDat=''2020-07-01 00:00:00'',@ToDat=''2020-07-27 00:00:00'',
@EmployeeName=N'''',@LevelID=N''0,1'',@EmployeeId=N''4'',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',
@GradeLevel=N''0'',@ParentId=1,@DesignationID=0,@Gender=N''Both'',@EmpAutoId=0,@IsExport=0,@status=''All''
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RptTimeSheet] 
	-- Add the parameters for the stored procedure here
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @EmployeeName varchar(max),  
	 @LevelID varchar(8000), 
	 @EmployeeId varchar(max),
	 @employeeCategory int,
	 @employeeType int,
	 @UserGroupName varchar(20),
	 @GradeLevel varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @EmpAutoId bigint,	 
	 @IsExport int=0,
	 @status varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @dateFormat as int
	set @dateFormat =(Select DateFormat from Func_TA_GetDateTimeFormat())
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end

	declare @sqlQuery as varchar(8000)  
	set @sqlQuery='''' 
	
	select 
		[Employee ID]=E.Employee_Code_Id,
		[Employee Name]=E.Employee_FirstName,
		Department=LD.name,
		Designation=D.TitleName,
		CategoryName=C.CategoryName,
		[Shift Date]=ShiftDate,
		[Project Name]=P.Project_Name,
		[Task Name]=PT.TaskName,
		[Task Description]=TP.TaskDescription,
		[Task Hours]=PT.TaskHours,
		[Spent Hours]=case when TP.Status=''Approved'' then TPS.ApprovedHours else  TP.SpentHours end,
		[Approved By]=(select ie.Employee_FirstName from ta_tbl_employee ie where employee_id in(case when TPS.ApprovedBy is null or TPS.ApprovedBy='''' then TP.ApprovedBy1 else TPS.ApprovedBy end)),
		[Approved Date]=case when TPS.ApprovedBy is null or TPS.ApprovedBy='''' then TP.ApprovedDate1 else TPS.ApprovedDate end,
		[Approved By]=
		case when TP.Status=''Forwarded'' then '''' 
			when TP.Status=''Approved'' then  
		(select ie.Employee_FirstName from ta_tbl_employee ie where employee_id in(case when TPS.ApprovedBy is null or TPS.ApprovedBy='''' then  TP.ApprovedBy2 else TPS.ApprovedBy end))
		end,
		[Approved Date]=case when TP.Status=''Forwarded'' then '''' 
			when TP.Status=''Approved'' then
		case when TPS.ApprovedBy is null or TPS.ApprovedBy='''' then TP.ApprovedDate2 else TPS.ApprovedDate end
		end,
		[Task Status]=TP.Status,
		TPS.ApprovedHours
	FROM TA_Tbl_Project P
	Inner join TA_tbl_ProjectTaskList PT on P.Project_Id=PT.ProjectID
	Inner join Ta_tbl_TaskProgressDetails  TP on (TP.TaskID=PT.TaskID and TP.ProjectID=PT.ProjectID)
	LEFT outer join ta_tbl_taskprogressStatus TPS on TP.TaskDetailID=TPS.TaskDetailID
	inner join TA_Tbl_Employee E on E.Employee_Id=TP.TaskSubmittedBy
	inner join #EmpLevel EL on E.Employee_Id=EL.EmployeeId
	Inner join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId
	inner join #LevelRights LR on LR.LevelId=LD.id
	inner join #EmpCategory EC on E.Employee_Id=EC.EmployeeId
	inner join #EmpType ET on E.Employee_Id=ET.EmployeeId
	inner join #EmpDesignation ED on E.Employee_Id=ED.EmployeeId
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId
	inner join TA_Tbl_Title D on D.TitleId=ED.DesignationId
	where E.Isdeleted=0 and E.Report_Exclude=0
	and (TP.ShiftDate>=@fromDat and TP.ShiftDate<=@ToDat)
	and (@status=''All'' or TP.Status=@status) 
	order by E.Employee_Code_Id,convert(datetime,ShiftDate),TP.Status
	
	
	select 
		[Employee ID]=E.Employee_Code_Id,
		[Employee Name]=E.Employee_FirstName,
		Department=LD.name,
		Designation=D.TitleName,
		CategoryName=C.CategoryName,
		[Shift Date]=ShiftDate,
		[Project Name]=P.Project_Name,
		[Spent Hours]=
		case when LEN(convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))/60))=1 then 
		''0''+convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))/60)
		else convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))/60)
		end +'':''+
		case when LEN(convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))%60))=1 then 
		''0''+convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))%60)
		else 
		convert(varchar(20),sum(dbo.ConvertHoursToMinites(isnull(TP.SpentHours,''00:00'')))%60)
		end,
		[Approved By1]=case when TPS.ApprovedBy is null or TPS.ApprovedBy='''' then TP.ApprovedBy1 else TPS.ApprovedBy end,
		[Approved Date]=TP.ApprovedDate1,
		[Approved By1]=TP.ApprovedBy2,
		[Approved Date]=TP.ApprovedDate2,
		[Task Status]=TP.Status		
	FROM TA_Tbl_Project P
	Inner join TA_tbl_ProjectTaskList PT on P.Project_Id=PT.ProjectID
	Inner join Ta_tbl_TaskProgressDetails  TP on (TP.TaskID=PT.TaskID and TP.ProjectID=PT.ProjectID)
	LEFT outer join ta_tbl_taskprogressStatus TPS on TP.TaskDetailID=TPS.TaskDetailID
	inner join TA_Tbl_Employee E on E.Employee_Id=TP.TaskSubmittedBy
	inner join #EmpLevel EL on E.Employee_Id=EL.EmployeeId
	Inner join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId
	inner join #LevelRights LR on LR.LevelId=LD.id
	inner join #EmpCategory EC on E.Employee_Id=EC.EmployeeId
	inner join #EmpType ET on E.Employee_Id=ET.EmployeeId
	inner join #EmpDesignation ED on E.Employee_Id=ED.EmployeeId
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId
	inner join TA_Tbl_Title D on D.TitleId=ED.DesignationId
	where E.Isdeleted=0 and E.Report_Exclude=0
	and (TP.ShiftDate>=@fromDat and TP.ShiftDate<=@ToDat)
	and (@status=''All'' or TP.Status=@status) 
	group by E.Employee_Code_Id,E.Employee_FirstName,LD.name,D.TitleName,C.CategoryName,P.Project_Name,TP.ApprovedBy1,
	TP.ApprovedDate1,TP.ApprovedBy2,TP.ApprovedDate2,TP.Status,convert(datetime,ShiftDate),ApprovedBy
	order by E.Employee_Code_Id,convert(datetime,ShiftDate),TP.Status
	
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptTempShiftAllocation]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
Procedure Name : Proc_TA_RptTempShiftAllocation  ''2015/06/01'',''2015/06/30'','''','''','''','''','''',''SuperAdmin'','''','''',0,0,''Both'',1
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07 
Modified by : sashma
Modified on : 12-May-2011    */  
CREATE PROCEDURE [dbo].[Proc_TA_RptTempShiftAllocation]  
(
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @Religion int,
 @EmpAutoId bigint
)	
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	--create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) AS LevelId
--Select * from #LevelRights
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level INSERT in Temporary table
	--INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	--SELECT max(el.EffectiveDate) AS EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	--where emp.Isdeleted=0 GROUP by EmployeeId) ELevel
	--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	--AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpLevel select * from [Func_TA_EmpLevel] (@ToDat,@EmpSwipeCard)
	--Select * from #EmpLevel
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	SELECT max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type INSERT in Temporary table
	INSERT INTO #EmpType SELECT EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	SELECT max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category INSERT in Temporary table
	INSERT INTO #EmpCategory SELECT EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	SELECT max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)   and ECategory.CategoryId is not null
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery AS varchar(8000)  
	SET @sqlQuery=''''  
	SET @sqlQuery = ''SELECT e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') AS Employee_FirstName,e.employee_code_id AS employee_id,ts.Year,ts.Month,ts.Day1Shift,ts.Day2Shift,ts.Day3Shift,ts.Day4Shift,ts.Day5Shift,ts.Day6Shift,ts.Day7Shift,ts.Day8Shift,ts.Day9Shift,ts.Day10Shift,ts.Day11Shift,ts.Day12Shift,ts.Day13Shift,ts.Day14Shift,ts.Day15Shift,ts.Day16Shift,ts.Day17Shift,ts.Day18Shift,ts.Day19Shift,ts.Day20Shift,ts.Day21Shift,ts.Day22Shift,ts.Day23Shift,ts.Day24Shift,ts.Day25Shift,ts.Day26Shift,ts.Day27Shift,ts.Day28Shift,ts.Day29Shift,ts.Day30Shift,ts.Day31Shift,ts.emp_id,ts.TimeStamp,ts.DateShift,TA_Tbl_Title.TitleName AS TitleName,e.Gender from TA_Tbl_TemporaryShiftAllocation ts inner join TA_Tbl_Employee e on e.Employee_Id=ts.EmployeeId ''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''	
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_code_Id ''
		End
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id ''
		End
	SET @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.employee_Status=1 and e.Report_exclude=0 ''  
	SET @sqlQuery=@sqlQuery + '' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat AS nvarchar(20)) + '''''', 102)) AS nvarchar(20))+''''/''''+ cast(1 AS nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat AS nvarchar(20)) +'''''', 102 ))AS nvarchar(10)),102) ''
	SET @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat AS nvarchar(20)) + '''''', 102)) AS nvarchar(20))+''''/''''+ cast(1 AS nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat AS nvarchar(20)) + '''''', 102 ))AS nvarchar(10)),102)''
	--if not(@EmployeeName='''')  
	--	BEGIN  
	--		SET @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName + '''' '''' +  isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' AS nvarchar(100)) + '''''')''
	--	END
	If Not (@EmpSwipeCard = '''')  
		BEGIN  
			Set @sqlQuery = @sqlQuery + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	--if not(@EmployeeId='''')  
	--	BEGIN  
	--		SET @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId AS nvarchar(100)) + '''''')''  
	--	END  
	if(@Gender<>''Both'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender AS nvarchar(8)) + '''''' ''
		END	
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID AS nvarchar(8))
		END	
	if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType AS nvarchar(8))
		END		
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpCategory.CategoryId = '' + cast(@employeeCategory AS nvarchar(8))
		END
	IF(@Religion!=1)
		BEGIN
			SET @sqlQuery=@sqlQuery+'' AND e.Religion = ''+cast(@Religion as varchar(50))+'' ''
		END
		if(@isReportingto > 0)
	  BEGIN
	     set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
	  END
	SET @sqlQuery = @sqlQuery + '' order by e.employee_code_id,e.Employee_FirstName,ts.Year,ts.Month''   
	exec(@sqlQuery)  
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectAddlWeekOffDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectAddlWeekOffDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_SelectAddlWeekOffDetails ''A'',0,''SuperAdmin'',0,''All'',''All''
CREATE   PROCEDURE [dbo].[Proc_TA_SelectAddlWeekOffDetails]
(
 @TYPE CHAR(1)='''', 
 @AddlWeekOffID INT,
 @userGroupName nvarchar(25),
 @ParentId int=0,
 @WeekOffDay varchar(100)=''All'',
 @WeekOffWeek varchar(100)=''All''
 )
AS
DECLARE @Isdeleted INT
SET @Isdeleted=0
declare @Query nvarchar(max);
declare @WhereQuery nvarchar(500)
declare @OrderByQuery nvarchar(max)
set @Query='''';
set @WhereQuery='''';
declare @LevelIds as varchar(250)
create table #Temp
(
LevelId varchar(250)
)
insert into #Temp
select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
select @LevelIds=  COALESCE(@LevelIds + '','', '''') + LevelId FROM #Temp;
BEGIN
IF (@TYPE=''A'')
	IF(@userGroupName=''SuperAdmin'')
	begin		
		--iF @PARENTiD is not passing for Search
		if(@ParentId<=0)
		begin
			set @Query='' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day +'''' - ''''+ A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,
			A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week		
			FROM TA_Tbl_Additional_WeeklyOff A	
			inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
			LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.LevelId_Id=L.id ''	
			set @WhereQuery='' where AL.LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''','''')) '' 
			set @OrderByQuery='' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
			A.Addl_WeekOff_Week ''
		end
		--If @ParentId is passing			
		else
		begin
			set @Query='' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day +'''' - ''''+ A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,
			A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
			FROM TA_Tbl_Additional_WeeklyOff A	
			inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
			LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id ''
			set @WhereQuery='' where AL.LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''','''')) ''
			set @OrderByQuery='' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted,  A.Addl_WeekOff_Day,
			A.Addl_WeekOff_Week '' 
		end		
	end	    		
	ELSE
		BEGIN
			if(@ParentId<=0)
			begin
				set @Query=''SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day + '''' - '''' + A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,
				A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
				FROM TA_Tbl_Additional_WeeklyOff A	
				inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
				LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.levelId_Id=L.id ''		
	    		set @WhereQuery='' WHERE A.Isdeleted=''+cast(@Isdeleted as varchar(100))+'' and AL.LevelId in (select Value from dbo.Split(''''''+cast(
	    		@LevelIds as varchar(100))+'''''','''','''')) ''
	    		set @OrderByQuery='' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
	    		A.Addl_WeekOff_Week ''
	    	end
	    	else
	    		begin
	    		set @Query=''SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day + '''' - '''' + A.Addl_WeekOff_Week as AddWeekday_week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,
	    		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week				
				FROM TA_Tbl_Additional_WeeklyOff A	
				inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
				LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id ''		
	    		set @WhereQuery= '' WHERE A.Isdeleted=''+cast(@Isdeleted as varchar(100))+'' and AL.LevelId in (select Value from dbo.Split(''''''+cast(
	    		@LevelIds as varchar(100))+'''''','''','''')) ''
	    		set @OrderByQuery='' group by A.Addl_WeeklyOff_Id, A.Addl_WeekOff_Day,A.Addl_WeekOff_Week, A.IsDeleted, A.Addl_WeekOff_Day,
	    		A.Addl_WeekOff_Week ''
	    		end
		END
ELSE IF (@TYPE=''P'')
	BEGIN
		set @Query='' SELECT * FROM TA_Tbl_Additional_WeeklyOff ''
		set @WhereQuery='' WHERE Addl_WeeklyOff_Id=''+cast(@AddlWeekOffID as varchar(100))+'' AND IsDeleted=''+cast(@Isdeleted as varchar(100))+'' ''
	END
ELSE If (@TYPE=''I'')
	BEGIN
	if(@ParentId<=-0)
	begin
		set @Query='' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day,A.Addl_WeekOff_Week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,L.Name, L.id AS LevelId,
		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week			
		FROM TA_Tbl_Additional_WeeklyOff A
		inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
		LEFT OUTER JOIN TA_Tbl_levelDetails L ON A.levelId_Id=L.id ''
		set @WhereQuery='' WHERE Addl_WeeklyOff_Id=''+cast(@AddlWeekOffID as varchar(100))+'' ''
	end
	else
	begin
		set @Query='' SELECT A.Addl_WeeklyOff_Id,A.Addl_WeekOff_Day,A.Addl_WeekOff_Week,case when A.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted,L.Name, L.id AS LevelId,
		A.Addl_WeekOff_Day ,A.Addl_WeekOff_Week			
		FROM TA_Tbl_Additional_WeeklyOff A
		inner join TA_Tbl_Additional_WeeklyOff_Levels AL on AL.Addl_WeeklyOff_Id=A.Addl_WeeklyOff_Id
		LEFT OUTER JOIN TA_Tbl_levelDetails L ON AL.LevelId=L.id ''
		set @WhereQuery='' WHERE A.Addl_WeeklyOff_Id=''+cast(@AddlWeekOffID as varchar(100))+'' and L.id=''+cast(@ParentId as varchar(100))+'' ''
	end
	END
	--Checking wher condition query
	if(@WeekOffDay<>''All'')
		begin
			if(@WhereQuery!='''')
			begin
				set @WhereQuery=@WhereQuery + '' and A.Addl_WeekOff_Day=''''''+cast(@WeekOffDay as nvarchar(500))+'''''' ''
			end
			else
			begin
				set @WhereQuery=@WhereQuery + '' where A.Addl_WeekOff_Day=''''''+cast(@WeekOffDay as nvarchar(500))+'''''' ''
			end
		end
		if(@WeekOffWeek<>''All'')
		begin
			if(@WhereQuery!='''')
			begin
				set @WhereQuery=@WhereQuery + '' and A.Addl_WeekOff_Week=''''''+cast(@WeekOffWeek as nvarchar(500))+'''''' ''
			end
			else
			begin
				set @WhereQuery=@WhereQuery + '' where A.Addl_WeekOff_Week=''''''+cast(@WeekOffWeek as nvarchar(500))+'''''' ''
			end
		end
	SET @Query=@Query+@WhereQuery+@OrderByQuery;
	EXEC (@Query);	
	DROP TABLE #Temp
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptYearClosure]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptYearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptYearClosure  '''',4,''1'','''',0,0,''SuperAdmin'',''0'','''',4,0,''Both''
Tables  : TA_Tbl_Employee, TA_Tbl_YearClosure 
Created By : Prabakaran  
Created on : 15-Oct-07    
Modified by : sashma
Modified on : 12-May-2011 
-- Modified By : Gopinath
-- Modified Date : 19-Dec-2013& 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
-- Description: Sql Query Optimization 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_RptYearClosure]  
(  
 @EmployeeName varchar(max),  
 @LevelID varchar(8000),
 @Year_SettingID varchar(20),
 @EmployeeId varchar(max),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10),
 @EmpAutoId bigint
)		
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @toDate datetime
	set @toDate=GETDATE()
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @toDate,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @toDate,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @toDate,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @toDate,@EmployeeId	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
			if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end	
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''')  as Designation,ys.StartMonth + space(1) + cast(ys.StartYear as nvarchar(4)) + ''''-'''' +  ys.EndMonth + space(1) + cast(ys.EndYear as nvarchar(4)) as YearSettingYear,lt.LeaveType,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Leave_Taken,yc.Available_Leaves,
    yc.Encashment,e.Gender,yc.LeaveTypeID,e.Employee_Id from Ta_Tbl_Employee e inner join ta_tbl_YearClosure yc  on e.Employee_Id=yc.Employee_Id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation EDesig on EDesig.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''   
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_YearSetting ys ON ys.YearSettings_Id=yc.Year_SettingID''  
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_LeaveType lt ON lt.LeaveType_Id=yc.LeaveTypeID''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End
						If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=e.Employee_code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and lt.Isdeleted=0''  
	--If Not (@EmpSwipeCard = '''')  
	--	Begin  
	--		Set @sqlQuery = @sqlQuery + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	--	End
	--if(@DesignationID<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and EDesig.DesignationId = '' + cast(@DesignationID as nvarchar(8))
	--	end	
	--if not(@EmployeeId='''')  
	--	begin  
	--		set @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id='''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
	--	end
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end  
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	if not(@Year_SettingID='''' or @Year_SettingID=''0'')  
		begin  
			set @sqlQuery = @sqlQuery + '' And (ys.YearSettings_ID In ('' + cast(@Year_SettingID as nvarchar(10)) + ''))''  
		End
	--if(@employeeCategory<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
	--	end
	--if(@employeeType<>0)
	--	begin
	--		set @sqlQuery = @sqlQuery + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
	--	end
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName''   
	Create table #final(Employee_Id nvarchar(200),
		empName nvarchar(200),BranchName nvarchar(200),Designation nvarchar(200),YearSettingYear nvarchar(200),LeaveType nvarchar(20),Carry_PrevYear decimal(18,1),
		Current_Quota decimal(18,1),Borrow_NextYear decimal(18,1),Leave_Taken decimal(18,1),Available_Leaves decimal(18,1),Encashment decimal(18,1),Gender varchar(6),LeaveTypeID int,EmployeeAutoId int)
	insert into #final exec(@sqlQuery) 
	update #final set Available_Leaves=RemainingNoOfLeaves,Leave_Taken=a.numberofdayAvailed from #final 
	inner join(
	Select yc.Employee_Id,(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		,yc.LeaveTypeID,ISNULL(sum(la.NumberOfDays),0.0)as numberofdayAvailed from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id and la.Status<>''Rejected'' and la.IsDeleted=0
		Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,yc.Employee_Id
		)
		as a on #final.EmployeeAutoId=a.Employee_Id and #final.LeaveTypeID =a.LeaveTypeID
select * from #final
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertLeaveApplicationByAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_InsertLeaveApplication  ''5'',''03/17/2008'',''52'',''Leave'',''03/17/2008'',''03/17/2008'',''First Session'',''Second Session'',1.0,''TEst Reason'',0,6,''''
CREATE     PROCEDURE [dbo].[Proc_TA_InsertLeaveApplicationByAdmin]  
(
@leaveApplicationId int,
@EmployeeID int,
@Leave_ApplicationDate datetime,
@LeaveType_id int,
@Type nvarchar(20),
@Leave_FromDate datetime,
@Leave_ToDate datetime,
@Leave_SessionFrom nvarchar(20),
@Leave_SessionTo nvarchar(20),
@NumberOfDays decimal(8,2),
@Reason nvarchar(1050),
@IsBorrow int,
@auEmpId nvarchar(50),
@YearSettings_Id nvarchar(20),
@LeaveStatus nvarchar(30),
@intimationType nvarchar(25),
@CCMail varchar(3000),
@InformTo VARCHAR(MAX)
)  
as  
BEGIN
SET NOCOUNT ON;
IF(@intimationType != ''UP-WI'')
BEGIN
	SET @InformTo = NULL
END
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@Leave_ToDate as nvarchar(50)), 102) and EL.LevelId is not null
declare @Isdeleted bit  
declare @del bit  
set @del=0  
set @Isdeleted=0  
declare @sql nvarchar(2000)
set @sql=''''
set @sql= @sql + ''INSERT INTO TA_Tbl_LeaveApplication(LeaveApplication_Id,Employee_Id,Leave_ApplicationDate,LeaveType_id,Type,Leave_FromDate,Leave_ToDate,Leave_SessionFrom,Leave_SessionTo,NumberOfDays,Status,IsDeleted,IsBorrow,Emp_Id,YearSettings_Id,IntimationType, InformTo)''
		set @sql= @sql + ''VALUES('''''' + cast(@leaveApplicationId as nvarchar(20)) + '''''','''''' + cast(@EmployeeID as nvarchar(20)) + '''''','''''' + cast(@Leave_ApplicationDate as nvarchar(20)) + '''''',''''''
		set @sql= @sql + cast(@LeaveType_id as nvarchar(20)) + '''''',N'''''' + @Type + '''''','''''' + cast(@Leave_FromDate as nvarchar(20))+ '''''',''''''
		set @sql= @sql + cast(@Leave_ToDate as nvarchar(20))+ '''''',N'''''' + @Leave_SessionFrom + '''''',N'''''' + @Leave_SessionTo + '''''','''''' + cast(@NumberOfDays as nvarchar(20)) + '''''',N''''''
		set @sql= @sql + @LeaveStatus + '''''','''''' + cast(@Isdeleted as nvarchar(10)) +  '''''','''''' + cast(@IsBorrow as nvarchar(10)) +  '''''',N'''''' + @auEmpId + '''''',N'''''' + @YearSettings_Id + '''''',N'''''' + @intimationType + '''''', '''''' + ISNULL(@InformTo, '''') + '''''')''
		exec(@sql)
		UPDATE TA_Tbl_LeaveApplication set Reason=t2.Reason
		from TA_Tbl_LeaveApplicationMaster t2
		inner join TA_Tbl_LeaveApplication t1 on t2.LeaveApplication_Id=t1.LeaveApplication_Id
		where t2.LeaveApplication_Id=@leaveApplicationId
        SELECT LA.LeaveApplication_Id, LD.Id AS LevelId FROM TA_Tbl_LeaveApplication LA
        INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = LA.Employee_Id
		INNER JOIN TA_Tbl_LevelDetails LD ON EL.LevelId = LD.id
        INNER JOIN #EmpLevel ON #EmpLevel.EffectiveDate = EL.EffectiveDate and #EmpLevel.employeeid=EL.EmployeeId
        WHERE LA.LeaveApplication_Id = @leaveApplicationId
		--update the processflag
		update Ta_Tbl_ProcessedData set processflag=0
		from Ta_Tbl_LeaveApplication t2
		inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
		inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
		t1.date between t2.Leave_FromDate and t2.Leave_ToDate
		where t2.LeaveApplication_Id=@leaveApplicationId
		declare @intEmployeeId as int
		set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@leaveApplicationId)
		--Update year closure
		update ta_tbl_yearclosure set Leave_Taken=
		(select isnull(sum(NumberOfDays),0.0)
		from Ta_Tbl_LeaveApplication
		inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
		where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
		and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
		and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
		and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status=''Approved''
		and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId
		)	
	--Remove the temporary tables here  
	drop table #EmpLevel
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertImportMasterData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertImportMasterData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================

CREATE PROCEDURE [dbo].[Proc_TA_InsertImportMasterData]
			@Emp_FirstName nvarchar(50)
           ,@Emp_MiddleName  nvarchar(50)
           ,@Emp_LastName  nvarchar(50)
           ,@Father_Name  nvarchar(50)
           ,@Mother_Name  nvarchar(50)
           ,@DateOfBirth   nvarchar(25)
           ,@DateOfBirth_Record  nvarchar(25)
           ,@Blood_Group  nvarchar(5)
           ,@Email_Id  nvarchar(200)
           ,@Contact_Address  nvarchar(500)
           ,@Permanent_Address  nvarchar(500)
           ,@Phone_Number  nvarchar(50)
           ,@Mobile_Number  nvarchar(50)
           ,@Gender  nvarchar(50)
           ,@Marital_Status  nvarchar(50)
           ,@Nationality  nvarchar(50)
           ,@Religion  nvarchar(50)
           ,@Personal_EmailID  nvarchar(100)
           ,@Passport_No  nvarchar(50)
           ,@Passport_ExpiryDate  nvarchar(50)
           ,@Visa_No  nvarchar(50)
           ,@Visa_ExpiryDate  nvarchar(25)
           ,@Employee_Code  nvarchar(50)
           ,@DateOfJoining  nvarchar(25)
           ,@Qualification_joiningtime  nvarchar(50)
           ,@Qualification_Employement  nvarchar(50)
           ,@OutDoorJob  nvarchar(1)
           ,@CompOff_Eligible  nvarchar(1)
           ,@OT_Eligible  nvarchar(1)
           ,@ESI_Eligible  nvarchar(1)
           ,@PF_Eligible  nvarchar(1)
           ,@Report_Exclude  nvarchar(1)
           ,@Employee_Status  nvarchar(1)
           ,@SwipeCardNo  nvarchar(50)
           ,@IsDeleted  nvarchar(1)
           ,@Hostel  nvarchar(1)
           ,@Designation  nvarchar(50)
           ,@Grade  nvarchar(50)
		   ,@GradeNo nvarchar(5)
           ,@EmployeeType  nvarchar(50)
           ,@EmployeeCategory  nvarchar(50)
           ,@BasicSalary  nvarchar(50)
           ,@Level1  nvarchar(50)
           ,@Level2  nvarchar(50)
           ,@Level3  nvarchar(50)
           ,@Level4  nvarchar(50)
           ,@Level5  nvarchar(50)
           ,@Level6  nvarchar(50)
           ,@Level7  nvarchar(50)
           ,@Level8  nvarchar(50)
           ,@Level9  nvarchar(50)
           ,@Level10 nvarchar(50)
AS
BEGIN
IF(@BasicSalary='''' or @BasicSalary=''0'')
BEGIN
	set @BasicSalary=1
END
 IF(@Passport_No='''')
	BEGIN
		set @Passport_ExpiryDate=null
	END
 IF(@Passport_ExpiryDate='''')
 BEGIN
	set @Passport_ExpiryDate=null
 END
	IF(@Visa_No='''')
	BEGIN
	set @Visa_ExpiryDate=null
	END
 IF(@Visa_ExpiryDate='''')
	BEGIN
	set @Visa_ExpiryDate=null
	END
 IF(@DateOfBirth_Record='''')
 BEGIN
	SET @DateOfBirth_Record=NULL
 END

 --adsf
 --asdf

 declare @countDesignation int
 set @countDesignation=(select COUNT(*) from TA_Tbl_Title where TitleName=@Designation)
 IF(@countDesignation<>0)
 begin
	declare @GradeID int
	select @GradeID=GradeID from TA_Tbl_Title where TitleName=@Designation
	select @Grade=Grade_Name from TA_Tbl_Grade where Grade_ID=CONVERT(int,@GradeID)
	select @GradeNo=Grade_Level from TA_Tbl_Grade where Grade_ID=CONVERT(int,@GradeID)
 end
IF(@Employee_Status='''')
BEGIN
SET @Employee_Status=1
END
declare @intEmpCount as int
select @intEmpCount=count(*) from Ta_Tbl_ImportMasterData where Employee_Code=@Employee_Code
if(@intEmpCount=0)
Begin
INSERT INTO [Ta_Tbl_ImportMasterData]
           ([Emp_FirstName]
           ,[Emp_MiddleName]
           ,[Emp_LastName]
           ,[Father_Name]
           ,[Mother_Name]
           ,[DateOfBirth]
           ,[DateOfBirth_Record]
           ,[Blood_Group]
           ,[Email_Id]
           ,[Contact_Address]
           ,[Permanent_Address]
           ,[Phone_Number]
           ,[Mobile_Number]
           ,[Gender]
           ,[Marital_Status]
           ,[Nationality]
           ,[Religion]
           ,[Personal_EmailID]
           ,[Passport_No]
           ,[Passport_ExpiryDate]
           ,[Visa_No]
           ,[Visa_ExpiryDate]
           ,[Employee_Code]
           ,[DateOfJoining]
           ,[Qualification_joiningtime]
           ,[Qualification_Employement]
           ,[OutDoorJob]
           ,[CompOff_Eligible]
           ,[OT_Eligible]
           ,[ESI_Eligible]
           ,[PF_Eligible]
           ,[Report_Exclude]
           ,[Employee_Status]
           ,[SwipeCardNo]
           ,[IsDeleted]
           ,[Hostel]
           ,[Designation]
           ,[Grade]
		   ,[GradeNo]
           ,[EmployeeType]
           ,[EmployeeCategory]
           ,[BasicSalary]
           ,[Level1]
           ,[Level2]
           ,[Level3]
           ,[Level4]
           ,[Level5]
           ,[Level6]
           ,[Level7]
           ,[Level8]
           ,[Level9]
           ,[Level10])
     VALUES
		   (@Emp_FirstName
           ,@Emp_MiddleName
           ,@Emp_LastName
           ,@Father_Name
           ,@Mother_Name
           ,@DateOfBirth
           ,@DateOfBirth_Record
           ,@Blood_Group
           ,@Email_Id
           ,@Contact_Address
           ,@Permanent_Address
           ,@Phone_Number
           ,@Mobile_Number
           ,dbo.Func_TA_ProperCase(@Gender)
           ,@Marital_Status
           ,@Nationality
           ,@Religion
           ,@Personal_EmailID
           ,@Passport_No
           ,@Passport_ExpiryDate
           ,@Visa_No
           ,@Visa_ExpiryDate
           ,@Employee_Code
           ,@DateOfJoining
           ,@Qualification_joiningtime
           ,@Qualification_Employement
           ,CASE @OutDoorJob WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @CompOff_Eligible WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @OT_Eligible WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @ESI_Eligible WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @PF_Eligible WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @Report_Exclude WHEN ''TRUE'' THEN 1 ELSE 0 END
          -- ,CASE @Employee_Status WHEN ''TRUE'' THEN 1 ELSE 0 END employee status not get from user in simple and advanced template so better set as 1
           ,1
		   ,@SwipeCardNo
           ,CASE @IsDeleted WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,CASE @Hostel WHEN ''TRUE'' THEN 1 ELSE 0 END
           ,@Designation
           ,@Grade
		   ,@GradeNo
           ,@EmployeeType
           ,@EmployeeCategory
           ,@BasicSalary
           ,@Level1
           ,@Level2
           ,@Level3
           ,@Level4
           ,@Level5
           ,@Level6
           ,@Level7
           ,@Level8
           ,@Level9
           ,@Level10)
end
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertHoliday]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--    Proc_TA_InsertHoliday ''I'',0,''G'',''02/29/2008'',''02/29/2008'',''test'',35,6
CREATE    PROCEDURE [dbo].[Proc_TA_InsertHoliday] 
(
	@Type char(1),
	@HolidayId int=0,
	@HolidayType char(1),
	@Holiday_FromDate datetime,
	@Holiday_Todate datetime,
	@Holiday_Description nvarchar(255),
	@YearSettings_Id nvarchar(25),
	@Emp_Id nvarchar(25),
	@XMLData xml
)
as
	declare @sql as nvarchar(3000)
	declare @Isdeleted bit
	set @Isdeleted=0
	Declare @LevelId int
	set @LevelId=0
   --Insert Method
	if(@Type=''I'')
		begin
			set @sql = ''INSERT INTO TA_Tbl_Holiday(Holiday_Type,Holiday_FromDate,Holiday_ToDate,Holiday_Description,Isdeleted,YearSettings_Id,Emp_Id,LevelId) VALUES(''''''+ @HolidayType +'''''',''''''+cast(@Holiday_FromDate as nvarchar(25))+'''''',''''''+cast(@Holiday_Todate as nvarchar(25))+'''''',N'''''' + @Holiday_Description + '''''','''''' +cast(@Isdeleted as nvarchar(25))+ '''''',''''''+cast(@YearSettings_Id as nvarchar(25))+'''''',''''''+ cast(@Emp_Id as nvarchar(25)) +'''''',''''''+ cast(@LevelId as nvarchar(10)) +'''''')''  
			exec(@sql)
			DECLARE @Index int
			declare @TempId int	   
			set @TempId= (select @@Identity)
			set @Index = 0 
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO [TA_Tbl_HolidayChildTable]
			select xm.LevelId,@TempId from OPENXML(@Index, ''/DocumentElement/TA_Tbl_Holiday_Levels'')
			with (LevelId int ''LevelId'') as xm
			exec sp_xml_removedocument @Index   
		end
   --Update Mehod
	else if(@Type=''U'')
		begin
			set @sql =''UPDATE TA_Tbl_Holiday SET Holiday_Type='''''' + @HolidayType + '''''',Holiday_FromDate=''''''+cast(@Holiday_FromDate as nvarchar(25))+'''''',Holiday_ToDate='''''' + cast(@Holiday_Todate as nvarchar(25)) + '''''',Holiday_Description=N'''''' + @Holiday_Description + '''''', Emp_Id= '''''' + cast(@Emp_Id as  nvarchar(25)) + '''''', LevelId= '''''' + cast(@LevelId as  nvarchar(10)) + ''''''  WHERE Holiday_Id= '''''' + cast(@HolidayId as  nvarchar(25)) + '''''' ''
			exec(@sql)
			delete from TA_Tbl_HolidayChildTable where Holiday_Id=@HolidayId
			EXEC sp_xml_preparedocument @Index OUTPUT, @XMLdata
			INSERT INTO [TA_Tbl_HolidayChildTable]
			select xm.LevelId,@HolidayId from OPENXML(@Index, ''/DocumentElement/TA_Tbl_Holiday_Levels'')
			with (LevelId int ''LevelId'') as xm
			exec sp_xml_removedocument @Index   
		end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertEmpLeavePolicydetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertEmpLeavePolicydetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Modified Author:R.Manikandan
-- Modified date: <12-July-2019 04:05 PM>
-- Description:	<Insert Employee Leave policy details>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertEmpLeavePolicydetails]
	@EmployeeId INT,
	@EmpLeavepolicyID INT,
	@PolicyID INT,
	@LeaveType_Id INT,
	@No_Of_Days DECIMAL(18,1),
	@auEmpId INT,
	@MaxDays_Month DECIMAL(18,1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql as nvarchar(3000)
	INSERT INTO TA_Tbl_Emp_LeavePolicyDetails (EmpID,Emp_LeavePolicyId,Policy_ID,LeaveType_Id,No_Of_Days,Isdeleted,Emp_Id,MaxDays_Month)
	VALUES (cast(@EmployeeId as nvarchar(25)),cast(@EmpLeavepolicyID as nvarchar(25)),cast(@PolicyID as nvarchar(25)),cast(@LeaveType_Id as nvarchar(25)),cast(@No_Of_Days as nvarchar(25)),0,cast(@auEmpId as nvarchar(25)),@MaxDays_Month)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertDataAfterYearClosure]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertDataAfterYearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_InsertDataAfterYearClosure
Description	:	It is used to insert or update values based on input
Tables used	:	TA_Tbl_YearClosure 
Modified by	:	Prabakaran.P
Modified on	:	15-Feb-08
*/
CREATE   procedure [dbo].[Proc_TA_InsertDataAfterYearClosure]      
(      
	@Year_SettingID INT,      
	@OrgLevelId INT,      
	@Employee_Id INT,      
	@LeaveTypeID INT,      
	@CarryPrevYear_AvailDays FLOAT,      
	@Current_Quota INT, 
	@AvailableLeaves FLOAT,           
	@Emp_ID INT      
)      
AS      
Begin
	declare @count as int
	set @count=(select count(YearClosureId) from TA_Tbl_YearClosure where Year_SettingID=@Year_SettingID AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID)
	if(@count>0)
		BEGIN
			UPDATE TA_Tbl_YearClosure
			SET Carry_PrevYear=@CarryPrevYear_AvailDays,    Current_Quota=@Current_Quota,Available_Leaves=@AvailableLeaves,Emp_ID=@Emp_ID,Time_Stamp=getdate()
			WHERE Year_SettingID=@Year_SettingID AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID 
		END
	else
		BEGIN 
			INSERT INTO TA_Tbl_YearClosure(Year_SettingID ,OrgLevelId  ,Employee_Id  ,LeaveTypeID ,Carry_PrevYear,Current_Quota ,Available_Leaves,Emp_ID   )      
			VALUES (@Year_SettingID,   @OrgLevelId   ,@Employee_Id   ,@LeaveTypeID  ,@CarryPrevYear_AvailDays,    @Current_Quota ,@AvailableLeaves,@Emp_ID     )      
		END
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_HolidayInsert_YearCreation]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_HolidayInsert_YearCreation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Gopinath.K
-- Description:	For Auto insert of Global holiday during new year creation
-- Proc_Ta_HolidayInsert_YearCreation 1,58
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_HolidayInsert_YearCreation]
@OldYearSettingsID int,
@NewYearSettingsID int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @TopHolidayID as int
	Declare @YearDifference as int
	SET @TopHolidayID = ((SELECT IDENT_CURRENT(''ta_tbl_holiday''))+1)
	Select @StartDate = Fromdate, @EndDate = Todate from ta_tbl_yearsetting where YearSettings_ID = @NewYearSettingsID
	SET @YearDifference = (select Datediff(Year,(select Fromdate from ta_tbl_yearsetting where yearsettings_id=@OldYearSettingsID),
						  (select Fromdate from ta_tbl_yearsetting where yearsettings_id=@NewYearSettingsID)))
	CREATE Table #TempHolidayInsert(OLDHoliday_ID int,NewHoliday_ID int identity(1,1) not null,Holiday_Type varchar(5),
	Holiday_FromDate datetime,Holiday_ToDate datetime,Holiday_Description nvarchar(500),
	YearSettings_Id int,OldYearSettings_Id int,Isdeleted int,Emp_Id int,LevelId int)
	DBCC CHECKIDENT (#TempHolidayInsert, RESEED, @TopHolidayID)
	DELETE ta_tbl_holidaysettings where YearSettingID = @NewYearSettingsID
	Delete TA_Tbl_HolidayChildTable where holiday_id in 
	(Select Holiday_ID from ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate)
	Delete ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate
	insert into ta_tbl_holidaysettings (Global_Maxdays,Yearly_Maxdays,YearSettingID)
	Select Global_Maxdays,Yearly_Maxdays,@NewYearSettingsID From ta_tbl_holidaysettings where YearSettingID = @OldYearSettingsID
	insert into ta_tbl_holiday (Holiday_Type,Holiday_FromDate,Holiday_ToDate,Holiday_Description,YearSettings_Id,Isdeleted,Emp_Id,LevelId)
	select Holiday_Type,DATEADD(year,@YearDifference,Holiday_FromDate),DATEADD(year,@YearDifference,Holiday_ToDate),Holiday_Description,@NewYearSettingsID,Isdeleted,Emp_Id,LevelId
	from ta_tbl_holiday where Holiday_Type=''G'' and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID
    Insert into #TempHolidayInsert
	select Holiday_ID,Holiday_Type,DATEADD(year,@YearDifference,Holiday_FromDate),DATEADD(year,@YearDifference,Holiday_ToDate),Holiday_Description,
	@NewYearSettingsID,@OldYearSettingsID,Isdeleted,Emp_Id,LevelId from ta_tbl_holiday where Holiday_Type=''G'' 
	and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID 
    insert into TA_Tbl_HolidayChildTable (Levelid,Holiday_ID)
 	select TA_Tbl_HolidayChildTable.Levelid, #TempHolidayInsert.NewHoliday_ID
	from TA_Tbl_HolidayChildTable 
	inner join #TempHolidayInsert on #TempHolidayInsert.OLDHoliday_ID=TA_Tbl_HolidayChildTable.Holiday_ID
	where TA_Tbl_HolidayChildTable.holiday_id in 
	(Select Holiday_ID from ta_tbl_holiday where Holiday_Type=''G'' and IsDeleted=0 and YearSettings_Id=@OldYearSettingsID)
	and #TempHolidayInsert.YearSettings_Id=@NewYearSettingsID
    Drop Table #TempHolidayInsert
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ImportLeaveData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ImportLeaveData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: 02-July-2019 02:46 PM
-- Description:	Import Leave Data using csv file
/*
Proc_Ta_ImportLeaveData
''<dsLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>01-Jul-2019</FromDate>
    <ToDate>01-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>02-Jul-2019</FromDate>
    <ToDate>02-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>03-Jul-2019</FromDate>
    <ToDate>03-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>04-Jul-2019</FromDate>
    <ToDate>04-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>05-Jul-2019</FromDate>
    <ToDate>05-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>06-Jul-2019</FromDate>
    <ToDate>06-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>07-Jul-2019</FromDate>
    <ToDate>07-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>08-Jul-2019</FromDate>
    <ToDate>08-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>09-Jul-2019</FromDate>
    <ToDate>09-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>10-Jul-2019</FromDate>
    <ToDate>10-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>11-Jul-2019</FromDate>
    <ToDate>11-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
  <dtLeave>
    <Sl.no />
    <Employee_Code_Id>787</Employee_Code_Id>
    <FromDate>12-Jul-2019</FromDate>
    <ToDate>12-Jul-2019</ToDate>
    <LeaveType>LLL</LeaveType>
  </dtLeave>
</dsLeave>'',1,''Superadmin''
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_ImportLeaveData]
	@LeaveData XML = NULL,
	@EmpAutoID bigInt,
	@UserGroup VARCHAR(max)
AS
BEGIN
	Declare @local_LeaveData XML = @LeaveData
	Declare	@local_EmpAutoID bigInt=@EmpAutoID
	Declare @local_UserGroup VARCHAR(max)=@UserGroup
	
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)	
	BEGIN TRY
		BEGIN TRAN ImportLeaveData
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @local_LeaveData	
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_UserGroup,0) AS LEVELID
				
			
			INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 
				GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
			
			create table #TempLeaveApp
			(
				autoid int identity(1,1),
				[Sl.no] NVARCHAR(20), 
				Employee_Code_Id NVARCHAR(20), 
				Fromdate NVARCHAR(20), 
				Todate NVARCHAR(20),
				LeaveType NVARCHAR(3),
				NumberOfDays float,
				Reason NVARCHAR(max),
				EmpAutoID bigint
			)	
					
			INSERT INTO #TempLeaveApp
			SELECT Tbl.*,E.Employee_Id FROM OPENXML (@XMLParams, ''/dsLeave/dtLeave'', 2) WITH 
			(
				[Sl.no] NVARCHAR(20), 
				Employee_Code_Id NVARCHAR(20), 
				FromDate NVARCHAR(20), 
				ToDate NVARCHAR(20), 
				LeaveType NVARCHAR(3),
				NumberOfDays float,				
				Reason NVARCHAR(max) 
			) Tbl			
			LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			AND E.IsDeleted = 0 AND E.Employee_Status = 1
			
			INSERT INTO @ErrorMsg
			SELECT autoid,Employee_Code_Id,'''',1,Fromdate FROM #TempLeaveApp
			
			--select * from #TempLeaveApp
			
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp)
			BEGIN
				SET @ErrMsg = ''There is no record in the file''
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
			END
			IF EXISTS(SELECT EmpAutoID FROM #TempLeaveApp WHERE ISNULL(EmpAutoID, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''This employee is not created in timecheck, please remove it and then try import;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.EmpAutoID, '''') = ''''
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Employee_Code_Id, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Employee Id is missing;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Employee_Code_Id, '''') = ''''
			END			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Fromdate, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''From Date is missing;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(Fromdate,'''')= ''''
			END	
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(Todate, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''To Date is missing;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Todate, '''') = ''''
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE ISNULL(LeaveType, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Leave Type is missing;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.LeaveType, '''') = ''''
			END	
			
			IF EXISTS(SELECT TLA.LeaveType FROM #TempLeaveApp TLA
			Left Outer Join TA_Tbl_LeaveType  LT on TLA.LeaveType=LT.LeaveType
			where LT.LeaveType is null and TLA.LeaveType is not null)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Leave Type is not available. Create the leave type in leave type master;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 				
				Left Outer Join TA_Tbl_LeaveType  LT on tot.LeaveType=LT.LeaveType
				where LT.LeaveType is null and tot.LeaveType is not null
			END
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE LEN(Reason)>1000)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Reason field filled more than 1000 characters;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE LEN(Reason)>1000
			END		
			
			IF EXISTS(SELECT Employee_Code_Id FROM #TempLeaveApp WHERE Fromdate is not null and Todate is not null and Fromdate!='''' and Todate!='''' and Todate<Fromdate)
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Todate should be greater than from date;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Fromdate is not null and Todate is not null and Fromdate!='''' and Todate!='''' and Todate<Fromdate
			END		
			
			IF Exists(
			SELECT autoid FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,fromdate ORDER BY Employee_Code_Id ASC)AS duplicate,
						autoid FROM #TempLeaveApp
			)AS A WHERE duplicate>1)
			BEGIN
				set @alertMsg=''Duplication Record Found;Please find and remove duplicate record in excel file;<br />''				
				UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,fromdate ORDER BY Employee_Code_Id ASC)AS duplicate,
					Employee_Code_Id,autoid FROM #TempLeaveApp
				)AS A on EM.RecordID=a.autoid WHERE a.duplicate>1
				and ISNULL(a.Employee_Code_Id, '''') != ''''
			END
			IF EXISTS(SELECT t.Employee_Code_Id FROM #TempLeaveApp t INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
			LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID=''''))
			BEGIN
				set @alertMsg=''Employee is not available or you are not having an previlege to import leave data for this employee;<br />''				
				UPDATE @ErrorMsg SET Error_Msg=CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN #TempLeaveApp t on EM.RecordID=t.autoid				
				INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID='''')
				and ISNULL(t.Employee_Code_Id, '''') != ''''
			END
			
			IF EXISTS(SELECT Fromdate FROM #TempLeaveApp where Fromdate>(select Todate from TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Apply Leave on available Year settings Days;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Fromdate>(select Todate from TA_Tbl_YearSetting where IsActive=1)
			END			
			
			IF EXISTS(SELECT Fromdate FROM #TempLeaveApp where Todate>(select Todate from TA_Tbl_YearSetting where IsActive=1))
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Apply Leave on available Year settings Days;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp tot on tot.autoid=EM.RecordID 
				WHERE Todate>(select Todate from TA_Tbl_YearSetting where IsActive=1)
			END
			
			IF EXISTS(SELECT LAE.LeaveApplicationId from #TempLeaveApp TLA 
			Inner join TA_Tbl_LeaveApplicationExists LAE on (TLA.EmpAutoID=LAE.Employee_Id and TLA.Fromdate=LAE.Leave_FromDate and TLA.Todate=LAE.Leave_ToDate)
			Inner join TA_Tbl_LeaveApplication LA on (LAE.LeaveApplicationId=LA.LeaveApplication_Id)
			where LA.IsDeleted=0 and LA.Status!=''Rejected'')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Leave is already updated into system for this date;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempLeaveApp TLA on TLA.autoid=EM.RecordID 
				Inner join TA_Tbl_LeaveApplicationExists LAE on (TLA.EmpAutoID=LAE.Employee_Id and TLA.Fromdate=LAE.Leave_FromDate and TLA.Todate=LAE.Leave_ToDate)
				Inner join TA_Tbl_LeaveApplication LA on (LAE.LeaveApplicationId=LA.LeaveApplication_Id)
				where LA.IsDeleted=0 and LA.Status!=''Rejected''
			END			
			IF NOT EXISTS(SELECT [Employee_Id] FROM @ErrorMsg WHERE flag=0)
			BEGIN								
				Declare @TotLeaveRecord int
				select @TotLeaveRecord=COUNT(*) from #TempLeaveApp				
				Declare @start int
				set @start=1				
				while @TotLeaveRecord>=@start
				begin					
					Declare @EmployeeID INT
					Declare @Leave_ApplicationDate DATETIME=null
					set @Leave_ApplicationDate=dbo.DateOnly(getdate())
					Declare @LeaveType_id INT
					
					Declare @Type NVARCHAR(20)
					set @Type=''Leave''
					Declare @Leave_FromDate DATETIME
					Declare @Leave_ToDate DATETIME
					Declare @Leave_SessionFrom NVARCHAR(20)
					set @Leave_SessionFrom=''First half''
					Declare @Leave_SessionTo NVARCHAR(20)
					set @Leave_SessionTo=''Second half''
					Declare @NumberOfDays DECIMAL(8,2)
					--set @NumberOfDays =1
					Declare @Reason NVARCHAR(250)
					Declare @IsBorrow INT
					set @IsBorrow=0
					Declare @auEmpId NVARCHAR(50)
					set @auEmpId=@EmpAutoID
					Declare @YearSettings_Id NVARCHAR(20)
					select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
					Declare @LeaveStatus NVARCHAR(30)
					set @LeaveStatus=''Approved''
					Declare @SuccessiveYear INT
					set @SuccessiveYear=0
					Declare @Intervening char(5)				
					set @Intervening=''''
					declare @Employee_Code_Id varchar(20)
					
					Declare @leaveTypeName varchar(20)
					
					select @NumberOfDays=case when (DATEDIFF(d,Fromdate,Todate)+1)>=NumberOfDays then DATEDIFF(d,Fromdate,Todate)+1 else NumberOfDays end,
						@leaveTypeName=LeaveType,@Employee_Code_Id=Employee_Code_Id,@EmployeeID=EmpAutoID,@Leave_FromDate=Fromdate,@Leave_ToDate=Todate,@Reason=Reason from #TempLeaveApp where autoid=@start
					select @LeaveType_id=LeaveType_Id from TA_Tbl_LeaveType where LeaveType=@leaveTypeName
					
					--select @EmployeeID,@Leave_ApplicationDate,
					--@LeaveType_id,@Type,@Leave_FromDate,@Leave_ToDate,@Leave_SessionFrom ,@Leave_SessionTo ,
					--@NumberOfDays ,@Reason ,@IsBorrow,@auEmpId,@YearSettings_Id,@LeaveStatus ,@SuccessiveYear ,@Intervening
					
					Execute [Proc_TA_InsertLeaveApplication] @EmployeeID,@Leave_ApplicationDate,
					@LeaveType_id,@Type,@Leave_FromDate,@Leave_ToDate,@Leave_SessionFrom ,@Leave_SessionTo ,
					@NumberOfDays ,@Reason ,@IsBorrow,@auEmpId,@YearSettings_Id,@LeaveStatus ,@SuccessiveYear ,@Intervening
					
					update TA_Tbl_ProcessedData set ProcessFlag=0 where Employee_Code_Id=@Employee_Code_Id
					and (Date>=@Leave_FromDate and Date<=@Leave_ToDate)
					
					set @start=@start+1
				end
			END
			ELSE 
			BEGIN
				SELECT	RecordID=RecordID+1,
						Employee_Id, 
						Error_Msg,
						date
				FROM @ErrorMsg where flag=0
			END
		COMMIT TRAN ImportLeaveData
			SELECT ''Msg:DataImportedSuccessfully'' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportLeaveData
		RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
	END CATCH
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_MonthClosure]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_MonthClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_MonthClosure]
(
	@Type CHAR(1)='''',
             @MonthClosureID INT,
             @OrgLevel_Id INT,
	@Month NVARCHAR(15)='''',
	@Year INT=0,
	@FromDate NVARCHAR(15)='''',
	@ToDate NVARCHAR(15)='''',
	@ClosedDate NVARCHAR(15)='''',
             @UserId int,
             @EntryDate NVARCHAR(15),
			 @YearSettingId INT	
)
AS
DECLARE @Isdeleted INT
SET @Isdeleted=0
BEGIN
IF (@Type=''I'')
	BEGIN
		INSERT INTO TA_Tbl_MonthClosure (OrgLevel_Id,MonthClosure_Month,MonthClosure_Year,MonthClosure_StartDate,MonthClosure_EndDate,MonthClosure_ClosingDate,[Emp_Id],Process,[TimeStamp],Isdeleted,YearSettings_Id)
		VALUES (@OrgLevel_Id,@Month,@Year,@FromDate,@ToDate,@ClosedDate,@UserId,''N'',@EntryDate,@Isdeleted, @YearSettingId)
	END
ELSE IF (@Type=''U'')
	BEGIN
		UPDATE TA_Tbl_MonthClosure SET Process = ''P''  WHERE MonthClosure_Id=@MonthClosureID
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSMSLogDetailsForNotification]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetailsForNotification]
	-- Add the parameters for the stored procedure here
	@TemplateName varchar(100),
	@Receivers varchar(250),
	@EmployeeID varchar(50),
	@Status bit,
	@Message varchar(max),	
	@StatusMessage varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @TemplateID int
	select @TemplateID=id from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName and Status=1
    -- Insert statements for procedure here
	Insert into TA_Tbl_SMSLogDetails values(@TemplateID,CONVERT(datetime, CONVERT(varchar(10),getdate(),111)),@Receivers,'''',@Status,@StatusMessage,0,@Message,GETDATE())
	Declare @id int
	set @id=@@IDENTITY
	Insert into TA_Tbl_SMSLogChild 
	select @id,@EmployeeID	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertSMSLogDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertSMSLogDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_InsertSMSLogDetails 3,''Rajendran'',''103-Manikandan-03:00,104-Anbu-03:00'',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertSMSLogDetails]
	-- Add the parameters for the stored procedure here
	@TemplateID int,
	@Receivers varchar(250),
	@ExceptionEmployees varchar(max),
	@Status int,
	@Message varchar(max),
	@ShiftID int,
	@StatusMessage varchar(max),
	@NextTriggeringTime varchar(20)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Insert into TA_Tbl_SMSLogDetails values(@TemplateID,CONVERT(datetime, CONVERT(varchar(10),getdate(),111)),@Receivers,@NextTriggeringTime,@Status,@StatusMessage,@ShiftID,@Message,GETDATE())
	Declare @id int
	set @id=@@IDENTITY
	if(@ExceptionEmployees!='''')
	begin
		Insert into TA_Tbl_SMSLogChild 
		select @id,Value from dbo.Split(@ExceptionEmployees,'','')
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LoadFirstYearLeaveQuota]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LoadFirstYearLeaveQuota]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	19-Jul-2013
Descriptions	:	for selecting leave quota for the employee
Proc_TA_LoadFirstYearLeaveQuota 2,42
*/
CREATE proc [dbo].[Proc_TA_LoadFirstYearLeaveQuota]
(
@YearsettingsId int,
@EmployeeId int
)
as
begin
	SET NOCOUNT ON;
	declare @CurrentYear as int;
	declare @getFirstPreviousYearCount as int;
	declare @EndYear as int;
	declare @CountPolicy as int;
	set @EndYear=0;
	set @getFirstPreviousYearCount=0;
	set @CurrentYear=0;
	set @CountPolicy=0;
	set @CurrentYear=(select StartYear from TA_Tbl_YearSetting where YearSettings_Id=@YearsettingsId and IsActive=1)
	set @EndYear=(select EndYear from TA_Tbl_YearSetting where YearSettings_Id=@YearsettingsId and IsActive=1)
	set @getFirstPreviousYearCount=(select COUNT(*) from TA_Tbl_YearSetting where StartYear<@CurrentYear and EndYear<@EndYear)
	set @CountPolicy=(select COUNT(*) from TA_Tbl_Employee E
			inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on ELPD.EmpID=E.Employee_Id
			inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELPD.Policy_ID
			inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELPD.LeaveType_Id
			left join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=ELPD.Policy_ID and LPD.LeaveType_Id=LT.LeaveType_Id
			inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.LeaveTypeId=LT.LeaveType_Id and ELT.EmployeeId=E.Employee_Id
			where E.Employee_Id=@EmployeeId)
	if(@getFirstPreviousYearCount=0)
		begin
			if(@CountPolicy>0)
				begin
				select LT.LeaveType_Id as Id,LT.LeaveType as ''Leave Type'',(ELT.PreviousYearBalance+LPD.MaxDays_avail)-(ELT.NoOffLeaveAvailed) as ''Number of Days'' from TA_Tbl_Employee E
				inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on ELPD.EmpID=E.Employee_Id
				inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELPD.Policy_ID
				inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELPD.LeaveType_Id
				left join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=ELPD.Policy_ID and LPD.LeaveType_Id=LT.LeaveType_Id
				inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.LeaveTypeId=LT.LeaveType_Id and ELT.EmployeeId=E.Employee_Id
				where E.Employee_Id=@EmployeeId
				end
			else
				begin
				select LT.LeaveType_Id as Id,LT.LeaveType as ''Leave Type'',(ELT.PreviousYearBalance+0)-(ELT.NoOffLeaveAvailed) as ''Number of Days'' from TA_Tbl_Employee E
				inner join ta_tbl_emp_LeaveTypedetails ELT on ELT.EmployeeId=E.Employee_Id
				inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id=ELT.LeaveTypeId
				where E.Employee_Id=@EmployeeId
				end
		end
	else
		begin
			select 0 as Id
		end
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================    
-- Author	:  Prabakaran.P   
-- ALTER  date	:     
-- Description	: Insert New Leave Types in Year closure table 
-- Modified by 	: Manjula.P
-- Modified on 	:  26-Jul-2013
-- Descriptions	:	Changing decimal to deciaml(18,2) datatype for current quota.
-- =============================================    
CREATE   PROCEDURE [dbo].[Proc_TA_InsertYearclosureNewLeaveTypes]     
 -- Add the parameters for the stored procedure here    
 @OrgLevelId INT,    
 @Employee_Id INT,    
 @LeaveTypeID INT,    
 @Current_Quota DECIMAL(18,2),    
 @auEmpId INT    
AS    
BEGIN    
SET NOCOUNT ON;    
Declare @Year_SettingID INT    
Declare @Count INT    
Declare @YearClosure VARCHAR(50)    
	Set @Year_SettingID=(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)    
	Set @Count=(select count(YearClosureId) from Ta_Tbl_Yearclosure    
   	Where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID )    
if (@Count<=0)    
	begin
		Insert into Ta_Tbl_Yearclosure     
 		(Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID)    
 		values (@Year_SettingID,@OrgLevelId,@Employee_Id,@LeaveTypeID,@Current_Quota,@Current_Quota,@auEmpId)    
	end   
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertYearclosure]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertYearclosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================    
-- Author:  Arun vinoth    
-- ALTER  date: 09 Aug 07    
-- Description: Insert Year closure table 
-- Modified by : Prabakaran.P
-- Modified on : 24-Mar-08   
--	Modified By		:	Manjula.P
--	Modified Date	:	26-Jul-2013
--	Descriptions	:	Changing decimal to deciaml(18,2) datatype for current quota.
--	Proc_TA_InsertYearclosure ''I'',1,21,1,9.5,1
-- =============================================    
CREATE  PROCEDURE [dbo].[Proc_TA_InsertYearclosure]     
	@Type CHAR,    
	@OrgLevelId INT,    
	@Employee_Id INT,    
	@LeaveTypeID INT,    
	@Current_Quota DECIMAL(18,2),    
	@auEmpId INT
AS    
BEGIN    
	SET NOCOUNT ON;    
	Declare @Year_SettingID INT    
	Declare @Count INT    
	Declare @YearClosure VARCHAR(50)    
	IF (@Type=''U'')    
	BEGIN     
		UPDATE Ta_Tbl_Yearclosure SET Current_Quota=0,Available_Leaves=0 WHERE LeaveTypeID=@LeaveTypeID AND Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id    
	END    
	select @Year_SettingID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
	select @Count=count(YearClosureId) from Ta_Tbl_Yearclosure Where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID
	if (@Count=1)
	BEGIN
		Update Ta_Tbl_Yearclosure set	Current_Quota=@Current_Quota ,
										Available_Leaves=@Current_Quota + isnull(Carry_PrevYear,0)-isnull(Leave_Taken,0),Time_Stamp=getdate()      
		where Year_SettingID=@Year_SettingID AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID     
	end
	else if (@Count=0)    
	begin
		Insert into Ta_Tbl_Yearclosure(Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID)    
		values (@Year_SettingID,@OrgLevelId,@Employee_Id,@LeaveTypeID,@Current_Quota,@Current_Quota,@auEmpId)    
	end
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ManualTimeEntryExport]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ManualTimeEntryExport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*   
Procedure Name : Proc_TA_RptManualTimeEntry    
Description : select manual time entry details
Tables Included : TA_Tbl_ManualTimeEntry  
Created By : Gopinath.K
Created On : 10-Sep-2013
Proc_TA_ManualTimeEntryExport '''','''',''2014/08/01'',''2014/08/01'',''0,39'',0,0,''SuperAdmin'',''0'',''All'','''',0,0,''Both''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ManualTimeEntryExport] 
(
	-- Add the parameters for the stored procedure here
	@EmpAutoID int,
	@employeeName nvarchar(50),
	@employeeId nvarchar(15),
	@fromdate nvarchar(20),
	@toDate nvarchar(20),
	@levelId varchar(8000),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(25)	,
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @DesignationID int,
	@Gender varchar(10)	
)
AS
declare @sqlQuery as varchar(8000)  
set @sqlQuery = ''''  
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	DECLARE @timeformat as int
	DECLARE @time as nvarchar(25)
	SELECT @time=TimeFormat FROM TA_Tbl_DateandTimeFormat
	if(@time=''HH:mm'')
		BEGIN
			SET @timeformat=108
		END
	ELSE
		BEGIN
			SET @timeformat=109
		END
BEGIN
	SET NOCOUNT ON;
	--Temporary table''s creation
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	Declare @sqlEmpLevel nvarchar(4000)
	Declare @sqlCommon nvarchar(4000)
	set @sqlEmpLevel=
		''insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,''''''+cast(@toDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''')''
	Execute(@sqlEmpLevel)
	Declare @sqlEmpDesi nvarchar(4000)
	set @sqlEmpDesi=
	''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@toDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(8)) + '''''')''
	Execute(@sqlEmpDesi)
	Declare @sqlEmpType nvarchar(4000)
	set @sqlEmpType=
	''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@toDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
	Execute(@sqlEmpType)
	Declare @sqlEmpCategory nvarchar(4000)
	set @sqlEmpCategory=
	''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@toDate as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
	Execute(@sqlEmpCategory)
	SET NOCOUNT ON;
	set @sqlQuery = @sqlQuery + '' SELECT distinct ISNULL(TA_Tbl_Employee.Employee_FirstName, '''' '''') + SPACE(1) + ISNULL(TA_Tbl_Employee.Employee_LastName, '''' '''') AS Employee_Name,'' 
	set @sqlQuery = @sqlQuery + ''  replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name,''
	set @sqlQuery = @sqlQuery + '' TA_Tbl_ManualTimeEntry.ManualTimeEntry_Id, dbo.TA_Tbl_Employee.Employee_Code_Id as ManualTimeEntry_Employee_Id, Convert(varchar, TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date, case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate, ''+cast(@dateFormat as varchar(100))+'') end AS ManualTimeEntry_InDate, case when ''+cast(@timeformat as varchar(100))+''=108 then convert(char(5),cast(TA_Tbl_ManualTimeEntry.ManualTimeEntry_InTime as datetime),108)
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_InTime end as ManualTimeEntry_InTime, case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate, ''+cast(@dateFormat as varchar(100))+'') end AS ManualTimeEntry_OutDate, 
	case when ''+cast(@timeformat as varchar(100))+''=108 then convert(char(5),cast(TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutTime as datetime),108)
	else TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutTime end as ManualTimeEntry_OutTime,  replace(TA_Tbl_ManualTimeEntry.ManualTimeEntry_Reason,''''&amp;'''',''''&'''') as ManualTimeEntry_Reason,TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status,
	TA_Tbl_Title.TitleName,TA_Tbl_Employee.Gender,TA_Tbl_ManualTimeEntry.ManualTimeEntry_InPunchType,TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutPunchType ''		set @sqlQuery = @sqlQuery + '' FROM TA_Tbl_Employee'' 
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_ManualTimeEntry ON TA_Tbl_Employee.Employee_Code_Id = TA_Tbl_ManualTimeEntry.ManualTimeEntry_Employee_Id''	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId = #EmpDesignation.DesignationId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' WHERE ((TA_Tbl_Employee.Employee_Status = 1) 
	or(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102)
	>= 
	convert(varchar(11),TA_Tbl_ManualTimeEntry.ManualTimeEntry_Date,102))) 
	AND (TA_Tbl_Employee.Isdeleted = 0) AND (TA_Tbl_Employee.report_exclude = 0) AND (TA_Tbl_ManualTimeEntry.IsOnDuty=0)''
	--********************************End***************************************************************************************************
	set @sqlQuery = @sqlQuery + '' AND ((TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate >= CONVERT(DATETIME, ''''''+cast(@fromdate as nvarchar(20))+'''''', 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_InDate <= CONVERT(DATETIME, ''''''+cast(@todate as nvarchar(20))+'''''', 102) )''
	set @sqlQuery = @sqlQuery + '' or (TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate >= CONVERT(DATETIME, ''''''+cast(@fromDate as nvarchar(20))+'''''', 102) and TA_Tbl_ManualTimeEntry.ManualTimeEntry_OutDate <= CONVERT(DATETIME, ''''''+cast(@toDate as nvarchar(20))+'''''', 102) ))''		 	
	IF not (@employeeName='''')  
		BEGIN
		 Declare @Tempname nvarchar(200)
         set @Tempname= ''(TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(TA_Tbl_Employee.Employee_LastName,'''''''')''
	     set @sqlQuery = @sqlQuery + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 
	    END
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	 
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	if not (@employeeId='''')  
  begin  
   set @SqlQuery = @SqlQuery + '' and ta_tbl_employee.Employee_Code_Id = '''''' + cast (@employeeId as nvarchar(50)) + '''''' ''  
  end  
	if not(@Status='''' or @Status=''All'')
		begin
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_ManualTimeEntry.ManualTimeEntry_Status = '''''' + @Status + ''''''''
		end	
	set @sqlQuery = @sqlQuery + '' order by TA_Tbl_Employee.Employee_Code_Id''
	EXEC (@sqlQuery)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeavSancAuthority]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeavSancAuthority]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_LeavSancAuthority 3
CREATE    PROCEDURE [dbo].[Proc_TA_LeavSancAuthority]
@TitleID INT 
AS
BEGIN
	SELECT e.Employee_Id,(e.Employee_FirstName + '' - '' +(e.Employee_Code_Id)) as Employee_FirstName FROM TA_Tbl_Employee e
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	WHERE EDesig.DesignationId IN 
	(
		SELECT t.TitleId FROM Ta_Tbl_Title t inner join ta_tbl_grade g on t.gradeid=g.grade_id 
		where g.isdeleted=0 and g.grade_Level  <= (SELECT g.grade_Level 
		FROM Ta_Tbl_Title t inner join ta_tbl_grade g on t.gradeid=g.grade_id  where TitleId = @TitleID and g.isdeleted=0)
	) 
	And EDesig.EffectiveDate = (select top 1 EffectiveDate from Ta_Tbl_employeeDesignation where EmployeeID=E.Employee_ID and  EffectiveDate <= getDate() 
	order by EffectiveDate desc )
	AND e.Isdeleted=0 and e.Employee_Firstname<>''Administrator'' and e.InActive_Status=0   ORDER BY e.Employee_FirstName
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectShiftRosterForShiftAllocation  
Description : select shift roster for respective company
Tables Included : TA_Tbl_ShiftRoaster
Created By : Christopher.S   
Created On : 13-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRosterForShiftAllocation]
	-- Add the parameters for the stored procedure here
	@companyId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT *  FROM TA_Tbl_ShiftRoaster WHERE Isdeleted = 0 and Level_Id = @companyId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoasterById]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRoasterById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRoasterById]
(@RoasterId int)
 AS
	BEGIN
		SELECT TA_Tbl_ShiftRoaster.*,TA_Tbl_Leveldetails.Name  
		FROM TA_Tbl_ShiftRoaster INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_ShiftRoaster.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE TA_Tbl_ShiftRoaster.ShiftRoaster_Id=@RoasterId and TA_Tbl_ShiftRoaster.IsDeleted=0
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftRoaster]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftRoaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftRoaster]  
@usergroupname nvarchar(250),
@UserLevels nvarchar(2000),
@ParentId int
    AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@usergroupname,@ParentID) as LevelId 
DECLARE @Isdel int
declare @Query as varchar(7000)
SET @Isdel=0
if(@usergroupname=''SuperAdmin'')
	BEGIN
		--set @Query = ''SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id WHERE SR.Isdeleted=''+cast(@Isdel as nvarchar(5))+'' and SR.Level_Id in ( ''+ @UserLevels +'' )''
		set @Query = ''SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id WHERE SR.Isdeleted=''+cast(@Isdel as nvarchar(5))+''''
	END
else
	BEGIN
		--set @Query = ''SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id WHERE SR.Isdeleted=''+cast(@Isdel as nvarchar(5))+'' and SR.Level_Id in ( ''+ @UserLevels +'' )''
		set @Query = ''SELECT LD.name,SR.*  FROM TA_Tbl_ShiftRoaster SR INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id WHERE SR.Isdeleted=''+cast(@Isdel as nvarchar(5))+''''
	END
             exec(@Query)
drop table #LevelRights
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternId]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternId]
 AS
  BEGIN
	 SELECT ShiftPattern_Id FROM TA_Tbl_ShiftPattern WHERE Isdeleted=1 				
  END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternForShiftRoster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftRoster]
	-- Add the parameters for the stored procedure here
	@companyId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id = @companyId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectShiftPatternForShiftAllocation  
Description : select shift pattern for respective company
Tables Included : TA_Tbl_ShiftPattern
Created By : Christopher.S   
Created On : 13-Jan-2009
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternForShiftAllocation]
	-- Add the parameters for the stored procedure here
	@companyId int	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT ShiftPattern_Id,Pattern_Name,Shift_days,Isdeleted FROM TA_Tbl_ShiftPattern WHERE Isdeleted = 0 and Level_Id = @companyId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPatternDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPatternDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPatternDetails]
(
@type CHAR(1),
@ShiftPatternId INT=0
)
AS
DECLARE @del BIT
SET @del=1
--selecting all Shift Pattern
IF @type=''A''
BEGIN
	SELECT * FROM TA_Tbl_ShiftPattern WHERE IsDeleted=@del
END
--selecting Shift Pattern based on id
ELSE IF @type=''P''
BEGIN
	SELECT * FROM TA_Tbl_ShiftPattern WHERE IsDeleted=@del AND ShiftPattern_Id=@ShiftPatternId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftPattern_ShiftAllocation]  
	@ShiftPatternID INT  
	AS  
	BEGIN  
	 SET NOCOUNT ON;  
	create table #TABLE  
	(  
	id INT,  
	name nvarchar(255)  
	)  
	DECLARE @Count INT  
	DECLARE @iLoop INT  
	DECLARE @Query NVARCHAR(4000)  
	DECLARE @Query1 NVARCHAR(4000)  
	SET @iLoop = 1  
	SET @Count= (SELECT Shift_days FROM TA_Tbl_Shiftpattern WHERE ShiftPattern_Id=@ShiftPatternID)   
	SET @Query = ''''  
	WHILE (@iLoop <= @Count)  
	 BEGIN  
		Declare @test varchar(1000)  
	  SET @test = ''SELECT count(dbo.TA_Tbl_ShiftPattern.Day''+ cast(@iLoop as VARCHAR) +''_Shift)''  
	  set @test = @test + '' FROM         dbo.TA_Tbl_ShiftPattern INNER JOIN ''  
	  set @test = @test + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_ShiftPattern.Day'' +  cast(@iLoop as VARCHAR)  + ''_shift = dbo.TA_Tbl_Shift.Shift_Id ''  
	  set @test = @test + '' WHERE     (dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id = '' + cast(@ShiftPatternID as VARCHAR) + '')''  
				create table #temp1 
				(
				rows int
				)  
				insert into #temp1 exec(@test) 
				declare @count1 int
				set @count1=(select * from #temp1)
				drop table #temp1
		if (@count1=0)
			begin
				insert into #TABLE values(-1,''Off'')
			end   
		else
			begin	 
				  SET @Query = ''SELECT dbo.TA_Tbl_ShiftPattern.Day''+ cast(@iLoop as VARCHAR) +''_Shift,''  
				  set @Query = @Query + '' dbo.TA_Tbl_Shift.Shift_ShortName ''  
				  set @Query = @Query + '' FROM         dbo.TA_Tbl_ShiftPattern INNER JOIN ''  
				  set @Query = @Query + '' dbo.TA_Tbl_Shift ON dbo.TA_Tbl_ShiftPattern.Day'' +  cast(@iLoop as VARCHAR)  + ''_shift = dbo.TA_Tbl_Shift.Shift_Id ''  
				  set @Query = @Query + '' WHERE     (dbo.TA_Tbl_ShiftPattern.ShiftPattern_Id = '' + cast(@ShiftPatternID as VARCHAR) + '')''  
				  Insert  into #TABLE exec(@Query)  
			end
	  set @iLoop = @iLoop + 1  
	 END  
	Select * From #TABLE  
	END  
drop table #TABLE  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftPattern]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_SelectShiftPattern]  
@UserGroupName nvarchar(250),
@UserLevels nvarchar(2000),
@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(8000)
BEGIN
	--set @Query = ''SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id in ( ''+ @UserLevels +'' )''
	set @Query = ''SELECT ShiftPattern_Id,Pattern_Name FROM TA_Tbl_ShiftPattern WHERE Isdeleted=0 and Level_Id in (select * from #LevelRights)''
	exec (@Query)
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftId]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name  : Proc_TA_SelectShiftId
-- Tables Used	     : TA_Tbl_TemporaryShiftAllocation,TA_Tbl_PermanentShiftAllocation,TA_Tbl_Employee
-- Purpose                : This Procedure is used to get the Shift Id either from Temporary or Permanent Shift Allocation   
--	Proc_TA_SelectShiftId ''8967661'',2019,8,30
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftId] 
(
   @Employeecode VARCHAR(15),
   @year VARCHAR(5),
   @month VARCHAR(5),
   @date VARCHAR(5)
)  
AS
DECLARE @query VARCHAR(2000)   
DECLARE @ShiftId INT 
CREATE TABLE #Temp(Shift_Id INT)
CREATE TABLE #Temp1(Shift_Id INT)

SET @query = ''SELECT (tsa.Day''+ @date + ''Shift)  from TA_Tbl_TemporaryShiftAllocation tsa,TA_Tbl_Employee emp where tsa.[Year]= '' + @year + ''  and  tsa.[Month]= '' + @month + '' and   tsa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = ''''''+ @Employeecode +'''''' ''  
INSERT INTO #Temp EXEC(@query)
SET @ShiftId=(SELECT * FROM #Temp)
SET @ShiftId = ISNULL(@ShiftId,-2)

IF(@ShiftId = -2 OR @ShiftId = 0)
BEGIN
  SET @query = ''SELECT (psa.Day''+ @date + ''Shift)  from TA_Tbl_PermanentShiftAllocation psa,TA_Tbl_Employee emp where psa.[Year]= '' + @year + ''  and  psa.[Month]= '' + @month + '' and   psa.EmployeeId = emp.Employee_Id and emp.Employee_Code_Id = '''''' + @Employeecode +'''''' ''  
   INSERT INTO #Temp1 EXEC(@query)
  SET @ShiftId=(SELECT * FROM #Temp1)
END

ELSE IF(@ShiftId > 0 or @ShiftId = -1)
BEGIN
   set @ShiftId = ISNULL(@ShiftId,0)
END

IF(@SHIFTID = 0)
		BEGIN
			Delete from #Temp1
			Declare @CompanyId int
			Declare @EmpAutoId int
			Declare @EmpLevelId int
			select @EmpAutoId = isnull(Employee_Id,0) from TA_Tbl_Employee where Employee_Code_Id=@Employeecode
			--checking AutoShift Employee or not
				IF Exists(SELECT AutoShiftConfigId FROM TA_Tbl_AutoShiftConfiguration WHERE EmployeeId = @EmpAutoId and (ShiftId1!=0 or ShiftId2!=0 or ShiftId3!=0 or ShiftId4!=0 or ShiftId5!=0))
				Begin				
					select @EmpLevelId = isnull(Levelid,0) from TA_Tbl_EmployeeLevel where EmployeeId = @EmpAutoId
					select @CompanyId = dbo.[Func_TA_GetParentIds](@EmpLevelId)		
					SELECT @ShiftId=Shift_Id FROM TA_TBL_SHIFT WHERE DEFAULTSHIFT = 1 AND ISDELETED = 0 AND LEVEL_ID=@CompanyId
				End
		END

 SELECT ISNULL(@ShiftId,0)

DROP TABLE #Temp
DROP TABLE #Temp1' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShiftDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShiftDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified by Manikandan.RR
-- Modified on 18-July-2020 04:22 PM
-- [Proc_TA_SelectShiftDetails]
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectShiftDetails]
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @timeformat   varchar(10)
	SELECT @timeformat=TimeFormat FROM dbo.Func_TA_GetDateTimeFormat()
	SELECT	LD.name,
			S.Shift_Id,
			S.Shift_Name,
			S.Shift_ShortName, 
			S.Shift_StartTime as shiftstart,
			S.Shift_EndTime as shiftend,  
			case	when @timeformat=''hh:mm tt'' then S.Shift_StartTime + '' TO '' + S.Shift_EndTime 
					else convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) 
			end as ShiftTime,
			case when S.IsDeleted=1 then ''True'' else ''False'' end Isdeleted,
			case when ShiftType=0 then ''Function Key'' else ''Free Scan'' end ShiftType,
			Case when [24HrsShift]=1 then ''Yes'' else ''No'' end [24HrsShift],
			Shift_GraceInTime,
			Shift_GraceOutTime,
			Shift_MinTimeOT,
			Shift_MaxTimeOT,
			Shift_WorkingDay_OverTime,
			Shift_FirstHalf_StartTime,
			Shift_FirstHalf_EndTime,
			Shift_SecondHalf_StartTime,
			Shift_SecondHalf_EndTime,
			Shift_BreakStartTime1,
			Shift_BreakEndTime1,
			Shift_BreakStartTime2,
			Shift_BreakEndTime2,
			Shift_BreakStartTime3,
			Shift_BreakEndTime3,
			DefaultShift,
			CreatedDate,
			ModifiedDate,
			MaxShiftWorkHours
	FROM TA_Tbl_Shift S 
	INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id
	INNER JOIN #LevelRights ON #LevelRights.LevelId = S.Level_Id 
	Union 
	SELECT '''' as name,
			S.Shift_Id,
			S.Shift_Name, 
			S.Shift_ShortName, 
			S.Shift_StartTime as shiftstart,
			S.Shift_EndTime as shiftend,  
			case	when @timeformat=''hh:mm tt'' then S.Shift_StartTime + '' TO '' + S.Shift_EndTime 
					else convert(char(5),cast(S.Shift_StartTime as datetime),108) + '' TO '' +  convert(char(5),cast(S.Shift_EndTime as datetime),108) 
			end as ShiftTime,
			case when S.IsDeleted=1 then ''True'' else ''False'' end Isdeleted,
			case when ShiftType=0 then ''Function Key'' else ''Free Scan'' end ShiftType,
			Case when [24HrsShift]=1 then ''Yes'' else ''No'' end [24HrsShift],
			Shift_GraceInTime,
			Shift_GraceOutTime,
			Shift_MinTimeOT,
			Shift_MaxTimeOT,
			Shift_WorkingDay_OverTime,
			Shift_FirstHalf_StartTime,
			Shift_FirstHalf_EndTime,
			Shift_SecondHalf_StartTime,
			Shift_SecondHalf_EndTime,
			Shift_BreakStartTime1,
			Shift_BreakEndTime1,
			Shift_BreakStartTime2,
			Shift_BreakEndTime2,
			Shift_BreakStartTime3,
			Shift_BreakEndTime3,
			DefaultShift,
			CreatedDate,
			ModifiedDate,
			MaxShiftWorkHours
	FROM TA_Tbl_Shift S
	WHERE S.Level_Id=0	
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectShift]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectShift]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Modified By		:	Prabakaran.P
Modified On		:	05-Feb-08
Description		:	UserGroupName Checking for Active and Inactive Records
Proc_TA_SelectShift ''superadmin'',''1,2,3,4,5,6,7,8,9,20,21,22,23,24,137,138,2,3,140,47,113,132,134,135,150,136,145,146,147,151,152,153,154,155,159,160,161,162,133'',0
Modified by:Manikandan.R
Modified on:23-11-2016 14.58
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectShift]
(
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentId int
)
AS
BEGIN
	SET NOCOUNT ON
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	DECLARE @timeformat   varchar(10)
	declare @Query as varchar(7000)
	declare @CommonJoinQuery as varchar(7000)
	declare @SelectJoinQuery as varchar(7000)
	set @SelectJoinQuery =''SELECT	LD.name,
									S.Shift_Id,
									S.Shift_ShortName, 
									S.Shift_StartTime as shiftstart,
									S.Shift_EndTime as shiftend,
									S.Isdeleted,''
	set @CommonJoinQuery ='' INNER JOIN TA_Tbl_LevelDetails LD ON LD.Id = S.Level_Id 
							INNER JOIN #LevelRights ON #LevelRights.LevelId = S.Level_Id
							WHERE S.Isdeleted=0''
	SELECT @timeformat=TimeFormat FROM TA_Tbl_DateandTimeFormat
	if(@timeformat=''hh:mm tt'')
	BEGIN
		set @Query	= @SelectJoinQuery 
		set @Query	= @Query+''S.Shift_Name + '''' -'''' + '''' ( '''' + S.Shift_StartTime + '''' - '''' +  S.Shift_EndTime + '''' )'''' as Shift_Name , 						
							S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime FROM TA_Tbl_Shift S'' 
		set @Query	= @Query +@CommonJoinQuery		
		set @Query	= @Query +'' Union ''
		set @Query	= @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,S.Isdeleted,S.Shift_Name + '''' -'''' + '''' ( '''' + S.Shift_StartTime + '''' - '''' +  S.Shift_EndTime + '''' )'''',  S.Shift_StartTime + '''' TO '''' + S.Shift_EndTime as ShiftTime FROM TA_Tbl_Shift S '' 
		set @Query	= @Query +'' WHERE S.Level_Id=0''	 				
	END
	else
	BEGIN
		set @Query	= @SelectJoinQuery 
		set @Query	= @Query +''	S.Shift_ShortName + '''' -'''' + '''' ( '''' + convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' - '''' + convert(char(5),cast(S.Shift_EndTime as datetime),108) + '''' )'''' as Shift_Name,
								convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' TO '''' + convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime
								FROM TA_Tbl_Shift S ''
		set @Query	= @Query +@CommonJoinQuery		
		set @Query	= @Query +'' Union ''
		set @Query	= @Query + ''SELECT '''''''' as name,S.Shift_Id,S.Shift_ShortName, S.Shift_StartTime as shiftstart,S.Shift_EndTime as shiftend,S.Isdeleted,S.Shift_ShortName + '''' -'''' + '''' ( '''' + convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' - '''' + convert(char(5),cast(S.Shift_EndTime as datetime),108) + '''' )'''', 
								convert(char(5),cast(S.Shift_StartTime as datetime),108) + '''' TO '''' + convert(char(5),cast(S.Shift_EndTime as datetime),108) as ShiftTime
								FROM TA_Tbl_Shift S '' 
		set @Query	= @Query +'' WHERE S.Level_Id=0''					
	END
	EXEC(@Query)
	DROP TABLE #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPreviousYearLeaveDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPreviousYearLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By:Manikandan.RR
-- Modified Date:12-Jul-2019 03:45 PM
-- Proc_TA_SelectPreviousYearLeaveDetails 4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectPreviousYearLeaveDetails] 
	-- Add the parameters for the stored procedure here
	@employeeId as int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT LT.LeaveDescription+'' (''+LT.LeaveType+'')'' AS [Leave Type],TA_Tbl_YearClosure.Carry_PrevYear AS [Carry Previous Year]
	FROM TA_Tbl_YearClosure
	INNER JOIN TA_Tbl_LeaveType LT ON TA_Tbl_YearClosure.LeaveTypeID = LT.LeaveType_Id
	INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_YearClosure.Year_SettingID = TA_Tbl_YearSetting.YearSettings_Id
	WHERE TA_Tbl_YearSetting.IsActive = 1 AND TA_Tbl_YearClosure.Employee_Id = @employeeId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetailsByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name :  Proc_TA_SelectPermissionDetailsByEmpId  
Description : Get Permisssion Details of Employees Based on their Employee_Id  
Tables Included : TA_Tbl_Permission  
Created By : Prabakaran  
Created On : 18-Jul-07  
Modified By :  
Modified On :
Proc_TA_SelectPermissionDetailsByEmpId 10899,''3'',''58'',''20120301'',''20120301'',''New - Trainee Staffs IT'',0
*/  
CREATE procedure [dbo].[Proc_TA_SelectPermissionDetailsByEmpId]  
@Employee_Id bigint,
@GradeLevel nvarchar(20),
@LevelRights varchar(8000), 
@PermissionStartDate datetime = ''01/01/1900'', 
@PermissionEndDate datetime = ''01/01/1900'',
@UserGroupName varchar(250),
@ParentID int  
as  
BEGIN
SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @CurrentDate AS NVARCHAR(30)
	DECLARE @sql AS VARCHAR(8000)
	declare @sql1 as varchar(8000)    
	SET @CurrentDate = GetDate()
	-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @sql1=''''
	 SET @sql = '' select '''''''' as employeeid,'''''''' as Employee_FirstName,'''''''' as ''''name'''',TA_Tbl_Permission.Permission_Id,TA_Tbl_Permission.Employee_Id, ''
	SET @sql = @sql + '' case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, TA_Tbl_Permission.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, TA_Tbl_Permission.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Permission_AppliedDate
	,TA_Tbl_Permission.Permission_Date, ''
	SET @sql = @sql + '' (REPLACE(CONVERT(VARCHAR(9), TA_Tbl_Permission.Permission_FromTime, 6), '''' '''', ''''/'''') + '''' - '''' + REPLACE(CONVERT(VARCHAR(9),TA_Tbl_Permission.Permission_ToTime, 6), '''' '''', ''''/'''')) AS Duration, ''
	SET @sql = @sql + '' TA_Tbl_Permission.Permission_FromTime,TA_Tbl_Permission.Permission_ToTime, ''
	SET @sql = @sql + '' TA_Tbl_Permission.Permission_Reason,TA_Tbl_Permission.Permission_Status,TA_Tbl_Permission.Emp_Id_Sanction, ''
	SET @sql = @sql + '' TA_Tbl_Permission.Remarks,TA_Tbl_Permission.IsDeleted,TA_Tbl_Permission.TimeStamp,TA_Tbl_Permission.Emp_Id from TA_Tbl_Permission ''
	SET @sql = @sql + '' inner join TA_Tbl_EmployeeLevel el ON TA_Tbl_Permission.Employee_Id = el.EmployeeId ''
	SET @sql = @sql + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Permission.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sql = @sql + '' inner join TA_Tbl_YearSetting ys on TA_Tbl_Permission.YearSettings_Id=ys.YearSettings_Id ''
	set @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=el.EffectiveDate and #EmpLevel.employeeid=el.EmployeeId ''
	set @sql = @sql + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	SET @sql = @sql + '' where ys.IsActive=1 and TA_Tbl_Permission.Employee_Id='''''' + cast(@Employee_Id as nvarchar(20)) + '''''' and TA_Tbl_Permission.IsDeleted=0 ''
	SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level >=''''''+ @GradeLevel + '''''' ''
	If not(@PermissionStartDate = ''01/01/1900'' and @PermissionEndDate = ''01/01/1900'')
	Begin
		set @sql = @sql + '' and (TA_Tbl_Permission.Permission_FromTime between convert(datetime,'''''' + cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'''', 102) and convert(datetime,'''''' + cast(@PermissionEndDate as nvarchar(11)) + '' 23:59:59.999'''',102)''
		set @sql = @sql + '' or TA_Tbl_Permission.Permission_ToTime between convert(datetime,'''''' + cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'''', 102) and convert(datetime,'''''' + cast(@PermissionEndDate as nvarchar(11)) + '' 23:59:59.999'''',102))''
	End
	set @sql1= @sql1 + '' Order By Permission_Id Desc ''
	exec(@sql + @sql1)  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPermissionDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPermissionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_SelectPermissionDetails] ''SuperAdmin'',''0'',21,null,null,''01/01/1900'',''01/01/1900'',null,0
CREATE  procedure [dbo].[Proc_TA_SelectPermissionDetails]
@Employee_ID int,
@UserGroupName nvarchar(250),
@GradeLevel nvarchar(20),
@LevelRights varchar(2000), 
@Employee_Code_Id nvarchar(50) = null, 
@Employee_FirstName varchar(50) = null, 
@PermissionStartDate datetime = ''01/01/1900'', 
@PermissionEndDate datetime = ''01/01/1900'' ,
@EmpSwipeCard varchar(20),
@ParentID int 
as  
begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000) 
	declare @sql1 as varchar(8000)  
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @sql1=''''
	SET @sql = '' select E.Employee_Code_Id as employeeid,e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''') as Employee_FirstName,ld.name,p.Permission_Id,p.Employee_Id,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, p.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, p.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Permission_AppliedDate	
	,p.Permission_Date,(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '''' '''', ''''/'''') + '''' - '''' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '''' '''', ''''/'''')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,p.Permission_Reason,p.Permission_Status,p.Emp_Id_Sanction,p.Remarks,p.IsDeleted,p.TimeStamp,p.Emp_Id from TA_Tbl_Permission p  ''
	SET @sql = @sql + '' inner join Ta_tbl_employee e on e.Employee_Id=p.Employee_Id  ''
	SET @sql = @sql + '' inner join TA_Tbl_EmployeeLevel el ON e.Employee_Id = el.EmployeeId ''
	SET @sql = @sql + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
	SET @sql = @sql + '' inner JOIN TA_Tbl_EmployeeDesignation ON p.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
	SET @sql = @sql + '' inner JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	SET @sql = @sql + '' inner JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId  ''
	set @sql = @sql + '' inner join TA_Tbl_YearSetting ys on p.YearSettings_Id=ys.YearSettings_Id ''
	set @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=el.EffectiveDate and #EmpLevel.employeeid=el.EmployeeId ''
	set @sql = @sql + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	SET @sql = @sql + '' where ys.IsActive=1 and p.IsDeleted=''''0''''  and e.isdeleted=''''0'''' ''
	If(@UserGroupName<>''SuperAdmin'')
		Begin
			SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level >=''''''+ @GradeLevel + '''''' ''
		End
	If not(@Employee_Code_Id = '''')
		Begin
			set @sql = @sql + '' and e.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sql = @sql + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	If not(@Employee_FirstName = '''')
		Begin
			set @sql = @sql + '' and (e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + '''''')''
		End
	If not(@PermissionStartDate = ''01/01/1900'' and @PermissionEndDate = ''01/01/1900'')
		Begin
			set @sql = @sql + '' and (p.Permission_FromTime between convert(datetime,'''''' + cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'''', 102) and convert(datetime,'''''' + cast(@PermissionEndDate as nvarchar(11)) + '' 23:59:59.999'''',102)''
			set @sql = @sql + '' or p.Permission_ToTime between convert(datetime,'''''' + cast(@PermissionStartDate as nvarchar(11)) + '' 00:00:00.000'''', 102) and convert(datetime,'''''' + cast(@PermissionEndDate as nvarchar(11)) + '' 23:59:59.999'''',102))''
		End
	set @sql1= @sql1 + '' Order By Permission_Id Desc ''	
	execute (@sql + @sql1)
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	: Proc_TA_SelectPayrollMonthClosureDetailsByCompId
Tables Incluced	: TA_Tbl_MonthClosure
Description	: It is used to fill month closure duration for company
Date Created	: 03-jun-09
Created By	: Christopher S
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetailsByCompId]
@companyId int
as
select mc.MonthClosure_Id, (Convert(varchar,mc.MonthClosure_StartDate,106) + '' - '' + Convert(varchar,mc.MonthClosure_EndDate,106) + '' [ '' + replace(ld.name,''&amp'',''&'') + '' ]'') as Duration 
from TA_Tbl_MonthClosure mc
inner join TA_Tbl_LevelDetails ld on ld.id=mc.OrgLevel_Id
where mc.IsDeleted=0 and mc.OrgLevel_Id=@companyId and mc.Process=''P''
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectPayrollMonthClosureDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	: Proc_TA_SelectPayrollMonthClosureDetails
Tables Incluced	: TA_Tbl_MonthClosure
Description	: It is used for the Payroll report to display duration Dropdown list
Date Created	: 16-Oct-07
Created By	: P.Prabakaran
*/
CREATE  PROCEDURE [dbo].[Proc_TA_SelectPayrollMonthClosureDetails]
as
select mc.MonthClosure_Id, (Convert(varchar,mc.MonthClosure_StartDate,106) + '' - '' + Convert(varchar,mc.MonthClosure_EndDate,106) + '' [ '' + replace(ld.name,''&amp'',''&'') + '' ]'') as Duration 
from TA_Tbl_MonthClosure mc
inner join TA_Tbl_LevelDetails ld on ld.id=mc.OrgLevel_Id
where mc.IsDeleted=0
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOtType]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectOtType]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
--Proc_TA_SelectOtType 5,''No'','''',''''
CREATE PROCEDURE [dbo].[Proc_TA_SelectOtType]
	@OtTypeID int,
	@All nvarchar(3),
	@UserGroup nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroup,@ParentID) as LevelId 
declare @Query as varchar(7000)
BEGIN	
	if (@All=''All'')
		Begin	
			if (@UserGroup=''SuperAdmin'')
				BEGIN	
					--select * from TA_Tbl_OtType order by OtType
					set @Query=	''select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID,case when TA_Tbl_OtType.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted, TA_Tbl_OtType.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_OtType''
					set @Query= @Query + '' inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id''
					set @Query= @Query + '' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_OtType.CompanyId''
					--set @Query= @Query +	'' where TA_Tbl_OtType.CompanyId in ('' +@UserLevels+ '')''
					set @Query= @Query +	'' order by ta_tbl_leveldetails.name'' 
				End
			Else
				Begin
					--select * from TA_Tbl_OtType where isdeleted=0 order by OtType
					set @Query= ''select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID, case when TA_Tbl_OtType.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted, TA_Tbl_OtType.TimeStamp,ta_tbl_leveldetails.name  from TA_Tbl_OtType''
					set @Query= @Query + '' inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id''
					set @Query= @Query + '' inner join #LevelRights on  #LevelRights.LevelId = TA_Tbl_OtType.CompanyId''
					--set @Query= @Query + '' where TA_Tbl_OtType.isdeleted=0 and TA_Tbl_OtType.CompanyId in ('' +@UserLevels+ '')''
					set @Query= @Query + '' where TA_Tbl_OtType.isdeleted=0''
					set @Query= @Query +	'' order by ta_tbl_leveldetails.name'' 
				End		
		End
	Else
		Begin
			set @Query= ''select TA_Tbl_OtType.OtTypeID, TA_Tbl_OtType.CompanyID, TA_Tbl_OtType.OtType, TA_Tbl_OtType.OtValue, TA_Tbl_OtType.EmpID, case when TA_Tbl_OtType.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted, TA_Tbl_OtType.TimeStamp from TA_Tbl_OtType where OtTypeID='' +cast(@OtTypeID as varchar(100))+ '' order by OtType''
		End
END
exec(@Query)
drop table #LevelRights
/*ALTER PROCEDURE [dbo].[Proc_TA_SelectOtType]
	@OtTypeID as int,
	@All as varchar(3),
	@UserGroup as varchar(25)	
AS
BEGIN	
	if (@All=''All'')
		Begin	
			if (@UserGroup=''SuperAdmin'')
				BEGIN	
					--select * from TA_Tbl_OtType order by OtType
						select TA_Tbl_OtType.*,ta_tbl_leveldetails.name  from TA_Tbl_OtType
						inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id
						order by ta_tbl_leveldetails.name
				End
			Else
				Begin
					--select * from TA_Tbl_OtType where isdeleted=0 order by OtType
					select TA_Tbl_OtType.*,ta_tbl_leveldetails.name  from TA_Tbl_OtType
						inner join ta_tbl_leveldetails on  TA_Tbl_OtType.CompanyId = ta_tbl_leveldetails.id
						where TA_Tbl_OtType.isdeleted=0
						order by ta_tbl_leveldetails.name
				End		
		End
	Else
		Begin
			select * from TA_Tbl_OtType where OtTypeID=@OtTypeID order by OtType
		End
END
*/
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectOnDutyEntryByID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectOnDutyEntryByID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_SelectManualEntryOnDutyByID] 916, null,null,''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',''1'',''0'',''1'',1 
-- CReate by Gopinath on 6thJun2014 for Individual users 
CREATE PROCEDURE [dbo].[Proc_TA_SelectOnDutyEntryByID]  
	@Employee_Id nvarchar(50),
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = ''01/01/1900'',   
	@EndDate datetime = ''01/01/1900'' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(8000)  
	set @SqlQuery = ''''  
	Declare @SqlQuery2 as varchar(8000)  
	set @SqlQuery2 = ''''  
	DECLARE @dateFormat as int
		SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	BEGIN  
	  set @SqlQuery = @SqlQuery + ''select OD.Onduty_EmployeeId as EmployeeID, OD.Onduty_ID,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS OndutyEntry_Date, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_FromDate ,
	 OD.Onduty_FromTime,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_ToDate,
	 OD.Onduty_ToTime,OD.Onduty_Reason,OD.Onduty_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then ''''''+
	   +'''''' + cast(E.Employee_MiddleName as varchar(50)) else ''''''+   +'''''' end + SPACE(1) + E.Employee_LastName AS Employee_Name,E.Employee_Id as EmpID ''  
	 set @SqlQuery = @SqlQuery + ''FROM TA_Tbl_OndutyEntry OD ''  
	 set @SqlQuery = @SqlQuery + ''INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=OD.Onduty_EmployeeId ''  
	 set @SqlQuery = @SqlQuery + ''and OD.Isdeleted=0 and E.IsDeleted=0 ''    
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''  
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''  
	 set @SqlQuery =@SqlQuery +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''  
	  set @SqlQuery = @SqlQuery + '' WHERE E.Employee_Code_Id=OD.Onduty_EmployeeId AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) ''
	 set @SqlQuery = @SqlQuery + '' AND E.Employee_Status=1 and OD.Onduty_EmployeeId='''''' + cast(@Employee_Id as nvarchar(100))  + ''''''''  
	 If not(@Employee_Code_Id = '''' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + '' and E.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''  
	 End  
		If Not (@EmpSwipeCard = '''')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
	 End   
	 If not(@Employee_FirstName = '''' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= ''(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')''
		set @SqlQuery2 = @SqlQuery2 + '' and ''+ @Tempname +''= '''''' + cast(@Employee_FirstName as nvarchar(100)) + '''''')''   
	 End  
	 If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + '' AND (((CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
		set @SqlQuery2 = @SqlQuery2 + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102)))''
	 End  
		set @SqlQuery2 = @SqlQuery2 + '' order by Onduty_ID desc''  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
	END  
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMovementsEntryXtraGrid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectMovementsEntryXtraGrid ''Admin'',''10''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectMovementsEntryXtraGrid]
	-- Add the parameters for the stored procedure here
	@FromDate VarChar(50), 
	@ToDate VarChar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@LevelRights varchar(1000),
	@ParentId int,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
		set @sqlQuery = ''''				
		set @sqlQuery = @sqlQuery + ''SELECT ED.employee_code_id AS [Employee Code Id],''       
		set @sqlQuery = @sqlQuery + '' ED.Employee_FirstName + '''' '''' + isnull(ED.Employee_LastName,'''''''') AS [Employee Name],''       
		set @sqlQuery = @sqlQuery + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''')  AS [Designation],''       
		set @sqlQuery = @sqlQuery + '' replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') AS [Level Name],''      
		set @sqlQuery = @sqlQuery + '' CD.Clk_InDeviceId as [In ReaderID],ITer.Terminal_Name as [In Terminal], CONVERT(VARCHAR,CD.Clk_InDate,101) as [InDate], Convert(varchar(10),CD.Clk_InTime,108) as [InTime],''      
		set @sqlQuery = @sqlQuery + '' CD.Clk_OutDeviceId as [Out ReaderID], OTer.Terminal_Name as [Out Terminal], CONVERT(VARCHAR,CD.Clk_OutDate,101) as [OutDate], Convert(varchar(10),CD.Clk_OutTime,108) as [OutTime], CONVERT(VARCHAR,CD.Clk_Date,101) as [ClockDate], SH.Shift_ShortName as [Shift Short Name] FROM TA_Tbl_Employee ED''      		 
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ED.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON ED.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
   		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ED.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ED.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''		
        set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_ClockDetails CD ON ED.SwipeCardNo = CD.Clk_EmpId''
        set @sqlQuery = @sqlQuery + '' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Processeddata PD ON PD.Employee_Code_Id = CD.Clk_EmpId and PD.Date=CD.Clk_Date''   
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_Shift SH ON SH.Shift_ID = PD.Shift_ID''  
	    set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON CD.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON CD.Clk_InDeviceId = ITer.Terminal_ReaderID''        
	    set @sqlQuery = @sqlQuery + '' Where  ED.IsDeleted = 0 and ED.report_exclude=0 and ED.employee_status=1''     				
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeDesignation.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ED.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
		--set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
			if(@EmpAutoId = 0)
		BEGIN 
		  set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
		END
		ELSE
		   BEGIN
			  set @sqlQuery = @sqlQuery + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
		   END
		if(@UserGroupName<>''SuperAdmin'')
		begin
		set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
		end
		If (@FromDate <> '''')      
		 Begin      
		  Set @sqlQuery = @sqlQuery + ''And CD.Clk_Date >= '''''' + @FromDate + '''''' ''      
		 End      
		 If (@ToDate <> '''')      
		 Begin      
		  Set @sqlQuery = @sqlQuery + ''And CD.Clk_Date <= '''''' + @ToDate + '''''' ''      
		 End   
		EXEC (@sqlQuery)
		drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthClosureById]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthClosureById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthClosureById]
	@MonthClosureID as int
AS
BEGIN
	select MonthClosure_Month, MonthClosure_Year from ta_tbl_monthclosure where MonthClosure_Id=@MonthClosureID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMonthCloseDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMonthCloseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_SelectMonthCloseDetails]
(
 @TYPE CHAR(1)='''',
 @MonthCloseID INT
)
AS
BEGIN	
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	DECLARE @Isdeleted INT
	SET @Isdeleted=0
	IF (@TYPE=''A'')
		BEGIN
			SELECT M.MonthClosure_Id,L.[Name],MonthClosure_Month,MonthClosure_Year,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_StartDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, MonthClosure_StartDate, @dateFormat) end AS MonthClosure_StartDate,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_EndDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, MonthClosure_EndDate, @dateFormat)end AS MonthClosure_EndDate,
			case when cast(@dateFormat as varchar(100))=106 then
			REPLACE(CONVERT(VARCHAR, MonthClosure_ClosingDate,@dateFormat),'' '',''-'') 
			else CONVERT(VARCHAR, MonthClosure_ClosingDate, @dateFormat)end AS MonthClosure_ClosingDate 
			FROM TA_Tbl_MonthClosure M
			INNER JOIN TA_Tbl_LevelDetails L  ON M.OrgLevel_Id = L.[Id]
			INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id  
			WHERE ys.IsActive=1 and M.Isdeleted=@Isdeleted			
		END
	ELSE IF (@TYPE=''P'')
		BEGIN
			SELECT L.[Name],M.MonthClosure_Month,M.MonthClosure_Year,
			CONVERT(VARCHAR,M.MonthClosure_StartDate,101) AS MonthClosure_StartDate,
			CONVERT(VARCHAR,M.MonthClosure_EndDate,101) AS MonthClosure_EndDate,
			CONVERT(VARCHAR,M.MonthClosure_ClosingDate,101) AS MonthClosure_ClosingDate 
			FROM TA_Tbl_MonthClosure M,TA_Tbl_LevelDetails L WHERE M.OrgLevel_Id = L.[Id] AND M.MonthClosure_Id=@MonthCloseID AND M.IsDeleted=@Isdeleted
		END
	ELSE If (@TYPE=''I'')
		BEGIN
			SELECT M.MonthClosure_Id, M.OrgLevel_Id,L.[Name],MonthClosure_Month,MonthClosure_Year,
			CONVERT(VARCHAR,MonthClosure_StartDate,101) AS MonthClosure_StartDate,
			CONVERT(VARCHAR,MonthClosure_EndDate,101) AS MonthClosure_EndDate,
			CONVERT(VARCHAR,MonthClosure_ClosingDate,101) AS MonthClosure_ClosingDate
			FROM TA_Tbl_MonthClosure M,TA_Tbl_LevelDetails L
			WHERE M.Isdeleted=@Isdeleted AND MonthClosure_Id=@MonthCloseID AND M.OrgLevel_Id = L.[Id]
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectMaxPayrollClosureDate]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectMaxPayrollClosureDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_SelectMaxPayrollClosureDate]
 AS
Begin
	SELECT Max(MonthClosure_EndDate) AS MonthClosure_EndDate FROM TA_Tbl_MonthClosure WHERE IsDeleted = 0 AND Process = ''P''
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDutyForTable]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_SelectManualEntryOnDutyForTable] null,null,''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',''16'',''0'',''1'',0
--Select * from TA_Tbl_OndutyEntry
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyForTable]  
      @Employee_FirstName nvarchar(50) = null,   
      @Employee_Code_Id nvarchar(15) = null,   
      @StartDate datetime = ''01/01/1900'',   
      @EndDate datetime = ''01/01/1900'' ,  
      @EmpSwipeCard varchar(15),  
      @UserGroupName NVARCHAR(250),  
      @UserLevels varchar(8000),  
      @GradeLevel nvarchar(20),  
      @EmpAutoId varchar(10),  
      @ParentID int  
AS   
begin
Set nocount on;
      create table #LevelRights(LevelId int)  
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
      declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](CAST(@EmpAutoId as int)) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](CAST(@EmpAutoId as int)) as EmpAutoId
      Declare @SqlQuery as varchar(MAX)  
      set @SqlQuery = ''''  
      Declare @SqlQuery2 as varchar(MAX)  
      set @SqlQuery2 = ''''  
		DECLARE @dateFormat as int
		DECLARE @TimeFormat as nvarchar(25)
		Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
      BEGIN  
       set @SqlQuery = @SqlQuery + ''select OD.Onduty_EmployeeId as EmployeeID, OD.Onduty_ID,
      case when ''+cast(@dateFormat as varchar(100))+''=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
            else CONVERT(VARCHAR, OD.Onduty_EntryDate, ''+cast(@dateFormat as varchar(100))+'')
            end 
       AS OndutyEntry_Date, 
       case when ''+cast(@dateFormat as varchar(100))+''=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
            else CONVERT(VARCHAR, OD.Onduty_FromDate, ''+cast(@dateFormat as varchar(100))+'')
            end 
       AS Onduty_FromDate ,
      CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Onduty_FromTime,0)), 114),0,6)
									ELSE Onduty_FromTime
									END Onduty_FromTime,
      case when ''+cast(@dateFormat as varchar(100))+''=106 then
            REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
            else CONVERT(VARCHAR, OD.Onduty_ToDate, ''+cast(@dateFormat as varchar(100))+'')
            end 
       AS Onduty_ToDate,
       CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN substring(CONVERT(varchar(8),DATEADD(minute,0,convert(datetime,Onduty_ToTime,0)), 114),0,6)
									ELSE Onduty_ToTime
									END Onduty_ToTime
      ,OD.Onduty_Reason,OD.Onduty_Status,E.Employee_FirstName + isnull(E.Employee_LastName,'''''''') AS Employee_Name,E.Employee_Id as EmpID ''  
            set @SqlQuery = @SqlQuery + ''FROM TA_Tbl_OndutyEntry OD ''  
            set @SqlQuery = @SqlQuery + '' INNER JOIN TA_Tbl_YearSetting ys on (ys.YearSettings_Id=OD.YearSettings_Id and isActive=1)''
            set @SqlQuery = @SqlQuery + ''INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=OD.Onduty_EmployeeId ''  
            set @SqlQuery = @SqlQuery + ''and OD.Isdeleted=0 and E.IsDeleted=0 ''    
            set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel el on E.Employee_Id = el.EmployeeId ''
            set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
            set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=ld.id ''
            set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''  
            set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''  
            set @SqlQuery =@SqlQuery +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''  
        set @SqlQuery = @SqlQuery + '' WHERE E.Employee_Code_Id=OD.Onduty_EmployeeId AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) ''
      set @SqlQuery = @SqlQuery + '' AND E.Employee_Status=1''  
       If not(@Employee_Code_Id = '''' or @Employee_Code_Id is null)  
       Begin  
        Set @SqlQuery2 = @SqlQuery2 + '' and E.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''  
       End  
       if(@isReportingto > 0)
            BEGIN
               set @SqlQuery2 = @SqlQuery2 + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
            If Not (@EmpSwipeCard = '''')    
            Begin    
            Set @SqlQuery2 = @SqlQuery2 + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
       End   
       If not(@Employee_FirstName = '''' or @Employee_FirstName is null)  
       Begin  
            Declare @Tempname nvarchar(200)
            set @Tempname= ''(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')''
            set @SqlQuery2 = @SqlQuery2 + '' and ''+ @Tempname +''= '''''' + cast(@Employee_FirstName as nvarchar(100)) + '''''')''   
       End  
       If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
       Begin  
        set @SqlQuery2 = @SqlQuery2 + '' AND (((CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
            set @SqlQuery2 = @SqlQuery2 + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@StartDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@EndDate as nvarchar(50))   + '''''', 102)))''
      End  
            set @SqlQuery2 = @SqlQuery2 + '' order by Onduty_ID desc''  
       Exec (@SqlQuery+@SqlQuery2)  
       drop table #LevelRights  
      END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDutyByID]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDutyByID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_SelectManualEntryOnDutyByID] 916, null,null,''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',''1'',''0'',''1'',1 
-- CReate by Gopinath on 6thJun2014 for Individual users 
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDutyByID]  
	@Employee_Id nvarchar(50),
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = ''01/01/1900'',   
	@EndDate datetime = ''01/01/1900'' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(max)  
	set @SqlQuery = ''''  
	Declare @SqlQuery2 as varchar(mAX)  
	set @SqlQuery2 = ''''  
		DECLARE @dateFormat as int
		SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	BEGIN  
	 set @SqlQuery = @SqlQuery + ''select M. ManualTimeEntry_Employee_Id as EmployeeID, M.ManualTimeEntry_Id,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_Date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_Date, 
	  case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.shift_date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.shift_date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS shiftDate, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_InDate ,
	 M.ManualTimeEntry_InTime,M.ManualTimeEntry_InPunchType,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_OutDate,
	 M.ManualTimeEntry_OutTime,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then ''''''+
	   +'''''' + cast(E.Employee_MiddleName as varchar(50)) else ''''''+   +'''''' end + SPACE(1) + E.Employee_LastName AS Employee_Name ''  
	 set @SqlQuery = @SqlQuery + ''FROM TA_Tbl_ManualTimeEntry as M ''  
	 set @SqlQuery = @SqlQuery + ''INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id ''  
	 set @SqlQuery = @SqlQuery + ''INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id ''  
	 set @SqlQuery = @SqlQuery + ''and M.Isdeleted=0 and E.IsDeleted=0 and ys.IsActive=1 ''  
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''  
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''  
	 set @SqlQuery =@SqlQuery +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''  
	 set @SqlQuery = @SqlQuery + '' WHERE E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) ''
	 set @SqlQuery = @SqlQuery + '' AND E.Employee_Status=1 AND M.ManualTimeEntry_Employee_Id='''''' + cast(@Employee_Id as nvarchar(100))  + '''''' AND M.IsOnDuty=1 '' 
	 If not(@Employee_Code_Id = '''' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + '' and E.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''  
	 End  
		If Not (@EmpSwipeCard = '''')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
	 End   
	 If not(@Employee_FirstName = '''' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= ''(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')''
		set @SqlQuery2 = @SqlQuery2 + '' and ''+ @Tempname +''= '''''' + cast(@Employee_FirstName as nvarchar(100)) + '''''')''   
	 End  
	 If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + '' and (M.ManualTimeEntry_InDate between convert(datetime,'''''' + cast(@StartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@EndDate as nvarchar(11)) + '''''',101)''  
	 End  
	 If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + '' or M.ManualTimeEntry_OutDate between convert(datetime,'''''' + cast(@StartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@EndDate as nvarchar(11)) + '''''',101))''  
	 End  
		set @SqlQuery2 = @SqlQuery2 + '' order by ManualTimeEntry_Date desc''  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
	END  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntryOnDuty]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntryOnDuty]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_SelectManualEntryOnDuty] null,null,''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',''1'',''0'',''1'',1  
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntryOnDuty]  
	@Employee_FirstName nvarchar(50) = null,   
	@Employee_Code_Id nvarchar(15) = null,   
	@StartDate datetime = ''01/01/1900'',   
	@EndDate datetime = ''01/01/1900'' ,  
	@EmpSwipeCard varchar(15),  
	@UserGroupName NVARCHAR(250),  
	@UserLevels varchar(8000),  
	@GradeLevel nvarchar(20),  
	@EmpAutoId varchar(10),  
	@ParentID int  
AS   
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	Declare @SqlQuery as varchar(8000)  
	set @SqlQuery = ''''  
	Declare @SqlQuery2 as varchar(8000)  
	set @SqlQuery2 = ''''  
	DECLARE @dateFormat as int
		DECLARE @TimeFormat as nvarchar(25)
		Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
		set @SqlQuery = @SqlQuery + ''select M. ManualTimeEntry_Employee_Id as EmployeeID, M.ManualTimeEntry_Id,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_Date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS OndutyEntry_Date, 
	  case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.shift_date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.shift_date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS shiftDate, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_InDate ,
	 CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,ManualTimeEntry_InTime,0)), 114) 
									ELSE SUBSTRING(ManualTimeEntry_InTime,13,5)+'''' '''' + SUBSTRING(ManualTimeEntry_InTime,18,2)									 
									END ManualTimeEntry_InTime,
	 M.ManualTimeEntry_InPunchType,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_OutDate,
	 CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,ManualTimeEntry_OutTime,0)), 114)
									ELSE SUBSTRING(ManualTimeEntry_OutTime,13,5)+'''' '''' + SUBSTRING(ManualTimeEntry_OutTime,18,2) 
									END ManualTimeEntry_OutTime
	 ,M.ManualTimeEntry_OutPunchType,M.ManualTimeEntry_Reason,M.ManualTimeEntry_Status,E.Employee_FirstName + case when E.Employee_MiddleName is not null then ''''''+
	   +'''''' + cast(E.Employee_MiddleName as varchar(50)) else ''''''+   +'''''' end + SPACE(1) + E.Employee_LastName AS Employee_Name,E.Employee_Id as EmpID ''  
	 set @SqlQuery = @SqlQuery + ''FROM TA_Tbl_ManualTimeEntry as M ''  
	 set @SqlQuery = @SqlQuery + ''INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id ''  
	 set @SqlQuery = @SqlQuery + ''INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id ''  
	 set @SqlQuery = @SqlQuery + ''and M.Isdeleted=0 and E.IsDeleted=0 and ys.IsActive=1 ''  
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''  
	 set @SqlQuery= @SqlQuery +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''  
	 set @SqlQuery =@SqlQuery +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''  
	 set @SqlQuery = @SqlQuery + '' WHERE E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id) ''
	 set @SqlQuery = @SqlQuery + '' AND E.Employee_Status=1 AND M.IsOnDuty=1''  
	 If not(@Employee_Code_Id = '''' or @Employee_Code_Id is null)  
	 Begin  
	  Set @SqlQuery2 = @SqlQuery2 + '' and E.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''  
	 End  
		If Not (@EmpSwipeCard = '''')    
		Begin    
		Set @SqlQuery2 = @SqlQuery2 + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
	 End   
	 If not(@Employee_FirstName = '''' or @Employee_FirstName is null)  
	 Begin  
		Declare @Tempname nvarchar(200)
		set @Tempname= ''(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')''
		set @SqlQuery2 = @SqlQuery2 + '' and ''+ @Tempname +''= '''''' + cast(@Employee_FirstName as nvarchar(100)) + '''''')''   
	 End  
	 If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + '' and (M.ManualTimeEntry_InDate between convert(datetime,'''''' + cast(@StartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@EndDate as nvarchar(11)) + '''''',101)''  
	 End  
	 If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
	 Begin  
	  set @SqlQuery2 = @SqlQuery2 + '' or M.ManualTimeEntry_OutDate between convert(datetime,'''''' + cast(@StartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@EndDate as nvarchar(11)) + '''''',101))''  
	 End  
		set @SqlQuery2 = @SqlQuery2 + '' order by ManualTimeEntry_Date desc''  
	 Exec (@SqlQuery+@SqlQuery2)  
	 drop table #LevelRights  
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectManualEntry]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectManualEntry]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_SelectManualEntry null,'''',''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',''1'',''0'',0,''ManualEntry'',1
-- Modified by K.Gopinath (01.02.2014), for Filter the OnDuty Entry
CREATE PROCEDURE [dbo].[Proc_TA_SelectManualEntry]
	@Employee_FirstName nvarchar(50) = null, 
	@Employee_Code_Id nvarchar(15) = null, 
	@StartDate datetime = ''01/01/1900'', 
	@EndDate datetime = ''01/01/1900'' ,
	@EmpSwipeCard varchar(10),
	@UserGroupName NVARCHAR(250),
	@UserLevels nvarchar(2000),
	@GradeLevel nvarchar(20),
	@ParentID int,
	@Type varchar(15),
	@LoginEmployeeAutoId int    
AS
BEGIN
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @Isdel as int
	SET @Isdel = 0
	Declare @SqlQuery as varchar(5000)
	set @SqlQuery = ''''
	DECLARE @dateFormat as int
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	declare @IndividualUserStatus int
	set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
	
	select	M.ManualTimeEntry_Employee_id as EmployeeCodeid, 
			M.ManualTimeEntry_Id,
			Convert(varchar,M.ManualTimeEntry_Date,101) AS ManualTimeEntry_Date,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_InDate,@dateFormat),'' '',''-'') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_InDate, @dateFormat) 
			end AS ManualTimeEntry_InDate,	
			M.ManualTimeEntry_InTime,
			case	when Latitude_value is not null and Longitude_value is not null then ''M - '' + M.ManualTimeEntry_InPunchType
					else M.ManualTimeEntry_InPunchType 
			end ManualTimeEntry_InPunchType,	
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, M.ManualTimeEntry_OutDate,@dateFormat),'' '',''-'') 
					else CONVERT(VARCHAR, M.ManualTimeEntry_OutDate, @dateFormat) 
			end AS ManualTimeEntry_OutDate,	
			M.ManualTimeEntry_OutTime,
			case	when Latitude_value is not null and Longitude_value is not null then ''M - '' + M.ManualTimeEntry_OutPunchType
					else M.ManualTimeEntry_OutPunchType 
			end ManualTimeEntry_OutPunchType,
			case	when Latitude_value is not null and Longitude_value is not null then Clock_Address 
					else M.ManualTimeEntry_Reason 
			end ManualTimeEntry_Reason,
			M.ManualTimeEntry_Status,
			E.Employee_FirstName + SPACE(1) + isnull(E.Employee_LastName,'''''''') AS Employee_Name,
			M.IsOnDuty,
			EntryType=case when M.IsImported=0 then ''M / D'' 
				 when M.IsImported=1 then ''I'' 
				 when M.IsImported=2 then ''Mo'' 
			end,
			ProcessStatus=case	when Clk_Process=''N'' then ''NP''
								when Clk_Process=''Y'' then ''P''	
						  END
	FROM TA_Tbl_ManualTimeEntry as M
	INNER JOIN  TA_Tbl_Employee as E ON  E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
	INNER JOIN TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id
	and M.Isdeleted=0 and E.IsDeleted=0 and E.Employee_Status=1 and ys.IsActive=1 
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId 
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid	
	where E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id AND M.IsOnDuty=0
	AND EDesig.EffectiveDate=(Select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id order by EffectiveDate desc) 
	AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)
	and ((@IndividualUserStatus  = 0) or (E.Employee_Id=@LoginEmployeeAutoId))
	and (@UserGroupName=''SuperAdmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
	and (@isReportingto = 0 or (E.Employee_ID IN (select * from #EmployeeIds)))
	and (isnull(@Employee_Code_Id,'''')='''' or E.Employee_Code_Id like cast(@Employee_Code_Id+''%'' as nvarchar(50)))
	and (isnull(@Employee_FirstName,'''')='''' or (E.Employee_FirstName + '' '' + isnull(E.Employee_LastName,'''') like cast(@Employee_FirstName+''%'' as nvarchar(100)))) 
	and ((@Type<>''Both'' and M.IsOnDuty != 1) or (@Type=''ODEntry'' and M.IsOnDuty = 1))
	and ((@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'') or (M.ManualTimeEntry_InDate between @StartDate and @EndDate))
	and ((@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'') or (M.ManualTimeEntry_OutDate between @StartDate and @EndDate))
	Order by M.ManualTimeentry_id desc
	Execute (@SqlQuery)
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name 		: Proc_TA_SelectLeaveTypesOfEmployees  
Description		: GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails  
Tables Included 	: TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType,ta_tbl_emp_LeavePolicy   
Created By		: Prabakaran  
Created On		: 08-Aug-07  
Modified By		:  
Modified On		: 
Proc_TA_SelectLeaveTypesOfEmployees 28 
*/  
Create     procedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees_Angler]  
@EmployeeId bigint  
as  
select distinct lp.LeaveType_Id,lt.LeaveType from TA_Tbl_emp_leavePolicyDetails lp  
inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id  
inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId
Where lp.empId=@EmployeeId and lp.IsDeleted=0 
--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
where 
--TA_Tbl_YearSetting.IsActive=1 and 
TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
order by lt.LeaveType
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesOfEmployees]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 		: Proc_TA_SelectLeaveTypesOfEmployees  2,''04/27/2012'',''04/27/2012''
Description		: GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails  
Tables Included 	: TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType,ta_tbl_emp_LeavePolicy   
Created By		: Prabakaran  
Created On		: 08-Aug-07  
Modified By		:  
Modified On		:  
*/  
CREATE     procedure [dbo].[Proc_TA_SelectLeaveTypesOfEmployees]  
(
@EmployeeId bigint,
@LeaveFromDate datetime,
@LeaveToDate datetime  
) 
as  
BEGIN 
    if((select IsActive from TA_Tbl_YearSetting where @LeaveToDate between FromDate and ToDate) = 1)
    BEGIn
		declare @LeaveFromDate_PolicyId int
		if exists (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
		inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
		where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
		and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		BEGIN
		    set @LeaveFromDate_PolicyId = (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
			and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		END
		ELSE
		BEGIN
		    set @LeaveFromDate_PolicyId = 0
		END
		declare @LeaveToDate_PolicyId int
		if exists(select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
		inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
		where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
		and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		BEGIN
		    set @LeaveToDate_PolicyId =(select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
			and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate))
		END
		ELSE
		BEGIN
		    set @LeaveToDate_PolicyId = 0
		END
		if((@LeaveFromDate_PolicyId = @LeaveToDate_PolicyId) or (@LeaveFromDate_PolicyId =0) or (@LeaveToDate_PolicyId=0))
		BEGIN
			select distinct lp.LeaveType_Id,lt.LeaveType,LeaveDescription=substring(lt.LeaveDescription,1,15)+'' (''+lt.LeaveType+'')'' from TA_Tbl_emp_leavePolicyDetails lp  
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id  
			inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId
			Where lp.empId=@EmployeeId and lp.IsDeleted=0 
			--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
						inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
						where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId 
						and (@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
						order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			order by lt.LeaveType
		END
		ELSE
		BEGIN
		 select 0
		END
	END
	ELSE
	BEGIN
			Declare @SuccessiveyearId int
			set @SuccessiveyearId = (select top 1 yearsettings_Id from ta_tbl_yearSetting where yearsettings_id> (select yearsettings_id from ta_tbl_yearSetting where isactive=1) order by yearsettings_id)
			Declare @SqlQuery varchar(8000)
			set @SqlQuery=''''
			set @SqlQuery = @SqlQuery + '' select distinct lp.LeaveType_Id,lt.LeaveType,LeaveDescription=substring(lt.LeaveDescription,1,15)+'''' rfec(''''+lt.LeaveType+'''')'''' from TA_Tbl_emp_leavePolicyDetails lp '' 
			set @SqlQuery = @SqlQuery + '' inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id ''  
			set @SqlQuery = @SqlQuery + '' inner join ta_tbl_emp_LeavePolicy elp on elp.EMP_LeavePolicyId=lp.Emp_LeavePolicyId ''
			set @SqlQuery = @SqlQuery + '' Where lp.empId='' + cast(@EmployeeId as varchar(25)) + '' and lp.IsDeleted=0 ''
			set @SqlQuery = @SqlQuery + '' and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy ''
			--and elp.FromDate<=CONVERT(NVARCHAR(20),getdate(),101) and elp.ToDate>=CONVERT(NVARCHAR(20),getdate(),101)
			--set @SqlQuery = @SqlQuery + '' and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy ''
			set @SqlQuery = @SqlQuery + '' inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid ''
			set @SqlQuery = @SqlQuery + '' where TA_Tbl_Emp_LeavePolicy.EmployeeId= '' + cast(@EmployeeId as varchar(25)) + '' and ''
			if((select count(*) from ta_tbl_emp_LeavePolicy where Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId)=0)
				begin
					set @SqlQuery = @SqlQuery + '' TA_Tbl_YearSetting.IsActive=1 ''
				end
			else if((select count(*) from ta_tbl_emp_LeavePolicy where Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId) >=1)
				begin
				set @SqlQuery = @SqlQuery + ''('''''' + cast(@LeaveFromDate as varchar(25)) + '''''' between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and ( '''''' + cast(@LeaveToDate as varchar(25)) + '''''' between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) '' 
				end
			set @SqlQuery = @SqlQuery + '' order by TA_Tbl_Emp_LeavePolicy.ToDate desc) ''
			--case (select count(*) from ta_tbl_emp_LeavePolicy where
			--			Employeeid=@EmployeeId and yearSettingId=@SuccessiveyearId) when 0 then  (TA_Tbl_YearSetting.IsActive=1) else  
			--			((@LeaveFromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@LeaveToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)) end
			--			order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			--order by lt.LeaveType ''
			exec(@SqlQuery)
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveTypesForEncashment]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveTypesForEncashment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_SelectLeaveTypesForEncashment
Description		:	GetLeaveTypeId from TA_TBL_Emp_LeavePolicyDetails
Tables Included	:	TA_TBL_Emp_LeavePolicyDetails,TA_Tbl_LeaveType, ta_tbl_leavePolicyDetails
					ta_tbl_emp_leavepolicy
Created By		:	Prabakaran
Created On		:	08-Aug-07
Modified By		:
Modified On		:
*/
CREATE    procedure [dbo].[Proc_TA_SelectLeaveTypesForEncashment]
@EmployeeId bigint
as
select distinct lp.LeaveType_Id,lt.LeaveType 
from TA_Tbl_emp_leavePolicyDetails lp
inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=lp.LeaveType_Id
inner join ta_tbl_leavePolicyDetails lpd   on lpd.Policy_Id=lp.Policy_ID and lpd.LeaveType_Id=lp.LeaveType_id
inner join  ta_tbl_emp_leavepolicy el on el.Emp_LeavePolicyId=lp.Emp_LeavePolicyId
Where lp.empId=@EmployeeId
and lp.IsDeleted=0 and lpd.Encashment=1 
--and (CONVERT(NVARCHAR(20),getdate(),101) between el.FromDate and el.Todate)
and el.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1 and TA_Tbl_Emp_LeavePolicy.EmployeeId=@EmployeeId order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_SelectLeavePolicyDetailsLeaveApplication 67,1,''07/04/2019'',''07/04/2019''
Description		:	Select Leave Policy Details of Employees Based on their Employee_Id
Tables Included	:	TA_Tbl_LeavePolicyDetails,Ta_Tbl_Emp_LeavePolicy
Created By		:	Prabakaran
Created On		:	11-Aug-07
Modified By		:
Modified On		:
*/
CREATE     PROCEDURE [dbo].[Proc_TA_SelectLeavePolicyDetailsLeaveApplication] 
@Employee_Id int,
@LeaveType_Id int,
@FromDate datetime,
@ToDate datetime
AS
BEGIN
	Declare @DateofJoining datetime
	Declare @currentMonth datetime
	Declare @FinancilaYearStartDate datetime
	Declare @difference_fy int
	Declare @difference_DJ int
	Declare @flag int
	IF(@FromDate>GETDATE() or @ToDate>GETDATE())
	BEGIN
		DECLARE @diff INT
		IF(@FromDate>GETDATE() and @ToDate>GETDATE())
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@ToDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
		ELSE IF(@FromDate>GETDATE())
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@FromDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
		ELSE
		BEGIN
			SET @diff=DATEDIFF(MONTH,GETDATE(),@ToDate)
			SET @currentMonth=DATEADD(MONTH,@diff,GETDATE())
		END
	END
	ELSE
	BEGIN	
		set @currentMonth=GETDATE()
	END
	IF(@currentMonth is null)
	BEGIN
		set @currentMonth=GETDATE()
	END
	--Newly Added This coding on 09-Jan-20120	
	Declare @CarryOverValue decimal(18,1)
	Declare @YearSettings_Id int
	select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate
	select @CarryOverValue=Carry_PrevYear from TA_Tbl_YearClosure where Year_SettingID=@YearSettings_Id	 and LeaveTypeID=@LeaveType_Id
	and Employee_Id=@Employee_Id	
	select @CarryOverValue=isnull(@CarryOverValue,0.0)+isnull(PreviousYearBalance,0.0) from ta_tbl_emp_LeaveTypedetails where EmployeeId=@Employee_Id and YearSettingsId=@YearSettings_Id and LeaveTypeID=@LeaveType_Id
	---- End of @CarryOverValue
	
	--if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
	--	BEGIN
	--		select @DateofJoining=
	--		CASE	WHEN DATEPART(d,DateOfJoining)>15 then
	--					CASE	WHEN DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))>15 then dateadd(d,0,DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))))
	--							ELSE DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))
	--					END 
	--				ELSE DATEADD(d,0,DATEADD(d,0,DateOfJoining))
	--		END
	--		from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
	--		select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
	--		set @difference_fy=DATEDIFF(month,@FinancilaYearStartDate,@currentMonth)+1
	--		set @difference_DJ=DATEDIFF(month,@DateofJoining,@currentMonth)+1
	--		select @flag=MIN(b.a) from
	--		(
	--			select	(@difference_DJ) as a union all
	--			select  (@difference_fy) as a
	--		)as b
	Declare @multiply int
	if((select IsActive from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate) = 1)
		BEGIN
			select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
			select @multiply=
			CASE	WHEN DATEPART(d,DateOfJoining)>15 then
						case	when DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)),getdate())+1
						end 
					else
						case	when DateOfJoining<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DateOfJoining,getdate())+1
						end 
			END
			from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
			Select *,Eligible=(@multiply*lpd.MaxDays_Month)+@CarryOverValue from Ta_TBl_LeavePolicyDetails lpd  
			inner join Ta_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1
			and (@FromDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate) and (@ToDate between TA_Tbl_Emp_LeavePolicy.FromDate and TA_Tbl_Emp_LeavePolicy.ToDate)
			and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		END
	ELSE
		BEGIN
			--select @DateofJoining=
			--CASE	WHEN DATEPART(d,DateOfJoining)>15 then 
			--			CASE	WHEN DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))>15 then dateadd(d,0,DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))))
			--					ELSE DATEADD(D,0,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)))
			--			END 
			--		ELSE DATEADD(d,0,DATEADD(d,0,DateOfJoining))
			--END
			--from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0
			--select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where @FromDate between FromDate and ToDate
			--set @difference_fy=DATEDIFF(month,@FinancilaYearStartDate,@currentMonth)+1
			--set @difference_DJ=DATEDIFF(month,@DateofJoining,@currentMonth)+1
			--select @flag=MIN(b.a) from
			--(
			--	select	(@difference_DJ) as a union all
			--	select  (@difference_fy) as a
			--)as b	
			select @FinancilaYearStartDate=FromDate from TA_Tbl_YearSetting where IsActive=1
			select @multiply=
			CASE	WHEN DATEPART(d,DateOfJoining)>15 then
						case	when DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining))<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DATEADD(d,-DATEPART(d,DateOfJoining)+1,dateadd(MONTH,1,DateOfJoining)),getdate())+1
						end 
					else
						case	when DateOfJoining<=@FinancilaYearStartDate then DATEDIFF(month,@FinancilaYearStartDate,getdate())+1
								else DATEDIFF(month,DateOfJoining,getdate())+1
						end 
			END 
			from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0	
			Select *,Eligible=(@multiply*lpd.MaxDays_Month)+@CarryOverValue from Ta_TBl_LeavePolicyDetails lpd
			inner join Ta_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id
			where elp.EmployeeId=@Employee_Id and lpd.LeaveType_Id=@LeaveType_Id 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid
			where TA_Tbl_YearSetting.IsActive=1
			and TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectHoliday]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Modified by	:	P.Prabakaran
Modified on	:	7-Feb-08*/
--Proc_TA_SelectHoliday ''P'',219,''superadmin'',0,1,0,0
CREATE   PROCEDURE [dbo].[Proc_TA_SelectHoliday]
(
	@Type char(1),
	@HolidayId int,
	@UserGroupName nvarchar(50),
	@LevelId int,
	@YearsettingsId int,
	@ParentId int,
	@EmployeeId int 
)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @dateFormat as int
	declare @EmployeeLevelId int
	Declare @LevelId1 int
	select @EmployeeLevelId=LevelId from ta_tbl_employeelevel where EmployeeId=@EmployeeId
	create table #LevelRights(LevelId int)	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	select @dateFormat =dateformat from dbo.Func_TA_GetDateTimeFormat()
	if(@Type=''A'')
	BEGIN
		if(@UserGroupName=''SuperAdmin'')
			begin 
				select  Holiday_Id,Htype=	case Holiday_Type	When ''Y'' Then ''Restricted Holiday'' 
															When ''G'' then ''Global Holiday'' 
											End,
						case when cast(@dateFormat as varchar(100))=106 then			
									REPLACE(CONVERT(VARCHAR, Holiday_FromDate,106),'' '',''-'')+'' ''  + ''To'' + '' '' + REPLACE(CONVERT(VARCHAR, Holiday_ToDate,106),'' '',''-'')
								else convert(varchar, Holiday_FromDate,@dateFormat) +'' ''  + ''To'' + '' '' + convert(varchar, Holiday_ToDate,@dateFormat) end ''HolidayDate'' ,
						Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,LevelId  
				FROM TA_Tbl_Holiday inner join Ta_tbl_Yearsetting
				on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id WHERE  Ta_tbl_Yearsetting.Isactive=1
			end
		else
			begin 
				select  Holiday_Id,Htype=case Holiday_Type	When ''Y'' Then ''Restricted Holiday''
															When ''G'' then ''Global Holiday'' End,
				case when cast(@dateFormat as varchar(100))=106 then			
				REPLACE(CONVERT(VARCHAR, Holiday_FromDate,106),'' '',''-'')+'' ''  + ''To'' + '' '' + REPLACE(CONVERT(VARCHAR, Holiday_ToDate,106),'' '',''-'')else 																
				convert(varchar, Holiday_FromDate,@dateFormat) +'' ''  + ''To'' + '' '' + convert(varchar, Holiday_ToDate,@dateFormat) end as  HolidayDate ,Holiday_Description,
				case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,
				LevelId  FROM TA_Tbl_Holiday
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id WHERE TA_Tbl_Holiday.Isdeleted=0 and 
				Ta_tbl_Yearsetting.Isactive=1
			end
	END
	SET @dateFormat = 101
	if(@Type=''P'')
	BEGIN
		select hct.Holiday_Id,Holiday_Type,
		convert(varchar, Holiday_FromDate,101 ) as  Holiday_FromDate,convert(varchar, Holiday_ToDate,101) as  Holiday_ToDate,
		Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,
		convert(varchar, Holiday_FromDate,101) as Holiday_FromDate,convert(varchar, Holiday_ToDate,101) as Holiday_ToDate,hct.LevelId,isnull(ta_tbl_levelDetails.name,''All'')as LevelName FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id 
		left join ta_tbl_levelDetails on TA_Tbl_Holiday.LevelId=ta_tbl_levelDetails.Id
		WHERE TA_Tbl_Holiday.Holiday_Id=@HolidayId  and Ta_tbl_Yearsetting.Isactive=1
	END
	if(@Type=''Y'' and  @HolidayId=-1)
	BEGIN
		select distinct Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,TA_Tbl_Holiday  .LevelId  FROM TA_Tbl_Holiday  
		inner join TA_Tbl_EmployeeLevel EL on EL.levelId=(TA_Tbl_Holiday.LevelId) or (TA_Tbl_Holiday.LevelId=0)
		inner join #LevelRights on #LevelRights.LevelId = EL.LevelId
		WHERE Isdeleted=0 and Holiday_Type=''Y'' and TA_Tbl_Holiday.yearsettings_Id=@YearsettingsId
		and EL.levelId= @EmployeeLevelId
	END
	if(@Type=''Y'' and  @HolidayId !=-1)
	BEGIN
		if(@UserGroupName=''SuperAdmin'')
			begin
				select hct.Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,hct.LevelId  FROM TA_Tbl_Holiday 
				inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id  WHERE Holiday_Type=''Y'' and TA_Tbl_Holiday.Holiday_Id=@HolidayId and Ta_tbl_Yearsetting.Isactive=1
			end
		else
			begin 
				select hct.Holiday_Id,Holiday_Type,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as  Holiday_ToDate ,Holiday_Description,case when TA_Tbl_Holiday.Isdeleted=1 then ''True'' else ''False'' end IsDeleted,convert(varchar, Holiday_FromDate,@dateFormat) as Holiday_FromDate,convert(varchar, Holiday_ToDate,@dateFormat) as Holiday_ToDate,hct.LevelId  FROM TA_Tbl_Holiday 
				inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
				inner join Ta_tbl_Yearsetting on Ta_tbl_Yearsetting.YearSettings_Id= TA_Tbl_Holiday.YearSettings_Id  WHERE Isdeleted=0 and Holiday_Type=''Y'' and TA_Tbl_Holiday.Holiday_Id=@HolidayId and Ta_tbl_Yearsetting.Isactive=1
			end
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_SelectLeaveApplicationDetailsByEmpId '''',''3'',''1'',''4/1/2020'',''5/18/2020'',''IndividualUsers'',0
CREATE PROCEDURE [dbo].[Proc_TA_SelectLeaveApplicationDetailsByEmpId]
(
@Employee_Id int,
@GradeLevel varchar(20),
@LevelRights varchar(8000), 
@LeaveApplicationStartDate datetime = ''01/01/1900'', 
@LeaveApplicationEndDate datetime = ''01/01/1900'',
@UserGroupName varchar(250),
@ParentId int
)    
AS    
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	DECLARE @CurrentDate AS NVARCHAR(30)
	Declare @LeaveSuccessiveFromDate datetime
	Declare @LeaveSuccessiveToDate datetime
	if( (select FromDate from ta_tbl_yearsetting where Isactive=1) is null)
		begin
			set @LeaveSuccessiveFromDate=''01/01/1900''
			set @LeaveSuccessiveToDate=''01/01/1900''				
		end
	else
		begin
			select @LeaveSuccessiveFromDate = FromDate from ta_tbl_yearsetting where Isactive=1
			if (@ParentId =0 )
				begin
					select @LeaveSuccessiveToDate= dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate) 
					from ta_tbl_yearsetting where Isactive=1 
				end
			else
				begin
					if exists(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@ParentId)
					begin
						select @LeaveSuccessiveToDate= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
						where companyId=@ParentId),ToDate) from ta_tbl_yearsetting where Isactive=1
					end
					else
					begin
						select @LeaveSuccessiveToDate= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
						where companyId=-1),ToDate) from ta_tbl_yearsetting where Isactive=1
					end
				end
		end
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)
	declare @sqlQuery2 as varchar(8000)
	declare @sqlQuery4 as varchar(8000)        
	set @sqlQuery = ''''      
	set @sqlQuery1 = ''''
	set @sqlQuery2 = ''''
	set @sqlQuery4 = ''''
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	SET @CurrentDate = GetDate()
	set @sqlQuery = @sqlQuery + '' select '''''''' as employeeid,'''' '''' as Employee_firstName,'''''''' as ''''name'''',la.LeaveApplication_Id,la.Employee_Id,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') end AS Leave_ApplicationDate,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
									+ '''' To '''' + 
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration,
									''
	set @sqlQuery = @sqlQuery + '' (lt.LeaveType + '''' / '''' + la.Type) as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''''Pending''''		then ''''Pen_16x16.png''''
			when status=''''Forwarded''''	then ''''Forw_52x52.png''''
			when status=''''Approved''''	then ''''Appr_52x52.png'''' 
			when status=''''Rejected''''	then ''''Rej_52x52.png'''' 
	end as image,
	case	when status=''''Pending''''		then ''''#DD4B39''''
			when status=''''Forwarded''''	then ''''#FF7F00''''
			when status=''''Approved''''	then ''''#00CC71'''' 
			when status=''''Rejected''''	then ''''#00CC74'''' 
	end as btnColor,isnull(lt.isWFH,0) as isWFH
	from TA_Tbl_LeaveApplication la ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_LeaveType lt on la.LeaveType_Id = lt.LeaveType_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id ''
	set @sqlQuery = @sqlQuery + '' where la.Employee_Id = '''''' + cast(@Employee_Id as nvarchar(100))  + '''''' and la.IsDeleted = 0 and la.type in (''''Leave'''',''''LOP'''') and (la.Leave_FromDate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101))''    
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin
			set @sqlQuery = @sqlQuery + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery = @sqlQuery + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''
	set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''
	set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level >='' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery1 = @sqlQuery1 + '' union ''    
	set @sqlQuery1 = @sqlQuery1 + '' select '''''''' as employeeid,'''''''' as Employee_firstName,'''''''' as ''''name'''',la.LeaveApplication_Id,la.Employee_Id,CONVERT(VARCHAR, la.Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') AS Leave_ApplicationDate,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
									+ '''' To '''' + 
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration,
	h.Holiday_Description as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''''Pending''''		then ''''Pen_16x16.png''''
			when status=''''Forwarded''''	then ''''Forw_52x52.png''''
			when status=''''Approved''''	then ''''Appr_52x52.png'''' 
			when status=''''Rejected''''	then ''''Rej_52x52.png'''' 
	end as image
	,
	case	when status=''''Pending''''		then ''''#DD4B39''''
			when status=''''Forwarded''''	then ''''#FF7F00''''
			when status=''''Approved''''	then ''''#00CC71'''' 
			when status=''''Rejected''''	then ''''#00CC74'''' 
	end as btnColor,0 as isWFH from TA_Tbl_Holiday h  ''  
	set @sqlQuery1 = @sqlQuery1 + '' inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id ''
	set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId ''
	set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id ''
	set @sqlQuery1 = @sqlQuery1 + '' where la.type=''''Restricted Holiday'''' and la.Employee_Id='''''' + cast(@Employee_Id as nvarchar(100))  + '''''' and la.Isdeleted=0 and (la.Leave_FromDate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101)) '' 
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin
			set @sqlQuery1 = @sqlQuery1 + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery1 = @sqlQuery1 + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''
	set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <= CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102)  order by EffectiveDate desc) '' 
	set @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level >= '' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery2 = @sqlQuery2 + '' union ''
	set @sqlQuery2 = @sqlQuery2 + '' select '''''''' as employeeid,'''''''' as Employee_firstName,'''''''' as ''''name'''',la.LeaveApplication_Id,la.Employee_Id,
	CONVERT(VARCHAR, la.Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') AS Leave_ApplicationDate,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
									+ '''' To '''' + 
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration,
	la.Type as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,
	la.NumberOfDays NumberOfDays,
	case	when status=''''Pending''''		then ''''Pen_16x16.png''''
			when status=''''Forwarded''''	then ''''Forw_52x52.png''''
			when status=''''Approved''''	then ''''Appr_52x52.png'''' 
			when status=''''Rejected''''	then ''''Rej_52x52.png'''' 
	end as image
	,
		case	when status=''''Pending''''		then ''''#f4c9c3''''
			when status=''''Forwarded''''	then ''''#ffd8b2''''
			when status=''''Approved''''	then ''''#b2efd4'''' 
			when status=''''Rejected''''	then ''''#00CC74'''' 
	end as btnColor,0 as isWFH from TA_Tbl_LeaveApplication la ''     
	set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeDesignation ON la.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel ON la.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_LevelDetails ON TA_Tbl_LevelDetails.id = TA_Tbl_EmployeeLevel.LevelId ''
	set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_LevelDetails.id ''
	set @sqlQuery2 = @sqlQuery2 + '' where la.Employee_Id='''''' + cast(@Employee_Id as nvarchar(100))  + '''''' and (la.type=''''Comp Off'''' or la.type=''''ESI'''') and  la.Isdeleted=0 and (la.Leave_FromDate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101))''
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin
			set @sqlQuery2 = @sqlQuery2 + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery2 = @sqlQuery2 + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''
	set @sqlQuery2 = @sqlQuery2 + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = la.Employee_Id and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''
	set @sqlQuery2 = @sqlQuery2 + '' AND TA_Tbl_Grade.Grade_Level >='' + cast(@GradeLevel as nvarchar(100))  
	set @sqlQuery4= @sqlQuery4 + '' Order by LeaveApplication_Id desc ''
	exec (@sqlQuery+@sqlQuery1+@sqlQuery2+@sqlQuery4)
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectLeaveApplicationDetails]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectLeaveApplicationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Modified By: Manikandan.R
-- Modified Date: 28-Feb-2012
-- Reason: Filter Condition is not working 
-- =============================================
--	Proc_TA_SelectLeaveApplicationDetails 1,''1'',null,null,''01/01/1900'',''01/01/1900'',null,''SuperAdmin'',0
--Proc_TA_SelectLeaveApplicationDetails @EmployeeID=2,@LevelRights=''1'',@Employee_Code_Id=NULL,@Employee_FirstName=NULL,@LeaveApplicationStartDate=''1900-01-01 00:00:00'',@LeaveApplicationEndDate=''1900-01-01 00:00:00'',@EmpSwipeCard=NULL,@UserGroupName=''Management'',@ParentId=0
CREATE  procedure [dbo].[Proc_TA_SelectLeaveApplicationDetails]
	@EmployeeID int,
	@LevelRights varchar(8000) = null, 
	@Employee_Code_Id nvarchar(50) = null, 
	@Employee_FirstName varchar(50) = null, 
	@LeaveApplicationStartDate datetime = ''01/01/1900'', 
	@LeaveApplicationEndDate datetime = ''01/01/1900'' ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentId int
as  
BEGIN
	SET NOCOUNT ON;
	declare @sqlQuery as varchar(8000)      
	declare @sqlQuery1 as varchar(8000)
	declare @sqlQuery2 as varchar(8000) 
	declare @sqlQuery3 as varchar(8000) 
	declare @sqlQuery4 as varchar(8000) 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	Declare @LeaveSuccessiveFromDate datetime
	Declare @LeaveSuccessiveToDate datetime
	Declare @Levelid int
	Declare @RowCount int
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	set @EmpSwipeCard=SUBSTRING(@EmpSwipeCard,0,len(@EmpSwipeCard)+1)	
	create table #SwipeCardNo(SwipecardNo varchar(25))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
    --select * from #EmployeeIds
	CREATE NONCLUSTERED INDEX [IDX_SwipecardNo] ON [dbo].[#SwipeCardNo]([SwipecardNo] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights]([LevelId] ASC) ON [PRIMARY]
	insert into #SwipeCardNo select value from dbo.split(@EmpSwipeCard,'','')
	select @RowCount=COUNT(SwipecardNo) from #SwipeCardNo
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId
	set @Levelid=@ParentId
	WHILE((SELECT Id from TA_tbl_LevelDetails where id=@Levelid) <> '''') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@Levelid) <> 1)
				begin	
					set @Levelid = (select parentId from TA_tbl_LevelDetails where id=@Levelid) 
				END
			ELSE
				BEGIN
					BREAK
				END
		END
	set @ParentId=@Levelid
	if((select FromDate from ta_tbl_yearsetting where Isactive=1) is null)
		begin
			set @LeaveSuccessiveFromDate=''01/01/1900''
			set @LeaveSuccessiveToDate=''01/01/1900''			
		end
	else
		begin
			select @LeaveSuccessiveFromDate = FromDate from ta_tbl_yearsetting where Isactive=1	
			if (@ParentId =0 )
				begin
					select @LeaveSuccessiveToDate=  isnull(dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate),0) 
					from ta_tbl_yearsetting where Isactive=1 
				end
			else
				begin
					select @LeaveSuccessiveToDate= isnull(dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings 
					where companyId=@ParentId),ToDate),0) from ta_tbl_yearsetting where Isactive=1
				end
		end
	set @sqlQuery = ''''      
	set @sqlQuery1 = ''''  
	set @sqlQuery2 = ''''
	set @sqlQuery3 = ''''
	set @sqlQuery4=''''
	set @sqlQuery = @sqlQuery + '' select Employee_Code_Id as employeeid,e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''') as Employee_FirstName,ld.name,
					la.LeaveApplication_Id,la.Employee_Id,case when ''+cast(@dateFormat as varchar(100))+''=106 then
					REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
					else CONVERT(VARCHAR, Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Leave_ApplicationDate,
					case when ''+cast(@dateFormat as varchar(100))+''=106 then
					REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
					else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
					+ '''' To '''' + 
					case when ''+cast(@dateFormat as varchar(100))+''=106 then
					REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
					else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration, ''
	set @sqlQuery = @sqlQuery + '' (lt.LeaveType + '''' / '''' + la.Type) as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,isnull(lt.isWFH,0) as isWFH ''   
	set @sqlQuery = @sqlQuery + '' from TA_Tbl_LeaveApplication la '' 
	set @sqlQuery = @sqlQuery + '' inner join  TA_Tbl_LeaveType lt  on la.LeaveType_Id = lt.LeaveType_Id '' 
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=ld.id ''
	if(@RowCount >0)
		begin
			set @sqlQuery = @sqlQuery + '' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo ''
		end
	set @sqlQuery = @sqlQuery + '' where la.IsDeleted = 0  and e.isdeleted=0 and la.type in (''''Leave'''',''''LOP'''') and la.Leave_FromDate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101)''
	set @sqlQuery = @sqlQuery + '' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) ''
	If not(@Employee_Code_Id = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and e.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''
		End
	 if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If not(@Employee_FirstName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (e.Employee_FirstName +'''' '''' + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + '''''')''
		End
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin
			set @sqlQuery = @sqlQuery + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery = @sqlQuery + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery1 = @sqlQuery1 + '' union ''
	set @sqlQuery1 = @sqlQuery1 + ''	select Employee_Code_Id as employeeid,e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''') as Employee_FirstName ,ld.name,la.LeaveApplication_Id,la.Employee_Id,
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Leave_ApplicationDate,
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
									+ '''' To '''' + 
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration,										h.Holiday_Description as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,0 as isWFH from TA_Tbl_Holiday h '' 
	set @sqlQuery1 = @sqlQuery1 + '' inner join  TA_Tbl_LeaveApplication la on la.LeaveType_Id=h.Holiday_Id ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id ''  
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=ld.id ''
	if(@RowCount >0)
		begin
			set @sqlQuery1 = @sqlQuery1 + '' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo ''
		end
	set @sqlQuery1 = @sqlQuery1 + '' where la.type=''''Restricted Holiday'''' and la.Isdeleted=0  and e.isdeleted=0''
	set @sqlQuery1 = @sqlQuery1 + '' and la.Leave_Fromdate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101) and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) ''
	If not(@Employee_Code_Id = '''')
		Begin
			set @sqlQuery1 = @sqlQuery1 + '' and e.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''
		End
	If not(@Employee_FirstName = '''')
		Begin
			set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_FirstName +'''' '''' + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + '''''')''
		End	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin		
			set @sqlQuery1 = @sqlQuery1 + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery1 = @sqlQuery1 + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery2 = @sqlQuery2 + '' union ''
	set @sqlQuery2 = @sqlQuery2 + '' select Employee_Code_Id as employeeid,e.Employee_FirstName  + '''' '''' + isnull(e.Employee_LastName,'''''''') as Employee_FirstName ,ld.name,la.LeaveApplication_Id,la.Employee_Id,
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Leave_ApplicationDate,
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end
									+ '''' To '''' + 
									case when ''+cast(@dateFormat as varchar(100))+''=106 then
									REPLACE(CONVERT(VARCHAR, Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
									else CONVERT(VARCHAR, Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Duration,la.Type ''
	set @sqlQuery2 = @sqlQuery2 + '' as LeaveType,la.Status as Status,la.Reason as Reason,la.Remarks as Remarks,NumberOfDays,0 as isWFH ''   
	set @sqlQuery2 = @sqlQuery2 + '' from TA_Tbl_LeaveApplication la ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_employee e on e.Employee_Id=la.Employee_Id ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join TA_Tbl_YearSetting ys on la.YearSettings_Id=ys.YearSettings_Id ''
	set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=ld.id ''
	if(@RowCount >0)
		begin
			set @sqlQuery2 = @sqlQuery2 + '' inner join #SwipeCardNo on #SwipeCardNo.SwipecardNo=e.swipecardNo ''
		end
	set @sqlQuery2 = @sqlQuery2 + '' where la.Isdeleted=0  and (la.type=''''Comp Off'''' or la.type=''''ESI'''') and  e.isdeleted=0  and la.Leave_FromDate >= convert(datetime,'''''' + cast(@LeaveSuccessiveFromDate as varchar(20)) + '''''',101) and la.Leave_ToDate <= convert(datetime, '''''' + cast(@LeaveSuccessiveToDate as varchar(20)) + '''''',101)''
	set @sqlQuery2 = @sqlQuery2 + '' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and  EffectiveDate <=  la.Leave_ApplicationDate order by EffectiveDate desc) ''
	If not(@Employee_Code_Id = '''')
		Begin
			set @sqlQuery2 = @sqlQuery2 + '' and e.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''
		End
	If not(@Employee_FirstName = '''')
		Begin
			set @sqlQuery2 = @sqlQuery2 + '' and (e.Employee_FirstName +'''' '''' + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + '''''')''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If not(@LeaveApplicationStartDate = ''01/01/1900'' and @LeaveApplicationEndDate = ''01/01/1900'')
		Begin		
			set @sqlQuery2 = @sqlQuery2 + '' and (la.Leave_FromDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101)''
			set @sqlQuery2 = @sqlQuery2 + '' or la.Leave_ToDate between convert(datetime,'''''' + cast(@LeaveApplicationStartDate as nvarchar(11)) + '''''', 101) and convert(datetime,'''''' + cast(@LeaveApplicationEndDate as nvarchar(11)) + '''''',101))''
		End
	set @sqlQuery3= @sqlQuery3 + '' Order by LeaveApplication_Id desc ''
	exec (@sqlQuery+@sqlQuery1+@sqlQuery2+@sqlQuery3)
	drop table #LevelRights
	drop table #SwipeCardNo
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGrades]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGrades]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Arun vinoth
-- ALTER  date: 18  July 07
-- Description:	Select All Grades
-- Modified By: Manikandan.R
-- Modified Date: 11-june-2012
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectGrades] 
	@Type CHAR,
	@GradeID INT,
	@userGroupName nvarchar(25)
AS	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Create table #TempGrade(Grade_ID int,Grade_Name nvarchar(100),Grade_Level int,Emp_ID int,Time_Stamp datetime,Isdeleted nvarchar(10),flag int)
	IF (@Type=''A'')
		IF(@userGroupName=''SuperAdmin'')
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted ,0  FROM TA_Tbl_Grade  order by Grade_Level
			END
		ELSE
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted ,0 FROM TA_Tbl_Grade where Isdeleted=0 order by Grade_Level
			END
	ELSE IF (@Type=''I'')
		IF(@userGroupName=''SuperAdmin'')
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted ,0 FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID order by Grade_Level
			END
		ELSE	
			BEGIN
				insert into #TempGrade
				SELECT Grade_ID, Grade_Name, Grade_Level, Emp_ID, Time_Stamp, case when IsDeleted=1 then ''True'' else ''False'' end IsDeleted ,0 FROM TA_Tbl_Grade WHERE Grade_ID=@GradeID order by Grade_Level
			END
	Update #TempGrade set flag=1 from #TempGrade TG inner join ta_tbl_Title T on TG.Grade_ID=T.GradeID --where T.Isdeleted=0
	Select * from #TempGrade 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectGradeLevel]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectGradeLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	Proc_TA_SelectGradeLevel 174
Created by	:	Prabakaran..P
Created  date	: 	26/Aug/08
Modified by	:	
Modified on	:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_SelectGradeLevel]
(
    	@EmpAutoId varchar(20)
)
AS      
BEGIN  
select Grade_Level from ta_tbl_grade G
Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
where eDesig.EffectiveDate =(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Proc_TA_SelectEncashmentDetailsSuperAdmin ''1'','''','''',''01/01/2007'',''12/23/2012'' ,'''',''Superadmin'',0 
*/  
CREATE procedure [dbo].[Proc_TA_SelectEncashmentDetailsSuperAdmin]  
@Employee_ID int,
@LevelRights varchar(8000) = null,   
@Employee_Code_Id nvarchar(50) = null,   
@Employee_FirstName varchar(50) = null,   
@StartDate datetime = ''01/01/1900'',   
@EndDate datetime = ''01/01/1900'',
@EmpSwipeCard varchar(20),
@UserGroupName varchar(250),
@ParentID int    
as    
BEGIN 
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	declare @SqlQuery as varchar(8000)   
	set @SqlQuery = ''''
	set @SqlQuery = @SqlQuery + ''select (e.Employee_FirstName + '''' '''' +  isnull(e.Employee_LastName,'''' '''')) as EmployeeName,e.Employee_Code_Id,ld.name,Et.EncashmentId,Et.EmployeeId,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, Et.DateOfEncashment,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, Et.DateOfEncashment, ''+cast(@dateFormat as varchar(100))+'') end	AS DateOfEncashment,
	lt.LeaveType as LeaveType,Et.NumberOfDays as NumberOfDays,Et.Reason as Reason,lt.LeaveType_Id as LeaveTypeId ''  
	set @SqlQuery = @SqlQuery + '' from TA_Tbl_Encashment Et ''  
	set @SqlQuery = @SqlQuery + '' inner join TA_Tbl_LeaveType lt on Et.LeaveTypeId = lt.LeaveType_Id ''  
	set @SqlQuery = @SqlQuery + '' inner join Ta_tbl_employee e on e.Employee_Id=Et.EmployeeId ''  
	set @SqlQuery = @SqlQuery + '' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId ''  
	set @SqlQuery = @SqlQuery + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''  
	set @SqlQuery = @SqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=Et.YearSettingId '' 
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=ld.id ''  
	set @SqlQuery = @SqlQuery + '' where ys.IsActive=1 and Et.IsDeleted = 0  and e.isdeleted=0 and ''  
	set @SqlQuery = @SqlQuery + '' el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  Et.DateOfEncashment order by EffectiveDate desc) ''  
	If not(@Employee_Code_Id = '''' or @Employee_Code_Id is null)  
		Begin  
			Set @SqlQuery = @SqlQuery + '' and e.Employee_Code_Id = '''''' + cast(@Employee_Code_Id as nvarchar(50)) + ''''''''  
		End  
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + '' And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If not(@Employee_FirstName = '''' or @Employee_FirstName is null)  
		Begin  
		Set @SqlQuery = @SqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + '''''')''
			--Set @SqlQuery = @SqlQuery + '' and e.Employee_FirstName like '''''' + cast(@Employee_FirstName+''%'' as nvarchar(100)) + ''''''''  
		End  
	If not(@StartDate = ''01/01/1900'' and @EndDate = ''01/01/1900'')  
		Begin  
			set @SqlQuery = @SqlQuery + '' and Et.DateOfEncashment between convert(datetime,'''''' + cast(@StartDate as nvarchar(11)) + '' 00:00:00.000'''', 101) and convert(datetime,'''''' + cast(@EndDate as nvarchar(11)) + '' 23:59:59.000'''',101)''  
		End  
	Execute (@SqlQuery)  
	drop table #LevelRights  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : Proc_TA_SelectEncashmentDetailsByEmpId 15,3,''1'',''NormalUser'',0   
Description : select Encashment details    
Tables Included : TA_Tbl_Encashment     
Created By : Prabakaran    
Created On : 28-Nov-07    
Modified By :     
Modified On :     
*/    
CREATE      procedure [dbo].[Proc_TA_SelectEncashmentDetailsByEmpId]      
@EmployeeId bigint,    
@GradeLevel varchar(20),    
@LevelRights varchar(2000),
@UserGroupName varchar(250),
@ParentID int      
as    
BEGIN    
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as varchar(8000)          
	set @sqlQuery = ''''          
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	set @sqlQuery = @sqlQuery + '' select (e.Employee_FirstName + '''' '''' +  isnull(e.Employee_LastName,'''' '''')) as EmployeeName,e.Employee_Code_Id,ld.name,Et.EncashmentId,Et.EmployeeId, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, Et.DateOfEncashment,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, Et.DateOfEncashment, ''+cast(@dateFormat as varchar(100))+'') end	AS DateOfEncashment,lt.LeaveType as LeaveType,Et.NumberOfDays as NumberOfDays,Et.Reason as Reason,lt.LeaveType_Id as LeaveTypeId ''    
	set @sqlQuery = @sqlQuery + '' from TA_Tbl_Encashment Et ''     
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_LeaveType lt on Et.LeaveTypeId = lt.LeaveType_Id ''    
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_employee e on e.Employee_Id=Et.EmployeeId ''    
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel el on e.Employee_Id = el.EmployeeId ''    
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation eDesig ON Et.EmployeeId = eDesig.EmployeeId ''    
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id  ''    
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=eDesig.DesignationId ''    
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''    
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=Et.YearSettingId ''    
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=LD.id ''    
	set @sqlQuery = @sqlQuery + '' where ys.IsActive=1 and Et.IsDeleted = 0  and e.isdeleted=0 and Et.EmployeeId='' + cast(@EmployeeId as nvarchar(50)) +'' and ''    
	set @sqlQuery = @sqlQuery + '' el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e.Employee_Id and EffectiveDate <=  Et.DateOfEncashment order by EffectiveDate desc) ''    
	set @sqlQuery = @sqlQuery + '' and eDesig.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = Et.EmployeeId and EffectiveDate <=CONVERT(DATETIME,'''''' + cast(getdate() as nvarchar(50)) + '''''', 102) order by EffectiveDate desc) ''    
	set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level >='' + cast(@GradeLevel as nvarchar(100))      
	exec (@sqlQuery) 
	drop table #LevelRights   
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmpName]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmpName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_SelectEmpName ''100000000000001'',''SuperAdmin'',''0'',''0,21'',0                           						
CREATE     PROCEDURE [dbo].[Proc_TA_SelectEmpName] 
(
	@Employee_ID int,
	@EmpCode varchar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@level varchar(2000),
	@ParentID int,
	@isFrom nvarchar(50)
)
AS    
BEGIN  
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000) 
	DECLARE @Isdel int  
	SET @Isdel=0  
	SET @sql =''Select Employee_Id,Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''''''') AS ''''Employee Name'''',TA_Tbl_Employee.CompOff_Eligible,Emailid '' 
	SET @sql = @sql + '' From TA_Tbl_Employee INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	SET @sql = @sql + '' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId ''
	SET @sql = @sql + '' WHERE Employee_Code_Id='''''' + @EmpCode + '''''' ''  
	SET @sql = @sql + '' AND  TA_Tbl_Employee.Employee_Code_Id<>''''18000000''''  AND TA_Tbl_Employee.IsDeleted='''''' + cast(@Isdel as nvarchar(20)) + ''''''  AND TA_Tbl_Employee.Employee_Status=''''1'''' ''
	SET @sql = @sql + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
    if(@isFrom=''CompOff'')
		begin
			set @sql = @sql + '' and TA_Tbl_Employee.CompOff_Eligible=1 and TA_Tbl_Employee.OT_Eligible=0 ''  
		end
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	exec(@sql)
	drop table #LevelRights
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--Proc_TA_SelectEmployeesBasedOnRoutes 1,''04/29/2011''
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeesBasedOnRoutes]
(
   @RouteId int,
   @InDate varchar(15),
   @LoginEmployeeId int,
   @Parameter varchar(10)
)
AS
BEGIN
create table #TempProcessedData(Employee_Code_Id varchar(20))
insert into #TempProcessedData select Employee_Code_Id from TA_Tbl_ProcessedData
where Attendance = ''Present'' and Date = @InDate
if(@Parameter = ''Select'')
	BEGIN
		select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + '' '' + emp.Employee_LastName) as EmployeeName from TA_Tbl_Employee emp,
		TA_Tbl_RouteMaster rm,
		#TempProcessedData p 
		where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and rm.Id = @RouteId
	END
else if(@Parameter = ''Add'')
	BEGIN
        insert into TA_Tbl_TempShiftAllocation 
        select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + '' '' + emp.Employee_LastName),@LoginEmployeeId from TA_Tbl_Employee emp,
		TA_Tbl_RouteMaster rm,#TempProcessedData p 
		where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and rm.Id = @RouteId
		select * from TA_Tbl_TempShiftAllocation where LoginEmployeeId=@LoginEmployeeId
	END
--where emp.Bus_Id = rm.Id and p.Employee_Code_Id = emp.SwipeCardNo and p.Attendance = ''Present'' and rm.Id = @RouteId and p.Date = @InDate
--select emp.Employee_Id,emp.Employee_Code_Id,(emp.Employee_FirstName + '' '' + emp.Employee_LastName) as EmployeeName from TA_Tbl_Employee emp
--inner join TA_Tbl_RouteMaster rm on emp.Bus_Id = rm.Id and rm.Id = @RouteId
--inner join (select * from TA_Tbl_ProcessedData where Attendance = ''Present'' and Date=''04/29/2011'') as p on p.Employee_Code_Id = emp.SwipeCardNo
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForShiftAlloc]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	[Proc_TA_SelectEmployeeForShiftAlloc] ''26'',''SuperAdmin'',0,null,26,'''',0,0,1
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
Modified by	:	A.Amsaveni on 28/09/2013 to give a space between Employee firstname and lastname
Modified by	:	Manjula.P on 20-Aug-2014 for searching by employee type and employee category @EmpCategoryShift,@EmpTypeShift
select * from TA_Tbl_EmployeeLevel
*/
CREATE     PROCEDURE [dbo].[Proc_TA_SelectEmployeeForShiftAlloc]
(
@Employee_ID int,
@LevelId varchar(8000),
@UserGroupName varchar(250),
@GradeLevel varchar(20)	,
@EmployeeCodeID as varchar(max),
@ParentId int,
@EmployeeName varchar(max),
@EmpCategoryShift int=0,
@EmpTypeShift int=0,
@Religion int
)      
AS      
BEGIN     
	SET NOCOUNT ON;
	Declare @RowCountEmployeeID int
	Declare @RowCountEmployeeName int
	DECLARE @sql AS VARCHAR(8000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '''')
		begin
			if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = '','')
				begin
					set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
				end	
			insert into #EmployeeID	select value from dbo.split(@EmployeeCodeID,'','')
			select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = '','')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end
			insert into #EmployeeName select value from dbo.split(@EmployeeName,'','')
			select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName
		end
	SET @CurrentDate = GetDate()
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId],[LevelId],[EffectiveDate] ASC
	) ON [PRIMARY]	
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
	IF(@LevelId = '''')
		BEGIN
			SET @LevelId = ''0''
		END
	SET @sql =''SELECT distinct Employee_Id,Employee_Code_Id,Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''' '''') AS ''''Employee Name'''' FROM TA_Tbl_Employee''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''
	SET @sql = @sql + '' inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=TA_Tbl_Employee.Employee_Id 
						inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId ''
	SET @sql = @sql + '' inner join ta_tbl_employeecategory EC on EC.EmployeeId=TA_Tbl_Employee.Employee_Id 
						inner join ta_tbl_category C on C.CategoryId=EC.CategoryId ''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	SET @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	SET @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	if(@RowCountEmployeeID >0)
		begin
			SET @sql = @sql + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		end
	if(@RowCountEmployeeName >0)
		begin
			SET @sql = @sql + '' Inner join #EmployeeName on #EmployeeName.EmployeeName=TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''''''') ''
		end
	SET @sql = @sql + '' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 AND Employee_Firstname<>''''Administrator''''''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	IF(@EmpCategoryShift>0)
		BEGIN
			SET @sql=@sql+'' AND C.CategoryId = ''+cast(@EmpCategoryShift as varchar(50))+'' ''
		END
	IF(@EmpTypeShift>0)
		BEGIN
			SET @sql=@sql+'' AND TP.TypeId = ''+cast(@EmpTypeShift as varchar(50))+'' ''
		END    
	IF(@Religion>1)
		BEGIN
			SET @sql=@sql+'' AND TA_Tbl_Employee.Religion = ''+cast(@Religion as varchar(50))+'' ''
		END
	set @sql=@sql+'' ORDER BY Employee_Code_Id ''
	EXEC(@sql)          
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForPopup]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForPopup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	Proc_TA_SelectEmployeeForPopup ''10'',''SuperAdmin'',''0'',10,''100'','''',0,0
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForPopup]
(
	@Employee_ID int,
	@LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@ParentId int,
	@EmployeeId varchar(Max),
	@EmployeeName varchar(Max),
	@EmpCategoryShift int=0,
	@EmpTypeShift int=0,
	@isFrom nvarchar(100)
)
AS
BEGIN      
	-- SET NOCOUNT ON added to prevent extra result sets from      
	-- interfering with SELECT statements.      
	SET NOCOUNT ON;      
	DECLARE @sql AS VARCHAR(5000)      
	DECLARE @CurrentDate AS NVARCHAR(30)
	SET @CurrentDate = GetDate()
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId] ,[EmployeeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
	group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @CurrentDate,@EmployeeId,''''	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @CurrentDate,@EmployeeId,@EmpTypeShift	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @CurrentDate,@EmployeeId,@EmpCategoryShift
	create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			if(SUBSTRING(@EmployeeId,LEN(@EmployeeId),len(@EmployeeId)) = '','')
				begin
					set @EmployeeId=SUBSTRING(@EmployeeId,0,len(@EmployeeId))
				end	
			insert into #EmployeeID	select value from dbo.split(@EmployeeId,'','')
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = '','')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end
			insert into #EmployeeName select value from dbo.split(@EmployeeName,'','')
		end
	IF(@LevelId = '''')
	BEGIN
		SET @LevelId = ''0''
	END
	SET @sql =''SELECT E.Employee_Id,E.Employee_Code_Id,Employee_FirstName + '''' '''' +  isnull(Employee_LastName,'''''''') AS ''''Employee Name'''',
	CompOff_Eligible FROM TA_Tbl_Employee E''
	SET @sql = @sql + ''	INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id ''	
	SET @sql = @sql + ''	INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id ''
	SET @sql = @sql + ''	INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sql = @sql + ''	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''	
	SET @sql = @sql + ''	INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id ''
	SET @sql = @sql + ''	INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id ''
	SET @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	if(@EmployeeId is not null and @EmployeeId <> '''')
	begin
		SET @sql = @sql + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=E.Employee_Code_Id ''
	end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			SET @sql = @sql + '' Inner join #EmployeeName on #EmployeeName.EmployeeName=E.Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''''''') ''
		end
	SET @sql = @sql + '' WHERE E.Isdeleted=0 AND E.Employee_Status=1 ''
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
	end
	if(@isFrom=''CompOff'')
		begin
			set @sql = @sql + '' AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@EmployeeName is not null and @EmployeeName <> '''')
	begin
		SET @sql = @sql + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	SET @sql = @sql + '' AND Employee_Firstname<>''''Administrator'''' ORDER BY Employee_Code_Id''     
	EXEC(@sql)          
	--Remove the temporary tables here  
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeForGroupPolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
 -- Proc_TA_SelectEmployeeForGroupPolicy 1,''50'',''SuperAdmin'',''0'',null,''Leave Policy VCIL  Corp'',50,'''',''''
 -- select * from testleavepolicy
 -- Delete from testleavepolicy

CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeForGroupPolicy]          
/****************************************************************************************/                
-- Name    : 
--	Proc_TA_SelectEmployeeForGroupPolicy 1,''SuperAdmin'',0,'''',''Count factor Leave Policy'',1
-- Desc    : To get the enties in TA_Tbl_Employee ''               
-- Company : Angler Technologies                
-- Author  : P.Santhosh Raj                
-- Date    : 24-Mar-2009                
-- Update History :   [Date Updated By (Initials) Reason]                
/****************************************************************************************/               
	(
	 @Employee_ID int,
	 @LevelId varchar(1000)   = Null,          
	 @UserGroupName varchar(250)  = Null,          
	 @GradeLevel varchar(20)  = Null,           
	 @Designation varchar(20)  = Null, 
	 @LeavePolicyName varchar(100)  = Null,
	 @ParentId int,
	 @EmployeeID VarChar(max),
	 @EmployeeName varchar(max)
	)	                
AS   
BEGIN                
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @sql AS VARCHAR(5000)
	DECLARE @CurrentDate AS NVARCHAR(30)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@EmployeeId)
		end	
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	SET @CurrentDate = GetDate()          
	SET @sql =''SELECT Distinct (Employee_Id),Employee_Code_Id,Employee_FirstName + '''' '''' +  isnull(Employee_LastName,'''''''') AS ''''Employee Name'''',convert(nvarchar(20),DateOfJoining,101) as DateOfJoining,TA_Tbl_EmployeeLevel.LevelID,Categoryid,typeid,Ta_tbl_Employee.Religion FROM TA_Tbl_Employee''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
	SET @sql = @sql + '' inner JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''
	SET @sql = @sql + '' inner JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	SET @sql = @sql + '' inner JOIN TA_Tbl_EmployeeCategory on TA_Tbl_EmployeeCategory.EmployeeId=TA_Tbl_Employee.Employee_Id''
	SET @sql = @sql + '' inner JOIN TA_Tbl_EmployeeType on TA_Tbl_EmployeeType.EmployeeId=TA_Tbl_Employee.Employee_Id''
	SET @sql = @sql + '' inner  JOIN #LevelRights on #LevelRights.LevelId=TA_Tbl_EmployeeLevel.LevelId''                  
	SET @sql = @sql + '' left outer  JOIN TA_Tbl_Religion R ON TA_Tbl_Employee.Religion=R.ID''    
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sql = @sql + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sql = @sql + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End	
	SET @sql = @sql + '' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 ''
	if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	SET @sql = @sql + '' AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,'''''' + @CurrentDate + '''''', 102) order by EffectiveDate desc) AND''          
	SET @sql = @sql + '' TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,'''''' + @CurrentDate + '''''', 102) order by EffectiveDate desc) ''           
	if (@LeavePolicyName!='''' and @LeavePolicyName is not null)              
		Begin
			if((select EmployeeCategory from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin
					set @sql=@sql+''and ta_tbl_employee.employee_id in(select Employeeid from TA_Tbl_EmployeeCategory where Categoryid=(
					select EmployeeCategory from ta_tbl_leavepolicy where policyname=''''''+ @LeavePolicyName+''''''''+''))'' 
				end
			if((select EmployeeType from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin
					set @sql=@sql+''and ta_tbl_employee.employee_id in(select Employeeid from TA_Tbl_EmployeeType where Typeid=(
					select EmployeeType from ta_tbl_leavepolicy where policyname=''''''+ @LeavePolicyName+''''''''+''))'' 
				end
			if((select Religion from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=0)
				begin	
					set @sql=@sql+''and ta_tbl_employee.Religion in(select Religion from ta_tbl_leavepolicy where policyname=''''''+ @LeavePolicyName+''''''''+'')'' 
				end
			if((select Gender from ta_tbl_leavepolicy where policyname=@LeavePolicyName)!=''Both'')
				begin	
					set @sql=@sql+''and ta_tbl_employee.Gender in(select Gender from ta_tbl_leavepolicy where policyname=''''''+ @LeavePolicyName+''''''''+'')'' 
				end
		End
	if (@Designation!='''' and @Designation is not null)              
		Begin              
			set @sql= @sql +'' AND TA_Tbl_EmployeeDesignation.DesignationId = ''''''+ @Designation+ ''''''''                
		End        
	if(@UserGroupName<>''SuperAdmin'')          
		begin          
			SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''          
		end
	SET @sql = @sql + '' AND Employee_Firstname<>''''Administrator'''' ORDER BY 1''
	EXEC(@sql) 
	drop table #LevelRights                  
END 



' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_SelectEmployeeFlexi]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_SelectEmployeeFlexi]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		senthil
-- ALTER  date: 04August08   
-- Modified By	:	Prabakaran.P
-- Modified On	:	26-Mar-09
-- Proc_Ta_SelectEmployeeFlexi '''',''11/12/2014'','''','''',''1'',0,0,3,''SuperAdmin'',3,1
-- Description:	Report Employee Details
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_SelectEmployeeFlexi]
	@fromDat varchar(50),
	@ToDat varchar(50),
	@EmployeeId varchar(100),
	--@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@Flexi int, -- 1 - get flexi , 0- get non flexi , 3- both
	--@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(250),
	@ParentId int,
	@isFlexible int,
	@EmpAutoID int
	--@GradeLevel varchar(20)	
AS
BEGIN
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @CompanyId int
	set @CompanyId =@ParentId
	WHILE((SELECT Id from TA_tbl_LevelDetails where id=@CompanyId) <> '''') 
		BEGIN 
			if((select levelID from TA_tbl_LevelDetails where Id=@CompanyId ) <> 1)
				begin	
					set @CompanyId = (select parentId from TA_tbl_LevelDetails where id=@CompanyId ) 
				END
			ELSE
				BEGIN
					BREAK
				END
		END	
	Declare @intFlexibeEnabled int
	Declare @FlexibleFlag int
	set @FlexibleFlag=(select FlexibleFlag from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	set @intFlexibeEnabled=(select IsFlexible from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Basic Pay Indexes
--/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
--CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
--(
--	[EffectiveDate] ASC
--) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
/*
select * from #EmpLevel
select * from #EmpDesignation
select * from #EmpType
select * from #EmpCategory
select * from #EmpPay
*/
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		declare @sqlQuery as varchar(8000)
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT TA_Tbl_Employee.isFlexible, replace(dept.name,''''&amp;'''',''''&'''') as department, dbo.TA_Tbl_Employee.Employee_code_Id as employee_id,dbo.TA_Tbl_Employee.Employee_Id as empAutoId,status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
		set @sqlQuery = @sqlQuery + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname,convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as dateOfBirth,dbo.TA_Tbl_Employee.Nationality,''
		set @sqlQuery = @sqlQuery + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, Convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as dateJoin''		
		set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_Employee ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		--set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''	
		--set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeePay ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeePay.EmployeeId ''	
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
		--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''') ''
--		if(@UserGroupName<>''SuperAdmin'')
--		begin
--		set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
--		end
		if not(@fromDat='''')		
		begin
		set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''		
		End
		if not (@ToDat='''')
		begin
		set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 		
		end
		if not(@EmployeeName='''')
		begin
			set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end
		if not (@EmployeeId='''')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
		end
		if not (@EmployeeCategory=0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))
		end
		if not (@EmployeeType=0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))
		end
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		--if not (@Flexi=3)
		--Begin
		--		set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.isFlexible = '' + cast(@Flexi as nvarchar(8))
		--End
		if(@intFlexibeEnabled=1)
			begin
				if(@FlexibleFlag=2)
					begin
						if (@isFlexible=1)
						Begin
								set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.isFlexible = 1''
						End
						if (@isFlexible=2)
						Begin
								set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.isFlexible = 0''
						End
					end
			end
		set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_Employee.Employee_code_Id ''
	exec(@sqlQuery)
--Remove the temporary tables here   
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
--drop table #EmpPay
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeEmailId]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeEmailId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_SelectEmployeeEmailId ''0'','''','''',''SuperAdmin'',''0''
CREATE    PROCEDURE [dbo].[Proc_TA_SelectEmployeeEmailId]
(	
	@EmployeeName varchar(100),
	@EmployeeCodeId varchar(25),
 	@UserGroupName varchar(20),
	@GradeLevel varchar(20),
	@ParentId int	
)      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
Declare @RowCountEmployeeID int
 Declare @RowCountEmployeeName int
    create table #EmployeeID(EmployeeID varchar(25))
	create table #EmployeeName(EmployeeName varchar(500))
	if(@EmployeeCodeID is not null and @EmployeeCodeID <> '''')
		begin
			if(SUBSTRING(@EmployeeCodeID,LEN(@EmployeeCodeID),len(@EmployeeCodeID)) = '','')
			begin
				set @EmployeeCodeID=SUBSTRING(@EmployeeCodeID,0,len(@EmployeeCodeID))
			end
				insert into #EmployeeID
				select value from dbo.split(@EmployeeCodeID,'','')
				select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID
	    end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = '','')
				begin
					set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))
				end 
				insert into #EmployeeName
				select value from dbo.split(@EmployeeName,'','')
				--select * from #EmployeeName
				select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName
		end
 DECLARE @sql AS VARCHAR(8000)      
 DECLARE @CurrentDate AS NVARCHAR(30)
 SET @CurrentDate = GetDate()
 --Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
 --SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end + Employee_LastName AS ''Employee Name'' FROM TA_Tbl_Employee WHERE LevelID in(@LevelId) and Isdeleted=1      
 SET @sql =''SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '''' '''' + cast(Employee_MiddleName as varchar(50)) else '''' '''' end +  isnull(Employee_LastName,'''''''') AS ''''Employee Name'''',''
 SET @sql = @sql + '' Employee_Code_Id + '''' - '''' + Employee_FirstName + case when Employee_MiddleName is not null then '''' '''' + cast(Employee_MiddleName as varchar(50)) else '''' '''' end +  isnull(Employee_LastName,'''''''')  AS ''''EmpName'''',EmailId,TitleName FROM TA_Tbl_Employee''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
SET @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
SET @sql = @sql + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
SET @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	if(@RowCountEmployeeID >0)
		begin
			SET @sql = @sql + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		end
	if(@RowCountEmployeeName >0)
		begin
			SET @sql = @sql + '' Inner join #EmployeeName on #EmployeeName.EmployeeName=TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(Employee_LastName,'''''''') ''
		end
 SET @sql = @sql + '' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1''
--IF(@EmployeeCodeId <> '''')
--	BEGIN
--		--SET @sql = @sql + '' AND Employee_Code_Id LIKE '''''' + @EmployeeCodeId + ''%''''''
--		SET @sql = @sql + '' AND Employee_Code_Id = '''''' + @EmployeeCodeId + '''''' ''
--	END
--IF(@EmployeeName <> '''')
--	BEGIN
--		SET @sql = @sql + '' AND Employee_FirstName + case when Employee_MiddleName is not null then '''' '''' + cast(Employee_MiddleName as varchar(50)) else '''' '''' end +  isnull(Employee_LastName,'''''''') LIKE '''''' + cast(''%'' + @EmployeeName+''%'' as nvarchar(100)) + ''''''''
--	END
if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='''''' + @GradeLevel + ''''''''
	end
SET @sql = @sql + '' AND Employee_Firstname<>''''Administrator'''' ORDER BY Employee_Code_Id''     
EXEC(@sql)  
drop table #EmpLevel
drop table #EmpDesignation
drop table #LevelRights        
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]    Script Date: 03/25/2021 10:22:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--   Proc_TA_SelectEmployeeDetailXtraGrid ''11/jun/2008'',''04/Jul/2011'',''SuperAdmin'',0,1,0
-- Proc_TA_SelectEmployeeDetailXtraGrid ''SuperAdmin'',''10'',''1,2,3,47,113,132,133,134,135,136'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailXtraGrid]
	-- Add the parameters for the stored procedure here
	--@FromDate varchar(50),
	--@ToDate varchar(50),
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	
	@LevelRights varchar(1000),
	@ParentId int	,
	@EmpAutoId bigint
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @sqlQuery as varchar(8000)
DECLARE @CurrentDate AS NVARCHAR(30)
SET @CurrentDate = GetDate()      
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
    -- Insert statements for procedure here
		set @sqlQuery = ''''
		set @sqlQuery = @sqlQuery + ''SELECT dbo.TA_Tbl_Employee.Employee_code_Id, isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as [Employee Name], Status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end,'' 
		set @sqlQuery = @sqlQuery + '' convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as [Date Of Birth],convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as [Date Of Joining],''
		set @sqlQuery = @sqlQuery + '' Gender = case Gender when ''''Male''''  then ''''Male''''  when ''''Female'''' then ''''Female'''' end, TA_Tbl_Employee.Passport_No, convert(nvarchar(20),TA_Tbl_Employee.Passport_expirydate,101) as [Passport Expiry Date], TA_Tbl_Employee.Visa_No, convert(nvarchar(20),TA_Tbl_Employee.Visa_expirydate,101) as [Visa Expiry Date], replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as [Designation],replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as [Level Name],''		
		set @sqlQuery = @sqlQuery + '' TA_Tbl_Category.CategoryName as [Employee Category], TA_Tbl_Type.TypeName as [Employee Type] FROM dbo.TA_Tbl_Employee'' 
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_EmployeeDesignation ON dbo.TA_Tbl_Employee.Employee_Id = dbo.TA_Tbl_EmployeeDesignation.EmployeeId'' 
		set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
		set @sqlQuery = @sqlQuery + '' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.LevelId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
		set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''		
		--set @sqlQuery = @sqlQuery + '' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.report_exclude = 0)''
		set @sqlQuery = @sqlQuery + '' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''')'' 
		set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''		
		set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''
	    set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = ta_tbl_Employee.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,'''''' + cast(@CurrentDate as nvarchar(50))  + '''''', 102) order by EffectiveDate desc)''	    
		--set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
		if(@EmpAutoId = 0)
			BEGIN 
			  set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeLevel.LevelId in ('' + @LevelRights +'')''
			END
		ELSE
		   BEGIN
			  set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
		   END
		if(@UserGroupName<>''SuperAdmin'')
			begin
				set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
			end
		--if not(@FromDate='''')		
		--begin
		--set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @FromDate as nvarchar(50))   + '''''', 102)) ''		
		--End
		--if not (@ToDate='''')
		--	begin
		--	  set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@ToDate as nvarchar(50))  + '''''', 102)) '' 		
		--	end
			set @sqlQuery=@sqlQuery+ ''order by dbo.TA_Tbl_Employee.Employee_code_Id''
		EXEC (@sqlQuery)		
drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsUpdated]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_SelectEmployeeDetails 153
-- Modified by : Prabakaran.P
-- Modified on : 26-Apr-08
--select * from ta_tbl_employee
CREATE        PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsUpdated] 
(  
	@EmployeeId INT=0  
)  
AS            
BEGIN  
	DECLARE @del BIT  
	SET @del=0 
	DECLARE @ActiveYearId INT
	DECLARE @EffectiveDate datetime
	DECLARE @EffectBPayDate datetime
	DECLARE @EffectLevelDate datetime
	DECLARE @EffectCategoryDate datetime
	DECLARE @EffectTypeDate datetime
	set @EffectiveDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectBPayDate=(select Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectLevelDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectCategoryDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeCategory where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	set @EffectTypeDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeType where EmployeeId=@EmployeeId and EffectiveDate<=getdate())
	--select @EffectiveDate,@EffectBPayDate,@EffectLevelDate,@EffectCategoryDate,@EffectTypeDate
	--selecting employee details based on id  
	SELECT E.Employee_Id,ELevel.LevelId,L.name AS LevelName,E.UserGroup_Id,g.groupName,EDesig.DesignationId as Designation_Id,EDesig.EffectiveDate as EDesigEffectDate,T.TitleName,  
	E.Bus_Id,TV.Route_Name AS Bus,  
	--E.Employee_FirstName + case when E.Employee_MiddleName ='''' then '' '' else  '' '' + E.Employee_MiddleName end + case when E.Employee_LastName <> '''' then '' '' + E.Employee_LastName end as Employee_FirstName, E.Father_name,E.Mother_name,  
	E.Employee_FirstName,E.Employee_MiddleName,isnull(E.Employee_LastName,'''') as Employee_LastName, E.Father_name,E.Mother_name,  
	CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
	E.Blood_Group,E.EmailId,E.Contact_Address,E.Permanent_Address,E.Phone_Number,E.Mobile_Number,E.Gender,E.Marital_status,  
	E.Nationality,E.Religion,E.Photo,E.Personal_mailid,E.Passport_No,CONVERT(NVARCHAR,E.Passport_expirydate,101) AS Passport_expirydate,  
	E.Visa_No,CONVERT(NVARCHAR,E.Visa_expirydate,101) AS Visa_expirydate,E.Vehicle_Type,E.Vehicle_No,  
	CONVERT(NVARCHAR,E.Anniversary_Date,101) AS Anniversary_Date,E.Native_Place,Look.Title AS City,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,  
	E.Spouse_No,E.Children_No,E.Employee_Code_Id,CONVERT(NVARCHAR,E.DateOfJoining,101) AS DateOfJoining,E.Reporting_To,Rep.Employee_FirstName as Reporting,  
	E.Leave_Sanc_Authority,Sanc.Employee_FirstName AS SancAuth, E.Prev_Experience,EPay.BasicPay as Basic_Salary,EPay.EffectiveDate as EPayEffectDate,E.Hostel,E.UserName,E.Emp_password,  
	E.Qual_JoiningTime,E.Qual_Employment,E.OutDoorJob,E.CompOff_Eligible,E.OT_Eligible,E.ESI_Eligible,E.PF_Eligible,   
	E.Report_Exclude,E.Employee_Status,E.SwipeCardNo,tblCat.CategoryName,tblCat.CategoryId,ECat.EffectiveDate as CategoryEffDate,tblType.TypeName,tblType.TypeId,EType.EffectiveDate as TypeEffDate,ELevel.EffectiveDate as LevelEffDate,E.Isdeleted 
	FROM TA_Tbl_Employee E   
	left Outer join ta_tbl_usergroup g on g.groupId = e.usergroup_id  
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ELevel ON ELevel.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=ELevel.LevelId 
	LEFT OUTER JOIN TA_Tbl_EmployeeCategory ECat ON ECat.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_EmployeeType EType ON EType.EmployeeID= E.Employee_Id
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId  
	--LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle TV ON TV.VehicleId=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_RouteMaster TV ON TV.[Id]=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
	LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
	LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
	LEFT OUTER JOIN TA_Tbl_Employee Rep ON Rep.Employee_Id = E.Reporting_To  
	LEFT OUTER JOIN TA_Tbl_Employee Sanc ON Sanc.Employee_Id = E.Leave_Sanc_Authority 
	INNER JOIN TA_Tbl_Category tblCat ON tblCat.CategoryId= ECat.CategoryId
	INNER JOIN TA_Tbl_Type tblType ON tblType.TypeId= EType.TypeId
	WHERE  E.Employee_Id=@EmployeeId AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate
	--WHERE E.Employee_Id=@EmployeeId AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsNew]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsNew]
(
@type CHAR(1),
@EmployeeId NVARCHAR(50),
@EmployeeName NVARCHAR(50)=''''
)
AS
DECLARE @del BIT
SET @del=0
DECLARE @EffectiveDate datetime
DECLARE @EffectBPayDate datetime
set @EffectiveDate=(select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId)
set @EffectBPayDate=(select Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId)
--selecting all employee details
IF @type=''A''
BEGIN
	SELECT Employee_Id,UserGroup_Id,EDesig.DesignationId,Bus_Id,Employee_FirstName,Employee_MiddleName,isnull(Employee_LastName,''''),
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,State,Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo
	FROM TA_Tbl_Employee E
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	WHERE E.IsDeleted=@del and Employee_Firstname<>''Administrator'' 
END
--selecting employee details based on id            
ELSE IF @type=''P''
BEGIN
	SELECT Employee_Id,UserGroup_Id,EDesig.DesignationId,Bus_Id,Employee_FirstName,Employee_MiddleName,isnull(Employee_LastName,'''') as Employee_LastName,
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,State,Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo,EL.LevelId
	FROM TA_Tbl_Employee E
	INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	WHERE E.IsDeleted=@del AND Employee_Id=@EmployeeId
END
--selecting employee using search option
ELSE IF @type=''N''
BEGIN
	SELECT E.Employee_Id,Employee_FirstName,L.levelName AS Company_Name,T.TitleName AS TitleName,Employee_MiddleName,isnull(Employee_LastName,'''') as Employee_LastName,
	Father_name,CONVERT(NVARCHAR,DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,DateofBirth_Record,101) AS DateofBirth_Record,Blood_Group,EmailId,Contact_Address,Permanent_Address,Phone_Number,Mobile_Number,
	Gender,Marital_status,Nationality,Religion,Photo,Personal_mailid,Passport_No,CONVERT(NVARCHAR,Passport_expirydate,101) AS Passport_expirydate,Visa_No,CONVERT(NVARCHAR,Visa_expirydate,101) AS Visa_expirydate,Vehicle_Type,
	Vehicle_No,CONVERT(NVARCHAR,Anniversary_Date,101) AS Anniversary_Date,Native_Place,District,E.State,E.Country,Children_No,Employee_Code_Id,
	CONVERT(NVARCHAR,DateOfJoining,101) AS DateOfJoining,Reporting_To,Leave_Sanc_Authority,Prev_Experience,EPay.BasicPay as Basic_Salary,UserName,Emp_password,Qual_JoiningTime,Qual_Employment,OutDoorJob,
	CompOff_Eligible,OT_Eligible,Employee_Status,SwipeCardNo
	 FROM TA_Tbl_Employee as E 
    INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	INNER JOIN TA_TBL_levelDetails as Ld2 on Ld2.id= EL.LevelId 
	INNER JOIN TA_TBL_levelDetails as Ld1 ON Ld1.id = ld2.parentid 
	 INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
	INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id
	INNER JOIN TA_TBL_level as L ON Ld2.Levelid=L.LevelId
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
	WHERE E.IsDeleted=@del AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND Employee_FirstName LIKE @EmployeeName+''%''  --(substring(E.Employee_FirstName,1,len(@EmployeeName)) = @EmployeeName )
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>

-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Late Entry'',15

-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Early Exit'',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Less Hours Worked'',7
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Absent - Single Day'',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Continuous Absent'',2
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Continuous Absent'',3
-- Proc_TA_SelectEmployeeDetailsForSmsTriggering ''Continuous Absent'',4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetailsForSmsTriggering]
	-- Add the parameters for the stored procedure here
	@TemplateName VARCHAR(50),
	@ShiftID INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    DECLARE @FirstTriggeringTime DATETIME
    DECLARE @ShiftTiming DATETIME
    DECLARE @TriggeringTime DATETIME
    DECLARE @TemplateID int
    DECLARE @NextTriggeringTime DATETIME
    DECLARE @LessHrsLimitation VARCHAR(5)	
    DECLARE @lesshrsLimitationInMins INT
    DECLARE @TagName VARCHAR(50)
    SELECT @TemplateID=ID from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
    create table #TempFinal(id int identity(1,1),EmployeeName varchar(250),EmployeeId varchar(50),Hrs varchar(5),date datetime)    
	if(@TemplateName=''Late Entry'')
	begin
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@NextTriggeringTime=Second_TriggeringTime 		
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @NextTriggeringTime=@FirstTriggeringTime+@ShiftTiming+@NextTriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		Set @TagName=''LateEntry''
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		--select @FirstTriggeringTime
		--select @TemplateID
		--select @ShiftTiming
		--  @TriggeringTime is the time after shift starttime, NextTriggeringTime is shift starttime + @TriggeringTime + @NextTriggeringTime
		--If shift start at 9, First triggger time is 01:00, next triegger is 00:30 it means First Trigger at 10 am and next trigger time is 10:30 am
		--select @TriggeringTime --
		--select @NextTriggeringTime
		if not exists(select top 1 logid from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and 
		TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))and Status=1 and ShiftId=@ShiftID)
		begin
			--10:00<=9.45
			--10:00<=10.00
			--10:00<=10.15
			if(@TriggeringTime<=GETDATE())
			begin
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,LateIn,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) 
				and 
				LateInMins>0 
				and InTime<>''00:00'' 
				and  
				date+convert(datetime,InTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
		end
		else
		begin
			SELECT @NextTriggeringTime=max(NextTriggeringTime) from TA_Tbl_SMSLogDetails where TemplateID=@TemplateID and TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
			and Status=1 and ShiftId=@ShiftID		
			set @TriggeringTime=@NextTriggeringTime
			SELECT @ShiftTiming=@NextTriggeringTime-CONVERT(datetime,First_TriggeringTime) from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			if(@TriggeringTime<=GETDATE())
			begin
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,LateIn,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				LateInMins>0 and InTime<>''00:00'' and date+convert(datetime,InTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
				and PD.Employee_Code_Id not in(select Employeesids from TA_Tbl_SMSLogChild)
			end
			SELECT @NextTriggeringTime=@NextTriggeringTime+CONVERT(datetime,Second_TriggeringTime) from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1
			select @ShiftTiming=Shift_EndTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))from TA_Tbl_Shift 
			where Shift_Id=@ShiftID and Isdeleted=0
			if @NextTriggeringTime>@ShiftTiming
			begin
				return
			end
		end
	end	
	if(@TemplateName=''Early Exit'')
	begin
		if not exists(select status from TA_Tbl_SMSLogDetails where TriggeredDate=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))and status=1
		and ShiftId=@ShiftID and TemplateID=@TemplateID)
			begin	
				Set @TagName=''EarlyExit''	
				SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID from Ta_Tbl_SMSTemplates where id=@TemplateID and Status=1
				select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
				set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming++CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
				if(@TriggeringTime<=GETDATE())
				begin
					Insert into #TempFinal
					select E.Employee_FirstName,E.SwipeCardNo,EarlyOut,Date from TA_Tbl_ProcessedData PD
					inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo and ProcessFlag=1
					where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
					EarlyOutMins>0 and OutTime<>''00:00'' and (date+convert(datetime,OutTime) <= @TriggeringTime)
					and E.Isdeleted=0
				end
			end
	end
	if(@TemplateName=''Less Hours Worked'')
	begin
		Set @TagName=''LessHours''		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID,@LessHrsLimitation=LessHrsLimitation 
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_EndTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		--select @TriggeringTime,@ShiftTiming
		set @lesshrsLimitationInMins=SUBSTRING(@LessHrsLimitation,0,CHARINDEX('':'',@LessHrsLimitation))*60+SUBSTRING(@LessHrsLimitation,CHARINDEX('':'',@LessHrsLimitation)+1,len(@LessHrsLimitation))
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,HrsLess,Date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				LessHoursInMins>=@lesshrsLimitationInMins and OutTime<>''00:00'' 
				--and date+convert(datetime,OutTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
	end
	if(@TemplateName=''Absent - Single Day'')
	begin
		Set @TagName=''AbsentSingleDay''		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select E.Employee_FirstName,E.SwipeCardNo,'''',date from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee E on PD.Employee_Code_Id=E.SwipeCardNo
				where Shift_Id=@ShiftID and Date=CONVERT(datetime, CONVERT(varchar(10),getdate(),111)) and 
				(InTime='''' or InTime=''00:00'' or OutTime='''' or OutTime=''00:00'')
				and (FNAttendanceCode=''Absent'' or ANAttendanceCode=''Absent'')
				--and date+convert(datetime,OutTime) between @ShiftTiming and @TriggeringTime
				and E.Isdeleted=0
			end
	end
	if(@TemplateName=''Continuous Absent'')
	begin
		Set @TagName=''AbsentContinuousDay''		
		SELECT @FirstTriggeringTime=First_TriggeringTime,@TemplateID=ID
		from Ta_Tbl_SMSTemplates where @TemplateName=TemplateName and Status=1		
		select @ShiftTiming=Shift_StartTime from TA_Tbl_Shift where Shift_Id=@ShiftID and Isdeleted=0
		set @TriggeringTime=@FirstTriggeringTime+@ShiftTiming
		set @ShiftTiming=@ShiftTiming+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))		
		set @TriggeringTime=@TriggeringTime+CONVERT(datetime, CONVERT(varchar(10),getdate(),111))
		Declare @ContinuousAbsentDays int
		select @ContinuousAbsentDays=Continue_AbsentDays from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		if(@TriggeringTime<=GETDATE())
			begin				
				Insert into #TempFinal
				select distinct E.Employee_FirstName,E.SwipeCardNo,'''',CONVERT(datetime, CONVERT(varchar(10),getdate(),111))	from TA_Tbl_Employee E where E.SwipeCardNo in(
				select a.Employee_Code_Id from(
				select count(*)count,PD.Employee_Code_Id from TA_Tbl_ProcessedData PD				
				where(Date>=DATEADD(D,-@ContinuousAbsentDays,CONVERT(datetime, CONVERT(varchar(10),getdate(),111))) 
				and Date<=CONVERT(datetime, CONVERT(varchar(10),getdate(),111))) 				
				and (FNAttendanceCode=''Absent'' and ANAttendanceCode=''Absent'')
				group by Employee_Code_Id having(count(*))>=@ContinuousAbsentDays)as a)
			end
	end
	Set @TagName=''LessHours''
	Declare @TagCount int
	CREATE TABLE #TempTags(id INT IDENTITY(1,1),Tags VARCHAR(20))
	CREATE TABLE #TempTagPosition(id int identity(1,1),Tag varchar(20),position int)
	CREATE TABLE #TempTagPositionFinal(id int identity(1,1),Tag varchar(20),position int,ColumnNames varchar(40))
	INSERT INTO #TempTags
	SELECT Tags FROM Ta_Tbl_SMSTags WHERE TemplateName=@TagName and Tags!=''{User Name}''
	set @TagCount=(select COUNT(*) from #TempTags)
	Declare @Tags varchar(20)
	declare @Start int
	set @Start=1	
	while @Start<=@TagCount
	begin		
		select @Tags=Tags from #TempTags where id=@Start
		--select @Tags
		insert into #TempTagPosition 
		select @Tags,CHARINDEX(@Tags,Tags) from Ta_Tbl_SMSTemplates where TemplateName=@TemplateName
		and CHARINDEX(@Tags,Tags)!=0
		set @Start=@Start+1
	end	
	insert into #TempTagPositionFinal	
	select Tag,position,
	case	when Tag=''{Employee ID}''	then ''EmployeeId''
			when Tag=''{Employee Name}''	then ''EmployeeName''
			when Tag=''{Late By Hrs}''	then ''Hrs''
			when Tag=''{Date}''			then ''convert(varchar(20),Date,103)''
			when Tag=''{Early Exit Hrs}''	then ''Hrs''
			when Tag=''{Less Hours}''		then ''Hrs''
			when Tag=''{Count}''			then ''Count''
	end
	from #TempTagPosition order by position	
	Declare @Totalrecord int
	set @Totalrecord=(select COUNT(*) from #TempFinal)
	--select * from #TempFinal
	declare @i int
	set @i=1
	Create table #FinalStringTable(id int identity(1,1),FinalString varchar(max))
	Declare @TagName1 varchar(40)
	Declare @TagName2 varchar(40)
	Declare @TagName3 varchar(40)
	Declare @TagName4 varchar(40)
	Declare @TagName5 varchar(40)
	select @TagName1=ColumnNames from #TempTagPositionFinal where id=1
	select @TagName2=ColumnNames from #TempTagPositionFinal where id=2
	select @TagName3=ColumnNames from #TempTagPositionFinal where id=3
	select @TagName4=ColumnNames from #TempTagPositionFinal where id=4
	select @TagName5=ColumnNames from #TempTagPositionFinal where id=5
	while @i<=@Totalrecord
	begin		
		Declare @DynamicSQL varchar(max)
		set @DynamicSQL=''''		
		set @DynamicSQL=@DynamicSQL+''select ''
		if(@TagName1!='''')
		begin
			set @DynamicSQL=@DynamicSQL+@TagName1
		end
		if(@TagName2!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName2
		end
		if(@TagName3!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName3
		end
		if(@TagName4!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+''''''-''''''+''+''+@TagName4
		end
		if(@TagName5!='''')
		begin
			set @DynamicSQL=@DynamicSQL+''+''+'''''',''''''+''+''+@TagName5
		end
		set @DynamicSQL=@DynamicSQL+'' From #TempFinal where id=''+CONVERT(varchar(max),@i)
		Insert into #FinalStringTable
		Execute(@DynamicSQL)		
		set @i=@i+1
	end
	--print @Totalrecord
	--select * from #FinalStringTable
	Declare @FinalString nvarchar(max)
	select @FinalString=coalesce(@FinalString+'','','' '')+isnull(FinalString,'''') from #FinalStringTable
	Declare @ExceptionReceivedEmployees nvarchar(max)
	select @ExceptionReceivedEmployees=coalesce(@ExceptionReceivedEmployees+'','','' '')+isnull(EmployeeId,'''') from #TempFinal
	--select @FinalString as concatString
	if(@FinalString!='''')
	begin
		select Message+@FinalString as Message,@FinalString as ExceptionEmployees,@TemplateName as TemplateName,
		@ExceptionReceivedEmployees as ExceptionReceivedEmployees,@NextTriggeringTime as next
		from Ta_Tbl_SMSTemplates where id=@TemplateID and Status=1
	end
	else
	begin
		select ''NO'' Message,'''' ExceptionEmployees,@TemplateName as TemplateName,'''' as ExceptionReceivedEmployees,@NextTriggeringTime 
		as next
	end
	select E.Employee_FirstName+'' ''+E.Employee_LastName as Receivers,E.SwipeCardNo,E.Mobile_Number,@TemplateID as TemplateID from TA_Tbl_Employee E where UserGroup_Id in(
	select Usergroupid from Ta_Tbl_SMSReceivers SR
	inner join Ta_Tbl_SMSTemplates ST on SR.TemplateId=ST.id
	where TemplateId=@TemplateID and ST.Status=1) and E.Isdeleted=0 and E.Employee_Status=1
	and E.SwipeCardNo!=''18000000'' and E.Mobile_Number!='''' and E.SMSEnabled = 1 
	--and E.Employee_Code_Id = ''8967661''
	drop table #TempFinal
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeDetails]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_SelectEmployeeDetails 361
-- Modified by : Prabakaran.P
-- Modified on : 26-Apr-08
--	Proc_TA_SelectEmployeeDetails 167
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeDetails] 
(  
	@EmployeeId INT=0 
)  
AS
BEGIN
	DECLARE @ActiveYearId INT
	DECLARE @EffectiveDate datetime
	DECLARE @EffectBPayDate datetime
	DECLARE @EffectLevelDate datetime
	DECLARE @EffectCategoryDate datetime
	DECLARE @EffectTypeDate datetime
	select @EffectiveDate=Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=@EmployeeId
	select @EffectBPayDate=Max(EffectiveDate) from TA_Tbl_EmployeePay where EmployeeId=@EmployeeId
	select @EffectLevelDate=Max(EffectiveDate) from TA_Tbl_EmployeeLevel where EmployeeId=@EmployeeId
	select @EffectCategoryDate=Max(EffectiveDate) from TA_Tbl_EmployeeCategory where EmployeeId=@EmployeeId
	select @EffectTypeDate=Max(EffectiveDate) from TA_Tbl_EmployeeType where EmployeeId=@EmployeeId
	declare @ReportingToEmailID as nvarchar(100)
	declare @ApprovalAuthorityEmailID as nvarchar(100)
	select @ReportingToEmailID=EmailId from TA_Tbl_Employee where Employee_Id=(select Reporting_To from TA_Tbl_Employee where Employee_Id=@EmployeeId)
	select @ApprovalAuthorityEmailID=EmailId from TA_Tbl_Employee where Employee_Id=(select Leave_Sanc_Authority from TA_Tbl_Employee where Employee_Id=@EmployeeId)
	SELECT	E.Employee_Id,ELevel.LevelId,L.name AS LevelName,E.UserGroup_Id,g.groupName,EDesig.DesignationId as Designation_Id,EDesig.EffectiveDate as EDesigEffectDate,
			T.TitleName,E.Bus_Id,TV.Route_Name AS Bus,E.Employee_FirstName,E.Employee_MiddleName,isnull(E.Employee_LastName,'''') as Employee_LastName, 
			E.Father_name,E.Mother_name,CONVERT(NVARCHAR,E.DateofBirth,101) AS DateofBirth ,CONVERT(NVARCHAR,E.DateofBirth_Record,101) AS DateofBirth_Record,  
			E.Blood_Group,E.EmailId,E.Contact_Address,E.Permanent_Address,E.Phone_Number,E.Mobile_Number,E.Gender,E.Marital_status,  
			E.Nationality,R.Name as Religion,R.ID as ReligionId,E.Photo,E.Personal_mailid,E.Passport_No,CONVERT(NVARCHAR,E.Passport_expirydate,101) AS Passport_expirydate,  
			E.Visa_No,CONVERT(NVARCHAR,E.Visa_expirydate,101) AS Visa_expirydate,E.Vehicle_Type,E.Vehicle_No,  
			CONVERT(NVARCHAR,E.Anniversary_Date,101) AS Anniversary_Date,E.Native_Place,Look.Title AS City,E.District,E.State,Look1.Title AS Statename,E.Country,Look2.Title AS Countryname,  
			E.Spouse_No,E.Children_No,E.Employee_Code_Id,CONVERT(NVARCHAR,E.DateOfJoining,101) AS DateOfJoining,E.Reporting_To,(Rep.Employee_FirstName + '''' + isnull(Rep.Employee_LastName,'''') + '' - '' + isnull(Rep.Employee_Code_id,'''')) as Reporting,  
			E.Leave_Sanc_Authority,(Sanc.Employee_FirstName + '''' + isnull(Sanc.Employee_LastName,'''')+ '' - '' + isnull(Sanc.Employee_Code_id,'''')) AS SancAuth, E.Prev_Experience,E.Basic_Salary as Basic_Salary,EPay.EffectiveDate as EPayEffectDate,E.Hostel,E.UserName,E.Emp_password,  
			E.Qual_JoiningTime,E.Qual_Employment,E.OutDoorJob,E.CompOff_Eligible,E.OT_Eligible,E.ESI_Eligible,E.PF_Eligible,   
			E.Report_Exclude,E.Employee_Status,E.SwipeCardNo,tblCat.CategoryName,tblCat.CategoryId,ECat.EffectiveDate as CategoryEffDate,tblType.TypeName,tblType.TypeId,EType.EffectiveDate as TypeEffDate,ELevel.EffectiveDate as LevelEffDate,E.Isdeleted,E.IsFlexible,convert(varchar(20),E.InActiveDate,110)as InActiveDate
			,E.CustomField1,E.CustomField2,E.CustomField3,E.CustomField4,E.CustomField5,ENT.Entrance_Name,@ReportingToEmailID as ''ReportingToEmailID'',@ApprovalAuthorityEmailID as ''ApprovalAuthorityEmailID'',
			E.penalty, E.MobileClockInOUt,E.SMSEnabled
			
	FROM TA_Tbl_Employee E   
	left Outer join TA_Tbl_EmployeeEntrance EE On EE.Employee_Code_Id=E.Employee_Code_Id 
	left Outer  Join TA_Tbl_Terminal TER On TER.Terminal_ReaderID=EE.Device_Id
	left Outer  Join TA_Tbl_Entrance_INOUTDetails ED On ED.Reader_Id=TER.Terminal_Id
	left Outer  Join TA_Tbl_Entrance ENT On ENT.Entrance_Id=ED.Entrance_Id
	left Outer join ta_tbl_usergroup g on g.groupId = e.usergroup_id  
	LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeePay EPay ON EPay.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeeLevel ELevel ON ELevel.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_LevelDetails L ON L.Id=ELevel.LevelId 
	LEFT OUTER JOIN TA_Tbl_EmployeeCategory ECat ON ECat.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_EmployeeType EType ON EType.EmployeeID= E.Employee_Id 
	LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId  
	LEFT OUTER JOIN TA_Tbl_RouteMaster TV ON TV.[Id]=E.Bus_Id  
	LEFT OUTER JOIN TA_Tbl_Lookup Look ON Look.ID=E.Native_Place  
	LEFT OUTER JOIN TA_Tbl_Lookup Look1 ON Look1.ID=E.State  
	LEFT OUTER JOIN TA_Tbl_Lookup Look2 ON Look2.ID=E.Country  
	LEFT OUTER JOIN TA_Tbl_Employee Rep ON Rep.Employee_Id = E.Reporting_To  
	LEFT OUTER JOIN TA_Tbl_Employee Sanc ON Sanc.Employee_Id = E.Leave_Sanc_Authority 
	INNER JOIN TA_Tbl_Category tblCat ON tblCat.CategoryId= ECat.CategoryId
	INNER JOIN TA_Tbl_Type tblType ON tblType.TypeId= EType.TypeId
	LEFT OUTER JOIN TA_Tbl_Religion R on e.Religion=R.ID
	WHERE E.Employee_Id=@EmployeeId  AND EDesig.EffectiveDate=@EffectiveDate AND EPay.EffectiveDate=@EffectBPayDate AND ELevel.EffectiveDate=@EffectLevelDate AND ECat.EffectiveDate=@EffectCategoryDate AND EType.EffectiveDate=@EffectTypeDate
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployeeCode]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployeeCode]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.R>
-- Create date: <15-12-2016>
-- Description:	<Get Employee Details using the employee code>
-- Proc_TA_SelectEmployeeCode ''11'',''SuperAdmin'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployeeCode]
	-- Add the parameters for the stored procedure here
	@EmployeeCode nvarchar(20),
	@UserGroupName nvarchar(100),
	@EmpAutoID int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    declare @LevelId int
	--Get the Top level ID
	declare @today datetime =getdate()
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into #EmpLevel exec [Proc_TA_EmpLevel] @today,@EmployeeCode 
	CREATE TABLE #LevelRights(LevelId INT)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	declare @GetLevelID as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
	;WITH ParentLevel AS
	(
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
		WHERE id = @GetLevelID
		UNION ALL
		SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
		INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
	)
	SELECT TOP 1 @LevelId=p.id
	FROM ParentLevel r
	inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	if(@LevelId is null)
		begin
			set @LevelId=@GetLevelID
		end
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId 
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@LevelId) as LevelId 
	declare @SQLQuery as nvarchar(Max)
	set @SQLQuery =''''
	set @SQLQuery =@SQLQuery + ''select ''+ ISNULL(cast(@LevelId as nvarchar(10)),0) + '' as ''''parentLevelID'''',E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + '''' '''' + E.Employee_LastName as ''''EmployeeName'''' from TA_Tbl_Employee E ''	
    set @SQLQuery =@SQLQuery +'' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
    set @SQLQuery =@SQLQuery +'' inner join #LevelRights on #LevelRights.LevelId=EL.levelID ''
    if(@isReportingto > 0)
    begin
		set @SQLQuery = @SQLQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
    end
		set @SQLQuery =@SQLQuery + '' where Employee_Code_Id=''''''+ cast(@EmployeeCode as varchar(100)) + ''''''''
		exec(@SQLQuery)
		drop table #EmpLevel
		drop table #LevelRights
		drop table #EmployeeIds
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectEmployee]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name 	:	Proc_TA_SelectEmployee ''45'',''SuperAdmin'',''9'',45
Created by	:	Janakaraj.P
Created  date	: 	03/08/07
Modified by	:	Prabakaran.P
Modified on	:	12-July-08
select * from TA_Tbl_EmployeeLevel
exec [Proc_TA_SelectEmployee] 22,''SuperAdmin'', 0, 22
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectEmployee]
(
	@Employee_ID int,
    @LevelId varchar(8000),
 	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@ParentId int	
)      
AS      
BEGIN      
 -- SET NOCOUNT ON added to prevent extra result sets from      
 -- interfering with SELECT statements.      
 SET NOCOUNT ON;      
 DECLARE @sql AS VARCHAR(5000)      
 DECLARE @CurrentDate AS NVARCHAR(30)
 SET @CurrentDate = GetDate()
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@CurrentDate as nvarchar(50)), 102) and ED.DesignationId is not null
-- Comment By Manikandan.R
-- ON 19-12-2013 4.52 for mantis bug 0020805
-- i have checked whether this procedure has been used into other modules or not. its not used.
--SELECT 
--	Employee_Id,
--	Employee_Code_Id,
--	Employee_FirstName + '' '' +  isnull(Employee_LastName,'''') AS ''Employee Name'',
--	TA_Tbl_Employee.CompOff_Eligible 
--FROM TA_Tbl_Employee 
--	INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
--	INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId
--	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId
--	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId
--	Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId
--	--Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId
--	--Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId
----WHERE TA_Tbl_Employee.Isdeleted=0 AND
----	TA_Tbl_Employee.Employee_Status=1 AND
----	Employee_Firstname<>''Administrator''
----ORDER BY Employee_Code_Id
--return
 IF(@LevelId = '''')
    BEGIN
	SET @LevelId = ''0''
    END
 --SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + case when Employee_MiddleName is not null then '' '' + cast(Employee_MiddleName as varchar(50)) else '' '' end + Employee_LastName AS ''Employee Name'' FROM TA_Tbl_Employee WHERE LevelID in(@LevelId) and Isdeleted=1      
 SET @sql =''SELECT Employee_Id,Employee_Code_Id,Employee_FirstName + '''' '''' +  isnull(Employee_LastName,'''''''') AS ''''Employee Name'''',TA_Tbl_Employee.CompOff_Eligible FROM TA_Tbl_Employee''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''
 SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
SET @sql = @sql + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
SET @sql = @sql + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''
SET @sql = @sql + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
SET @sql = @sql + '' WHERE TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.Employee_Status=1 ''
--SET @sql = @sql + '' AND #EmpLevel.LevelId in ('' + @LevelId + '') ''
--SET @sql = @sql + '' AND #EmpLevel.LevelId in (select * from #LevelRights) ''
--SET @sql = @sql + '' AND TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,'''''' + @CurrentDate + '''''', 102) order by EffectiveDate desc) AND''
--SET @sql = @sql + '' TA_Tbl_EmployeeDesignation.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = TA_Tbl_Employee.Employee_Id and EffectiveDate <= CONVERT(DATETIME,'''''' + @CurrentDate + '''''', 102) order by EffectiveDate desc) '' 
if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sql = @sql + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
	end
if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
SET @sql = @sql + '' AND Employee_Firstname<>''''Administrator'''' ORDER BY Employee_Code_Id''     
 EXEC(@sql)          
--Remove the temporary tables here  
drop table #EmpLevel
drop table #EmpDesignation
drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_ta_SelectDiscrepancyEmployee]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_ta_SelectDiscrepancyEmployee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from 
-- [proc_ta_SelectDiscrepancyEmployee] ''2012/01/01'',''2012/11/24'',''S787'',0,'''',''0'',0,0,''NormalUser'',''3'','''',0,0,15
CREATE  PROCEDURE [dbo].[proc_ta_SelectDiscrepancyEmployee]  
(  
 @fromDat datetime,  
 @ToDat datetime,  
 @empId varchar(100),  
 @shift int,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),  
 @employeeCategory int,  
 @employeeType int,  
 @UserGroupName varchar(250),  
 @GradeLevel varchar(20) ,  
 @EmpSwipeCard varchar(20),
 @CompanyId int,
 @ParentID int,
 @LoginEmployeeAutoId int 
)  
AS  
BEGIN   
-- SET NOCOUNT ON added to prevent extra result sets from  
-- interfering with SELECT statements.  

SET NOCOUNT ON;  
--Temporary table''s creation  
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)  
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)  
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)  
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)  
create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoginEmployeeAutoId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoginEmployeeAutoId) as EmpAutoId
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
create table #TempProcessedData(EmpAutoId bigint,Shift_Id int,Date datetime,Employee_Code_Id varchar(50))
CREATE TABLE #TempClockDetails
(
    Clk_Id int,
	Clk_CompId varchar(10),
	Clk_EmpId nvarchar(20),
	Clk_InDeviceId nvarchar(20),
	Clk_InDate datetime,
	Clk_InTime datetime,
	Clk_InPunchType nvarchar(25),
	Clk_OutDeviceId nvarchar(20),
	Clk_OutDate datetime,
	Clk_OutTime datetime,
	Clk_OutPunchType nvarchar(25),
	Clk_Process nvarchar(1) ,
	Clk_Remarks nvarchar(500),
	Clk_User nvarchar(20),
	Clk_Date datetime,
	Clk_Status char(1),
	IsVoid bit
)
create table #TempFinal
(
Employee_Code_Id nvarchar(15),
EmployeeAutoId int,
EmpName nvarchar(200),
InReaderID nvarchar(20),
InTerminalName nvarchar(50),
InDate nvarchar(20),
InTime nvarchar(20),
InpunchType nvarchar(50),
OutReaderID nvarchar(20),
OutTerminalName nvarchar(50),
OutDate nvarchar(20),
OutTime nvarchar(20),
OutPunchtype nvarchar(50),
ClockDate varchar(20),
CLK_EmpID nvarchar(20),
CLK_ID int,
DiscrepancyType varchar(2),
Reason varchar(255),
MaxHoursBeforeShift nvarchar(50),
Shift_Id int,
WeeklyOffStartHours nvarchar(5),
ShiftInDateTime nvarchar(20),
Shift_StartTime nvarchar(10),
Shift_EndTime nvarchar(10),
--ShiftOutDateTime nvarchar(20),
ManualEntryAlreadyExists varchar(5)
)
-- #TempProcessedData Indexes  
 /****** Object:  Index [IDX_EmpAutoId]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmpAutoId] ON [dbo].[#TempProcessedData]   
(  
 [EmpAutoId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData]   
(  
 [Date] ASC  
) ON [PRIMARY]  
-- #TempClockDetails Indexes   
/****** Object:  Index [IDX_Clk_EmpId]    Script Date:******/  
CREATE NONCLUSTERED INDEX [IDX_Clk_EmpId] ON [dbo].[#TempClockDetails]   
(  
 [Clk_EmpId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_Clk_Date]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Clk_Date] ON [dbo].[#TempClockDetails]   
(  
 [Clk_Date] ASC  
) ON [PRIMARY]  
--Employee Level Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel]   
(  
 [LevelId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Designation Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation]   
(  
 [DesignationId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Type Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]   
(  
 [EffectiveDate] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType]   
(  
 [TypeId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType]   
(  
 [EmployeeId] ASC  
)ON [PRIMARY]  
--Employee Category Indexes  
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/  
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]   
(  
 [EffectiveDate] ASC  
)ON [PRIMARY]  
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/  
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory]   
(  
 [CategoryId] ASC  
) ON [PRIMARY]  
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory]   
(  
 [EmployeeId] ASC  
) ON [PRIMARY]  
--Employee Level insert in Temporary table  
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (  
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el  
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
inner join #LevelRights on #LevelRights.LevelId=el.LevelId
where emp.Isdeleted=0 group by EmployeeId) ELevel  
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId 
inner join #LevelRights on #LevelRights.LevelId=EL.LevelId 
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null  
--select * from #EmpLevel  
--Employee Designation insert in Temporary table  
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (  
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed  
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EDesig  
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId  
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null  
--select * from #EmpDesignation  
--Employee Type insert in Temporary table  
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (  
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et  
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpType  
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId  
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null  
--select * from #EmpType  
--Employee Category insert in Temporary table  
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (  
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec  
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id   
where emp.Isdeleted=0 group by EmployeeId) EmpCategory  
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId  
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null  
--select * from #EmpCategory 
create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
/****** Object:  Index [IDX_EmpSwipeCardNo]    Script Date: 05/27/2009 16:27:55 ******/  
CREATE NONCLUSTERED INDEX [IDX_EmpSwipeCardNo] ON [dbo].[#TempEmployee]   
(  
 [EmpSwipeCardNo] ASC  
) ON [PRIMARY]  
insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id
where SwipeCardNo is not null
--select * from #TempEmployee
insert into  #TempProcessedData 
select #TempEmployee.EmpAutoId,TA_Tbl_ProcessedData.Shift_Id,TA_Tbl_ProcessedData.Date,TA_Tbl_ProcessedData.Employee_Code_Id 
from #TempEmployee  
INNER JOIN TA_Tbl_ProcessedData ON #TempEmployee.EmpSwipeCardNo = TA_Tbl_ProcessedData.Employee_Code_Id and Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--select * from  #TempProcessedData
insert into #TempClockDetails
select Clk_Id,Clk_CompId,Clk_EmpId,Clk_InDeviceId,Clk_InDate,Clk_InTime,Clk_InPunchType,Clk_OutDeviceId,Clk_OutDate,Clk_OutTime,Clk_OutPunchType,Clk_Process,Clk_Remarks,Clk_User,Clk_Date,Clk_Status,IsVoid
from  ta_tbl_clockdetails
inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo = ta_tbl_clockdetails.Clk_EmpId
where Clk_Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
and (clk_inTime is null or clk_outTime is null) AND IsVoid = 0
--select * from  #TempClockDetails
 Declare @finalCompanyId int
 if exists(select * from TA_Tbl_ShiftSettings where CompanyId=@CompanyId)
	begin
		set @finalCompanyId=@CompanyId
	end
else
	begin
		set @finalCompanyId =-1
	end
 declare @IndividualUserStatus int
 set @IndividualUserStatus = (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0)
 declare @sqlQuery as varchar(8000)  
 declare @sqlQuery1 as varchar(8000) 
 set @sqlQuery = ''''  
  set @sqlQuery1 = ''''
 SET @sqlQuery = @sqlQuery + ''insert into #TempFinal SELECT ta_tbl_Employee.employee_code_id,ta_tbl_Employee.employee_id AS EmployeeAutoId, ''        
 SET @sqlQuery = @sqlQuery + ''ta_tbl_Employee.Employee_FirstName + ''        
 SET @sqlQuery = @sqlQuery + '' '''' '''' + isnull(ta_tbl_Employee.Employee_LastName,'''''''') AS ''''EmpName'''', ''        
 SET @sqlQuery = @sqlQuery + ''#TempClockDetails.Clk_InDeviceId as InReaderID,ITer.Terminal_Name as InTerminalName,CONVERT(VARCHAR,#TempClockDetails.Clk_InDate,101) as InDate, convert(varchar,#TempClockDetails.Clk_InTime,108) as InTime ,case #TempClockDetails.Clk_InPunchType when ''''I'''' then ''''F_In'''' else #TempClockDetails.Clk_InPunchType end as Clk_InPunchType,''        
 SET @sqlQuery = @sqlQuery + ''#TempClockDetails.Clk_OutDeviceId as OutReaderID,OTer.Terminal_Name as OutTerminalName,CONVERT(VARCHAR,#TempClockDetails.Clk_OutDate,101) as OutDate, convert(varchar,#TempClockDetails.Clk_OutTime,108) as OutTime,case #TempClockDetails.Clk_OutPunchType when ''''O'''' then ''''F_Out'''' else #TempClockDetails.Clk_OutPunchType end as Clk_OutPunchType,CONVERT(VARCHAR,#TempClockDetails.Clk_Date,101) as ClockDate,#TempClockDetails.CLK_EmpID as CLK_EmpID, ''        
 SET @sqlQuery = @sqlQuery + '' #TempClockDetails.CLK_Id as CLK_ID, (case when #TempClockDetails.Clk_InDate is null then CONVERT(varchar(1),''''I'''') when #TempClockDetails.Clk_OutDate is null then CONVERT(varchar(1),''''O'''') end) as DiscrepancyType,''  
 SET @sqlQuery = @sqlQuery + '' CONVERT(varchar(255),'''''''') as Reason ''
 SET @sqlQuery = @sqlQuery + '',TA_Tbl_ShiftSettings.MaxHoursBeforeShift,#TempProcessedData.Shift_Id''
 SET @sqlQuery = @sqlQuery + '',TA_Tbl_ShiftSettings.WeeklyOffStartHours''
 SET @sqlQuery = @sqlQuery + '' ,((CONVERT(VARCHAR,#TempProcessedData.Date,101)) + CONVERT(varchar(1),'''' '''') + TA_Tbl_Shift.Shift_StartTime) AS ShiftInDateTime''  
 set @sqlQuery = @sqlQuery + '' ,TA_Tbl_Shift.Shift_StartTime,TA_Tbl_Shift.Shift_EndTime,''''No''''''  
 set @sqlQuery = @sqlQuery + '' from TA_Tbl_Employee''  
 set @sqlQuery = @sqlQuery + '' INNER JOIN #TempClockDetails ON TA_Tbl_Employee.SwipeCardNo = #TempClockDetails.Clk_EmpId''  
 SET @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_Terminal OTer ON #TempClockDetails.Clk_OutDeviceId = OTer.Terminal_ReaderID LEFT OUTER JOIN TA_Tbl_Terminal  ITer ON #TempClockDetails.Clk_InDeviceId = ITer.Terminal_ReaderID ''         
 set @sqlQuery = @sqlQuery + '' inner join #TempProcessedData on #TempProcessedData.EmpAutoId = TA_Tbl_Employee.Employee_Id and #TempProcessedData.Date = #TempClockDetails.CLK_Date''  
 SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId''  
 SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId''  
 SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''  
 set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId'' 
 set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Shift on #TempProcessedData.Shift_Id = TA_Tbl_Shift.Shift_Id'' 
 set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_ShiftSettings on Ta_Tbl_ShiftSettings.CompanyId = '''''' + cast(@finalCompanyId as nvarchar(11)) + ''''''''
 set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''  
 set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''  
 set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=TA_Tbl_EmployeeDesignation.EffectiveDate and #EmpDesignation.employeeid=TA_Tbl_EmployeeDesignation.EmployeeId ''  
 set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''  
 set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''  
 set @sqlQuery1 = @sqlQuery1 + '' where ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0''  
 if(@IndividualUserStatus  = 1)
 	BEGIN
 	  set @sqlQuery1 = @sqlQuery1 + '' and TA_Tbl_Employee.Employee_Id = '''''' + cast(@LoginEmployeeAutoId as varchar(25)) + '''''' ''
 	END
 if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
 if(@UserGroupName<>''SuperAdmin'')  
 begin  
  SET @sqlQuery1 = @sqlQuery1 + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''  
 end  
 if not(@EmployeeName='''')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + '' and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''  
 end 
 if not (@empId='''')  
 begin  
  set @sqlQuery1 = @sqlQuery1 + '' And (TA_Tbl_Employee.Employee_code_id = '''''' + @empId + '''''' )''  
 end  
 If Not (@EmpSwipeCard = '''')    
    Begin    
    Set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''    
 End   
 if(@employeeCategory<>0)  
 begin  
  set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))   
 end  
 if(@employeeType<>0)  
 begin  
  set @sqlQuery1 = @sqlQuery1 + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))   
 end 
 if(@shift<>0)  
 begin  
  Set @sqlQuery1 = @sqlQuery1 + '' And #TempProcessedData.shift_id= ''+  cast (@shift as nvarchar(50))  
 end  
 exec(@sqlQuery + @sqlQuery1)
 select distinct * from #TempFinal order by Employee_Code_Id,EmpName,ClockDate,InDate,InTime,OutDate,OutTime asc  
drop table #EmpLevel  
drop table #EmpDesignation  
drop table #EmpType  
drop table #EmpCategory  
drop table #LevelRights  
drop table #TempProcessedData
drop table #TempClockDetails
drop table #TempFinal
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		: senthil
-- ALTER  date  : 04August08   
-- Modified By	: Sashma
-- Modified On	: 12-May-2011
--Modified By		:	Gopinath.K
--Modified Date	:	04-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--Descriptions	:	SQL Query OPtimazation for handle EMPID.
-- Proc_Ta_RptEmployeeShiftNotAlloc ''04/17/2009'',''04/17/2012'','''','''','''',[0,1],'''','''','''',''SuperAdmin'','''','''',0,0,''Both''
-- Description:	Report Employee Details
-- =============================================
CREATE  PROCEDURE [dbo].[Proc_Ta_RptEmployeeShiftNotAlloc]
(
	@fromDat nvarchar(50),
	@ToDat nvarchar(50),
	@EmployeeId varchar(max),
	@shift int,
	@EmployeeName varchar(max),
	@LevelID varchar(8000),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmployeeStatus nvarchar(50),
	@UserGroupName varchar(20),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoId bigint
)
AS
BEGIN
	if(charIndex(''-'',@ToDat)>0)
		begin
			set @ToDat=(select convert(varchar(30),getdate(),102))
		end
	SET NOCOUNT ON;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@EmployeeId	
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''SELECT replace(dept.name,''''&amp;'''',''''&'''') as department, dbo.TA_Tbl_Employee.Employee_code_Id as employee_id,dbo.TA_Tbl_Employee.Employee_Id as empAutoId,status = case employee_status  when ''''1''''  then ''''Active''''  when ''''0'''' then ''''Inactive'''' end ''
	set @sqlQuery = @sqlQuery + '' ,isnull(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as empname,convert(nvarchar(20),TA_Tbl_Employee.DateofBirth,101) as dateOfBirth,dbo.TA_Tbl_Employee.Nationality,''
	set @sqlQuery = @sqlQuery + '' replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, Convert(nvarchar(20),TA_Tbl_Employee.DateOfJoining,101) as dateJoin,dbo.TA_Tbl_Employee.Report_Exclude,TA_Tbl_Employee.Gender''		
	set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_Employee ''
	set @sqlQuery = @sqlQuery + '' INNER join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.Ta_Tbl_levelDetails ON #EmpLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''
	set @sqlQuery = @sqlQuery + '' INNER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id''
	set @sqlQuery = @sqlQuery + '' INNER join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN dbo.TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId''
	set @sqlQuery = @sqlQuery + '' INNER join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER join #EmpType on #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
	set @sqlQuery = @sqlQuery + '' where  (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''') ''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			set @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + '' ''
		end
	if not(@fromDat='''')		
		begin
			set @sqlQuery = @sqlQuery + '' And (dbo.TA_Tbl_Employee.DateOfJoining >= CONVERT(DATETIME, '''''' +cast( @fromDat as nvarchar(50))   + '''''', 102)) ''			End
	if not (@ToDat='''')
		begin
			set @sqlQuery = @sqlQuery + '' AND (dbo.TA_Tbl_Employee.DateOfJoining <= CONVERT(DATETIME,'''''' + cast(@todat as nvarchar(50))  + '''''', 102)) '' 			end
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@EmployeeStatus=''Active'')
		begin
			set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_Status = 1) ''
		end		
	else if(@EmployeeStatus=''InActive'')
		begin		
			set @sqlQuery = @sqlQuery + '' and (dbo.TA_Tbl_Employee.Employee_Status = 0) ''	
		end		
	--if(@EmpAutoId > 0)
	--		BEGIN
	--		   set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
	--		END
	set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_Employee.Employee_code_Id ''
	exec(@sqlQuery)
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompanyForOverTime]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompanyForOverTime]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name    :     Proc_TA_SelectCompany
Description :     select the companies
Tables Included   :     TA_Tbl_LevelDetails,TA_Tbl_Level
Created By  :     Christopher S
Created On  :     10-Jan-09
Modified By :
Modified On :
Proc_TA_SelectCompanyForOverTime ''SuperAdmin'',''159'',1
*/
Create PROCEDURE [dbo].[Proc_TA_SelectCompanyForOverTime]
      -- Add the parameters for the stored procedure here
      @UserGroupName nvarchar(250),
      @UserLevels nvarchar(2000),
      @ParentID int     
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
declare @Query as varchar(7000)
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
    -- Insert statements for procedure here
      --if(@UserGroupName=''SuperAdmin'')
            BEGIN
                  set @Query = ''select ld.id as CompanyId,replace(ld.name,''''&amp;'''',''''&'''') as CompanyName'' 
                  set @Query= @Query +'' from TA_Tbl_LevelDetails ld''
                  set @Query= @Query +'' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId''
                  set @Query= @Query +'' inner join #LevelRights on #LevelRights.LevelId=ld.id inner join TA_Tbl_ShiftSettings S on ld.id=S.CompanyId''
                  --set @Query= @Query +'' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in (''+ @UserLevels +'')''
                  set @Query= @Query +'' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0''
            END
      /* else
            BEGIN
                  set @Query = ''select ld.id as CompanyId,replace(ld.name,''''&amp;'''',''''&'''') as CompanyName'' 
                  set @Query= @Query +'' from TA_Tbl_LevelDetails ld''
                  set @Query= @Query +'' inner join TA_Tbl_Level l on l.LevelId=ld.LevelId''
                  set @Query= @Query +'' where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 and ld.id in (''+ @UserLevels +'')''
            END */
            exec (@Query)
            drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCompany]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCompany]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_SelectCompany
Description	:	select the companies
Tables Included	:	TA_Tbl_LevelDetails,TA_Tbl_Level
Created By	:	Christopher S
Created On	:	10-Jan-09
Modified By	:	Manikandan.RR
Modified On	:	29-10-2019 11:57 AM
Changed dynamic query to normal SQL query.
Proc_TA_SelectCompany ''SuperAdmin'',''1'',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_SelectCompany]
	-- Add the parameters for the stored procedure here
	@UserGroupName nvarchar(250),
	@UserLevels nvarchar(2000),
	@ParentID int	
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	select ld.id as CompanyId,replace(ld.name,''&amp;'',''&'') as CompanyName 
	from TA_Tbl_LevelDetails ld
	inner join TA_Tbl_Level l on l.LevelId=ld.LevelId
	inner join #LevelRights on #LevelRights.LevelId=ld.id
	where l.parentLevelid=0 and l.isdeleted=0 and ld.isdeleted=0 order by ld.id
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureModify]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureModify]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE procedure [dbo].[Proc_TA_UpdateYearClosureModify]
(
@YearClosureId int,
@Carry_PrevYear float,
@Current_Quota float,
@Borrow_NextYear float,
@Leave_Taken float,
@Available_Leaves float,
@Encashment float
)
AS
UPDATE TA_Tbl_YearClosure
SET Carry_PrevYear=@Carry_PrevYear,
Current_Quota=@Current_Quota,
Borrow_NextYear=@Borrow_NextYear,
Leave_Taken=@Leave_Taken,
Available_Leaves=@Available_Leaves,
Encashment=@Encashment
WHERE YearClosureId=@YearClosureId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name  : Proc_TA_UpdateYearClosureByLeaveSanction    
Description  : Update year closure leave taken field while Leave sanctioned    
Tables Included  : TA_Tbl_YearClosure     
Created By  : Prabakaran    
Created On  : 21-Aug-07    
Modified By  :     
Modified On  :   
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByLeaveSanction]  
( 
	@NumberOfDays decimal(18,1),    
	@LeaveTypeId int,  
	@Employee_Id int,  
	@ModeType nvarchar(10),  
	@auEmpId int,
	@YearSetting_ID int  
)  
as  
BEGIN
	-- A indicates Leave Approved  
	if(@ModeType=''A'')    
	begin    
		update TA_Tbl_YearClosure set Leave_Taken=isnull(Leave_Taken,0)+@NumberOfDays,Emp_Id=@auEmpId  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID   
	end  
	-- R indicates Leave Rejected  
	else if(@ModeType=''R'')    
	begin  
		update TA_Tbl_YearClosure set Leave_Taken=isnull(Leave_Taken,0)-@NumberOfDays,Emp_Id=@auEmpId  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID    
	end  
	-- AB indicates Borrow Leave Approved   
	else if(@ModeType=''AB'')  
	begin  
		update TA_Tbl_YearClosure set Borrow_NextYear=isnull(Borrow_NextYear,0)+(-@NumberOfDays),Emp_Id=@auEmpId  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID
	end  
	-- RB indicates Borrow Leave Rejected    
	else if(@ModeType=''RB'')  
	begin 
		update TA_Tbl_YearClosure set Borrow_NextYear=isnull(Borrow_NextYear,0)-(-@NumberOfDays),Emp_Id=@auEmpId  
		where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id  
		and Year_SettingId=@YearSetting_ID 
	end
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosureByEncashment]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosureByEncashment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Procedure Name	:	Proc_TA_UpdateYearClosureByEncashment
Description		:	Update year closure Encaschment field while Encash sanctioned
Tables Included	:	TA_Tbl_YearClosure and Ta_tbl_yearsetting
Created By		:	Prabakaran
Created On		:	21-Aug-07
Modified By		:	
Modified On		:	
*/
CREATE   PROCEDURE [dbo].[Proc_TA_UpdateYearClosureByEncashment]
@Employee_Id int,
@NumberOfDays decimal(18,1),
@LeaveTypeId int
as
update TA_Tbl_YearClosure set Encashment=isnull(Encashment,0) + @NumberOfDays
where LeaveTypeId=@LeaveTypeId and Employee_Id=@Employee_Id
and Year_SettingId=(select YearSettings_Id from Ta_tbl_yearsetting where IsActive=1)
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateYearClosure]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateYearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  procedure [dbo].[Proc_TA_UpdateYearClosure]
(
@OrgLevelId INT,
@Employee_Id INT,
@Year_SettingID INT,
@LeaveTypeID INT,
@Available_Leaves FLOAT,
@YearClosed NVARCHAR(50),
@DateClosed NVARCHAR(15),
@Emp_ID INT
)
AS
UPDATE TA_Tbl_YearClosure
SET Available_Leaves=@Available_Leaves,YearClosed=@YearClosed,DateClosed=@DateClosed,Emp_ID=@Emp_ID,Time_Stamp=getdate()
WHERE Year_SettingID=@Year_SettingID AND OrgLevelId=@OrgLevelId AND Employee_Id=@Employee_Id AND LeaveTypeID=@LeaveTypeID 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateDefaultSE]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateDefaultSE]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateDefaultSE]
	-- Add the parameters for the stored procedure here
	@gradeName nvarchar(50),
    @gradeLevel int,
	@empAutoId int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
declare @RecordCount as int
set @RecordCount=(select count(*) from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=0)    
if(@RecordCount=0)
	begin
	INSERT INTO TA_Tbl_Grade(Grade_Name,Grade_Level,Emp_ID,Time_Stamp,Isdeleted) VALUES(@gradeName,@gradeLevel,@empAutoId,getdate(),0)
	select @@identity
	UPDATE TA_Tbl_Title SET GradeID = @@identity
	UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> ''18000000''
	DELETE TA_Tbl_Grade WHERE Grade_ID <> @@identity
    DELETE FROM TA_Tbl_ApprovalSettings
	end
else
begin
	UPDATE TA_Tbl_Title SET GradeID = (select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=0)
	UPDATE TA_Tbl_Employee SET Reporting_To = 0, Leave_Sanc_Authority = 0 WHERE Employee_Code_Id <> ''18000000''
	DELETE TA_Tbl_Grade WHERE Grade_ID <> (select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'' and Grade_Level=1 and IsDeleted=0)
    DELETE FROM TA_Tbl_ApprovalSettings
end	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosureDetailsForModify]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearClosureDetailsForModify]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_SelectYearClosureDetailsForModify  '''','''',''0,1'',0,0,''SuperAdmin'',''0'','''',0
Tables  : TA_Tbl_Employee, TA_Tbl_YearClosure 
Created By : Prabakaran  
Created on : 15-Oct-07    
Modified By		:	Manjula.P
Modified On		:	07-Feb-2014
Descriptions	:	Added  and ys.IsActive=1 becuase the Leave_Taken is wrongly displayed when the year closure is done then added new employee in that year 
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_SelectYearClosureDetailsForModify]  
 @EmployeeName varchar(50), 
 @EmployeeId varchar(50), 
 @LevelID varchar(8000),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(250),
 @GradeLevel varchar(20),
@EmpSwipeCard varchar(20),
@ParentId int  		
AS  
BEGIN  
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--CREATE TABLE #TempTblRecord (EmpId INT, NoOfDays DECIMAL(18, 1), YearSettingId INT)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
/*
INSERT INTO #TempTblRecord
		SELECT OTS.Employee_Id, ISNULL(SUM(OTS.NoOfDays), 0.0), YS.YearSettings_Id FROM TA_Tbl_OverTimeStatus OTS 
			LEFT JOIN TA_Tbl_ProcessedData PD ON PD.Process_Rec_ID = OTS.Process_RecID
			INNER JOIN TA_Tbl_Employee Emp ON PD.Employee_Code_Id = Emp.SwipeCardNo
			LEFT JOIN TA_Tbl_Emp_LeavePolicy ELP ON ELP.EmployeeId = Emp.Employee_Id
			LEFT JOIN TA_Tbl_LeavePolicy LP ON LP.Policy_Id = ELP.LeavePolicy_Id
			INNER JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = ELP.YearSettingId
			WHERE 
				OTS.OverTimeStatus = ''Approved'' AND
				ISNULL(OTS.CompOffSatus, ''Not Taken'') != ''Expired'' AND
				OTS.CompOffEligible = 1 AND			
				OTS.[Date] BETWEEN YS.FromDate AND YS.ToDate AND
				CONVERT(VARCHAR(11), OTS.[DateToExpired], 101) >= CONVERT(VARCHAR(11), GETDATE(), 101) AND
				YS.IsActive = 1
			GROUP BY OTS.Employee_Id, YS.YearSettings_Id
	UPDATE #TempTblRecord SET NoOfDays = NoOfDays - LeaveTaken FROM #TempTblRecord TR
	LEFT JOIN (SELECT LA.Employee_Id, ISNULL(SUM(LA.NumberOfDays), 0.0) [LeaveTaken] FROM TA_Tbl_LeaveApplication LA
	LEFT JOIN TA_Tbl_Employee Emp ON Emp.Employee_Id = LA.Employee_Id
	LEFT JOIN TA_Tbl_YearSetting YS ON YS.YearSettings_Id = LA.YearSettings_Id
	WHERE
		((LA.Leave_FromDate BETWEEN YS.FromDate AND YS.ToDate) AND
		(LA.Leave_ToDate BETWEEN YS.FromDate AND YS.ToDate)) AND
		LA.[Type] = ''Comp Off'' AND
		LA.[Status] != ''Rejected'' AND
		LA.IsDeleted=0 AND
		Emp.CompOff_Eligible = 1 AND
		Emp.OT_Eligible = 1 AND
		Emp.Isdeleted = 0
	GROUP BY LA.Employee_Id) Tbl ON Tbl.Employee_Id = TR.EmpId 
*/
declare @sqlQuery as varchar(8000)  
SET @sqlQuery='''' 
SET @sqlQuery=''select yc.YearClosureId,emp.Employee_code_Id,(emp.Employee_FirstName + '''' '''' + emp.Employee_LastName) as EmployeeName, ''
SET @sqlQuery = @sqlQuery + '' lt.LeaveType,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Leave_Taken,yc.Available_Leaves,Encashment 
,emp.Gender,yc.LeaveTypeID,emp.Employee_Id'' 
--,ISNULL(YC.Carry_PrevYearCompOff, TR.NoOfDays) [Carry_PrevYearCompOff] ''
SET @sqlQuery = @sqlQuery + '' from ta_tbl_yearclosure yc ''
SET @sqlQuery = @sqlQuery + '' inner join Ta_tbl_employee emp  on emp.Employee_Id=yc.Employee_Id ''
SET @sqlQuery = @sqlQuery + '' inner join Ta_tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeId ''
  SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on emp.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
  SET @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
  SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation EDesig ON emp.Employee_Id=EDesig.EmployeeID''
  SET @sqlQuery = @sqlQuery + '' INNER join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId ''
  SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''
SET @sqlQuery = @sqlQuery + '' inner join Ta_tbl_Yearsetting ys on ys.YearSettings_Id=yc.Year_SettingId ''
  SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on emp.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
  SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
  SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on emp.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
  SET @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''	
--SET @sqlQuery = @sqlQuery + '' LEFT JOIN #TempTblRecord TR ON TR.EmpId = emp.Employee_Id AND ys.YearSettings_Id = TR.YearSettingId''
SET @sqlQuery = @sqlQuery + '' where emp.Isdeleted=0 and emp.employee_Status=1 and lt.Isdeleted=0 and ys.IsActive=1''  
--SET @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = emp.Employee_Id AND EffectiveDate <='''''' + cast(getdate() as nvarchar(50))  + '''''' order by EffectiveDate desc)''
--SET @sqlQuery = @sqlQuery + '' and EDesig.EffectiveDate=(select top 1 EffectiveDate FROM TA_Tbl_EmployeeDesignation WHERE EmployeeId=emp.Employee_Id AND EffectiveDate <='''''' + cast(getdate() as nvarchar(50))  + '''''' order by EffectiveDate desc)''
--SET @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeCategory where EmployeeId = emp.Employee_Id AND EffectiveDate <='''''' + cast(getdate() as nvarchar(50))  + '''''' order by EffectiveDate desc)''
--SET @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeType where EmployeeId = emp.Employee_Id AND EffectiveDate <='''''' + cast(getdate() as nvarchar(50))  + '''''' order by EffectiveDate desc)''  
  if(@UserGroupName<>''SuperAdmin'')
  begin
	SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
  end
  --if not(@LevelID='''' or @LevelID=''0'')  
  --begin  
   --SET @sqlQuery = @sqlQuery + '' And (#EmpLevel.levelId In ('' + @LevelID + ''))''  
  --End  
  if not(@EmployeeName='''' or @EmployeeName=''0'')  
  begin  
   --set @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''  
   SET @sqlQuery = @sqlQuery + ''and (emp.Employee_FirstName + '''' '''' + isnull(emp.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
  end  
  if not(@EmployeeId='''' or @EmployeeId=''0'')  
  begin  
   SET @sqlQuery = @sqlQuery + ''and (emp.Employee_Code_Id='''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
  end  
 If Not (@EmpSwipeCard = '''')  
    Begin  
		  Set @sqlQuery = @sqlQuery + '' And emp.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End
  if(@employeeCategory<>0)
	begin
		SET @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
	end	
  SET @sqlQuery = @sqlQuery + '' order by emp.Employee_FirstName''   
	Create table #final(YearClosureId int,Employee_Code_Id nvarchar(200),
		EmployeeName nvarchar(200),LeaveType nvarchar(20),Carry_PrevYear decimal(18,1),
		Current_Quota decimal(18,1),Borrow_NextYear decimal(18,1),Leave_Taken decimal(18,1),
		Available_Leaves decimal(18,1),Encashment decimal(18,1),Gender varchar(6),LeaveTypeID int,EmployeeAutoId int)
	insert into #final exec(@sqlQuery) 
	update #final set Available_Leaves=RemainingNoOfLeaves,Leave_Taken=a.numberofdayAvailed from #final 
	inner join(
	Select yc.Employee_Id,(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		,yc.LeaveTypeID,ISNULL(sum(la.NumberOfDays),0.0)as numberofdayAvailed from TA_tbl_Yearclosure yc
		--Added  and ys.IsActive=1 becuase the Leave_Taken is wrongly displayed when the year closure is done then added new employee in that year by MAnjula.P on 07-Feb-2014
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id and ys.IsActive=1
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id and la.Status<>''Rejected'' and la.IsDeleted=0
		Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,yc.Employee_Id
		)
		as a on #final.EmployeeAutoId=a.Employee_Id and #final.LeaveTypeID =a.LeaveTypeID
select * from #final
--Remove the temporary tables here
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
--DROP TABLE #TempTblRecord
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectYearClosuredetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectYearClosuredetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_TA_SelectYearClosuredetails 5,''1'',''SuperAdmin''
CREATE  procedure [dbo].[Proc_TA_SelectYearClosuredetails]     
(    
@YearSettingId INT,    
@OrgLeavelID nvarchar(4000),
@UserGroupName varchar(250)  
)    
AS 
Begin
	declare @sql nvarchar(2000)  
	set @sql=''''    
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@OrgLeavelID) as LevelId 
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	--SELECT * FROM #EmpLevel
	set @sql=@sql+ ''select * from TA_Tbl_YearClosure ''
	set @sql=@sql + ''inner join #EmpLevel on #EmpLevel.LevelId=TA_Tbl_YearClosure.OrgLevelId and #EmpLevel.EmployeeId=TA_Tbl_YearClosure.Employee_Id''
	set @sql=@sql + '' where Year_SettingID=''+ cast(@YearSettingId as nvarchar) + ''''  
	exec(@sql)
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectWorkingDays]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectWorkingDays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectWorkingDays 5,2009
-- =============================================
CREATE PROCEDURE  [dbo].[Proc_TA_SelectWorkingDays]
	 @SelectedMonth nvarchar(20),  
	 @SelectedYear nvarchar(20) 
AS
BEGIN
	declare @FromDate as nvarchar(15)
	declare @ToDate as nvarchar(15)
	set @FromDate = cast(@SelectedMonth as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
	if (@SelectedMonth=12)
		Begin
			set @ToDate =  ''01/'' + ''01/'' + cast(@SelectedYear+1 as nvarchar(20))
		End
	Else
		Begin
			set @ToDate = cast(@SelectedMonth+1 as nvarchar(20)) + ''/'' + ''01/'' + cast(@SelectedYear as nvarchar(20))
		End	
	select dbo.fn_TA_CountNumberOfWorkingDays(@FromDate,@ToDate) as TotalWokingDays
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectSwipesHandling]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectSwipesHandling]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_SelectSwipesHandling ''1'','''','''',0,0,''01/01/2019'',''05/31/2019'',''All'',''All'',''1'','''',''superadmin'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_SelectSwipesHandling]
	@Employee_ID int,
	@EmployeeID as varchar(100),
	@EmployeeName as varchar(100),
	@employeeCategory as int,
	@employeeType as int,
	@FromDate as datetime,
	@ToDate as datetime,
	@SwipesType as varchar(15), 
	@VoidUnVoid as varchar(15),
	@LevelID as varchar(8000),
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
    @ParentID int  
AS
BEGIN
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	DECLARE @dateFormat as int
	Select @dateFormat=dateformat from Func_TA_GetDateTimeFormat()
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	CREATE TABLE #TempClockDetails
	(
		[CLK_ID] [bigint],
		[CLK_CARDID] [nvarchar](20) NULL,
		[CLK_DEVICEID] [nvarchar](20) NULL,
		[CLK_DATE] [datetime] NULL,
		[CLK_TIME] [nvarchar](25) NULL,			
		[ReasonId] [int] NULL,
		employee_code_id varchar(50)
	)
	Declare @DynamicSQL varchar(max)
	set @DynamicSQL=''''
	set @DynamicSQL=@DynamicSQL+''insert into #TempClockDetails
	select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME,ReasonId,e.Employee_Code_Id
	from TA_Tbl_Clk_RawData CR
	inner join TA_Tbl_Employee E on CR.CLK_CARDID=E.SwipeCardNo
	inner join #EmpLevel el on el.employeeid=e.employee_id
	where CLK_DATE between''''''+CONVERT(varchar(20),@FromDate)+''''''and''''''+CONVERT(varchar(20),@ToDate)+''''''''
	if(@VoidUnVoid=''Void'')
	begin
		set @DynamicSQL=@DynamicSQL+ '' and isnull(ReasonId,0)=6''
	end
	else if(@VoidUnVoid=''un-Void'')
	begin
		set @DynamicSQL=@DynamicSQL+ '' and isnull(ReasonId,0)=0''
	end
	else
	begin
		set @DynamicSQL=@DynamicSQL+ '' and isnull(ReasonId,0) in(6,0)''
	end
	Execute(@DynamicSQL)
	Declare @SelectSQL As Varchar(6000)      
	Set @EmployeeName = @EmployeeName + ''%''      
	Set @SelectSQL = '' ''        
	
	Set @SelectSQL = @SelectSQL + ''SELECT	CD.Clk_ID,
											ED.employee_code_id AS EmployeeCode,
											ED.Employee_FirstName + '''' '''' + isnull(ED.Employee_LastName,'''''''') AS ''''EmpName'''',
											CONVERT(VARCHAR,CD.CLK_DATE,''+ cast(@dateFormat as varchar(100)) +'') as InDate,
											Convert(varchar(10),CD.CLK_TIME,108) as InTime,
											case when ReasonId=6 then ''''True'''' else ''''False'''' end as IsVoid,
											'''''''' as ClockDate,
											'''''''' as OutDate,
											'''''''' as OutTime
											''
	Set @SelectSQL = @SelectSQL + '' FROM TA_Tbl_Employee ED ''      
	Set @SelectSQL = @SelectSQL + '' INNER JOIN #TempClockDetails CD ON ED.SwipeCardNo = CD.CLK_CARDID''	
	set @SelectSQL = @SelectSQL + '' Inner join #EmpLevel on  #EmpLevel.employeeid=ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpType on #EmpType.employeeid=ED.Employee_Id ''
	set @SelectSQL = @SelectSQL + '' Inner join #EmpCategory on #EmpCategory.employeeid=ED.Employee_Id ''
	Set @SelectSQL = @SelectSQL + '' Where  ED.IsDeleted = ''''0'''' and ED.report_exclude=0 and ED.employee_status=1 
	and ED.Employee_FirstName + case when ED.Employee_MiddleName is not null then '''' '''' + cast(ED.Employee_MiddleName as varchar(50)) 
	else '''' '''' end + isnull(ED.Employee_LastName,'''''''') like '''''' + @EmployeeName + '''''' ''  
	If Not (@EmployeeId = '''')      
		Begin      
			Set @SelectSQL = @SelectSQL + ''And ED.employee_code_id = '''''' + @EmployeeId + '''''' ''      
		End      	      
	if(@isReportingto > 0)
            BEGIN
               set @SelectSQL = @SelectSQL + '' and (ED.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If Not (@EmpSwipeCard = '''')  
		Begin  
			Set @SelectSQL = @SelectSQL + '' And ED.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End
	if(@employeeCategory<>0 and @employeeCategory<>'''')
		begin
			set @SelectSQL = @SelectSQL + '' And #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar) 
		end
	if(@employeeType<>0 and @employeeType<>'''')
		begin
			set @SelectSQL = @SelectSQL + '' And #EmpType.TypeId = '' + cast(@employeeType as nvarchar) 
		end     
	--if (@VoidUnVoid=''Void'')
	--	Begin
	--		set @SelectSQL = @SelectSQL + '' And CD.ReasonId=6''
	--	End
	--if (@VoidUnVoid=''Un-Void'')
	--	Begin
	--		set @SelectSQL = @SelectSQL + ''  And CD.ReasonId=0''
	--	End
	Exec (@SelectSQL)
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempClockDetails
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ShowCMITechEmployeeInGrid]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <26-Jan-2020>
-- Description:	<Show Employee info in Grid - CMI Tech>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ShowCMITechEmployeeInGrid]
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @DATEFORMAT AS INT
	DECLARE @TIMEFORMAT AS NVARCHAR(10)
	SELECT @DATEFORMAT=DATEFORMAT,@TIMEFORMAT=TIMEFORMAT FROM [DBO].[FUNC_TA_GETDATETIMEFORMAT]()
	
	--New Employee Records
	Select isnull(EmployeeId,'''') as EmployeeId, isnull(EmployeeName,'''') as EmployeeName,
	CONVERT(VARCHAR, getdate(), @DATEFORMAT)  as DOJ
	,''Staff'' as Designation
	,''Angler Technologies India Pvt Ltd'' as CompanyName
	from TA_Tbl_CMITechSyncEmployeeInfo a
	left outer join TA_Tbl_Employee b on b.Employee_Code_Id = a.EmployeeId
	where b.Employee_Code_Id is null
	
	--Already Existing records	
	Select isnull(b.Employee_Id,'''') as EmployeeId, isnull(b.Employee_FirstName,'''') as EmployeeName,
	CONVERT(VARCHAR, b.DateOfJoining, @DATEFORMAT)  as DOJ
	,c.TitleName as Designation
	,e.name as CompanyName
	from TA_Tbl_CMITechSyncEmployeeInfo a
	inner join TA_Tbl_Employee b on b.Employee_Code_Id = a.EmployeeId
	inner join TA_Tbl_EmployeeDesignation f on f.EmployeeID = b.Employee_Id
	inner join TA_Tbl_Title c on c.TitleId = f.DesignationID
	inner join TA_Tbl_EmployeeLevel d on d.EmployeeId = b.Employee_Id
	inner join Ta_Tbl_levelDetails e on e.id =d.LevelId

END



' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours ''06/14/2020'',420,''Approved'',4,4
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_UpdateClockTimingBasedOnApprovedTimeSheetHours]	
	@ShiftDate datetime,
	@ApprovedMinutes int,
	@status varchar(50),
	@approvedby bigint,
	@Task_EmployeeID bigint
AS
BEGIN
	SET NOCOUNT ON;
	IF(@status=''Approved'')
	BEGIN
		if(@ApprovedMinutes!=0)
		BEGIN
			/************************Get Shift Details for the current Date******************/
			Create table #TempShiftID(Shiftid int)				
			Insert into #TempShiftID(Shiftid)				
			select pd.Shift_Id from TA_Tbl_ProcessedData pd
			inner join TA_Tbl_Employee E on pd.Employee_Code_Id=E.SwipeCardNo
			where E.Employee_Id=@Task_EmployeeID and Isdeleted=0
			/*Shift is not available get default / no shift for allocation based on the employeee level*/
			IF Not EXISTS(SELECT Shiftid FROM #TempShiftID)
			BEGIN
				Declare @EmpLevelID int
				/*********Get Employee Level details for get***********/
				create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
				insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
				(
					select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
					inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
					where emp.Isdeleted=0 
					and(emp.Employee_Id=@Task_EmployeeID)
					group by EmployeeId
				) ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
				AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
				select @EmpLevelID=LevelId from #EmpLevel
				DECLARE @CompanyId INT
				IF(ISNULL(@EmpLevelID,'''')!='''')
				BEGIN						
					;with getCompanyID
					as
					(
						SELECT id,parentId FROM Ta_Tbl_levelDetails where id=@EmpLevelID
						union all
						select ld.id,ld.parentId from getCompanyID gc
						inner join Ta_Tbl_levelDetails ld on ld.id=gc.parentId
					)
					select top 1 @CompanyId=id from getCompanyID where parentId=0
				end
				/************************Get Default or No shift for allocation ******************/
				if exists(select Shift_Id from TA_Tbl_Shift where DefaultShift=1)
				begin
					Insert into #TempShiftID(Shiftid)
					select Shift_Id from TA_Tbl_Shift where DefaultShift=1 and Level_Id=@CompanyId
				END
				ELSE
				BEGIN
					Insert into #TempShiftID(Shiftid)
					SELECT Shift_Id FROM TA_Tbl_Shift WHERE Shift_ShortName =''Nos'' AND IsDeleted = 0
				END
			END
			/*Shift is not available get default / no shift for allocation based on the employeee level*/
			IF EXISTS(SELECT Shiftid FROM #TempShiftID)
			BEGIN
				IF((SELECT top 1 Shiftid FROM #TempShiftID)!=-1)
				BEGIN
					DECLARE @currentDayShiftID int
					DECLARE @ShiftStartTime varchar(20)
					Declare @Break2StartTime varchar(20)
					Declare @Break2EndTime varchar(20)
					Declare @Break2Diff int
					SELECT @currentDayShiftID =Shiftid FROM #TempShiftID
					select @ShiftStartTime=Shift_StartTime,@Break2StartTime=Shift_BreakStartTime2,@Break2EndTime=Shift_BreakEndTime2 from TA_Tbl_Shift where Shift_Id=@currentDayShiftID and Isdeleted=0
					select @Break2Diff=isnull(DATEDIFF(minute,convert(datetime,@Break2StartTime),convert(datetime,@Break2EndTime)),0)
					if(@ShiftStartTime!='''')
					begin						
						Declare @ManualEntry_EmployeeId NVARCHAR(20)
						Declare @ManualEntry_Date DATETIME
						Declare @InDate NVARCHAR(15)
						Declare @InTime NVARCHAR(20) 
						Declare @InPunchType NVARCHAR(25)
						Declare @OutDate NVARCHAR(15)
						Declare @OutTime NVARCHAR(20)
						Declare @OutPunchType NVARCHAR(25)
						Declare @InReader_Id INT
						Declare @OutReader_Id INT  
						Declare @Reason NVARCHAR(255)
						Declare @RouteId INT
						Declare @TimeStamp DATETIME
						Declare @UserId INT
						Declare @YearSettings_Id NVARCHAR(25)
						Declare @IsOnDuty INT
						Declare @IsImported int
						DECLARE @ShiftEndTime datetime
						IF EXISTS(SELECT Entrance_Id FROM TA_Tbl_Entrance where Entrance_Name=''TimecheckPhase'')
						BEGIN								
							Declare @CountDevice int	
							Declare @InDeviceAutoID int
							Declare @OutDeviceAutoID int
							select @CountDevice=COUNT(distinct Reader_Id)from TA_Tbl_Entrance_INOUTDetails 	EIO
							inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
							where Entrance_Name=''TimecheckPhase''							
							IF(@CountDevice=1)
							BEGIN
								select distinct @InDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name=''TimecheckPhase''								
								SELECT @InReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@InDeviceAutoID
								set @OutReader_Id=@InReader_Id
								set @OutDeviceAutoID=@InDeviceAutoID
							END
							ELSE
							BEGIN
								select top 1 @InDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name=''TimecheckPhase'' and EIO.Type=''In''
								select top 1 @OutDeviceAutoID=Reader_Id from TA_Tbl_Entrance_INOUTDetails 	EIO
								inner join TA_Tbl_Entrance E on E.Entrance_Id=EIO.Entrance_Id
								where Entrance_Name=''TimecheckPhase'' and EIO.Type=''Out''
								SELECT @InReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@InDeviceAutoID
								SELECT @OutReader_Id=Terminal_ReaderID FROM TA_Tbl_Terminal where Terminal_Id=@OutDeviceAutoID								
							END
							select top 1 @InPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@InDeviceAutoID
							and PunchType in(''Shift In'',''In'')
							select top 1 @OutPunchType=PunchType from TA_Tbl_PunchTypes where Terminal_Id=@OutDeviceAutoID
							and PunchType in(''Shift Out'',''Out'')
							select @ManualEntry_EmployeeId=Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@Task_EmployeeID
							select @YearSettings_Id=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
							set @ManualEntry_Date=CONVERT(varchar(11), GETDATE())
							set @OutDate=CONVERT(varchar(11),CONVERT(datetime,@ShiftDate))
							set @InDate=@OutDate
							set @InTime=@ShiftStartTime
							set @ShiftEndTime=DATEADD(minute,@ApprovedMinutes+@Break2Diff,@ShiftStartTime)
							set @OutTime=case when len(ltrim(right(convert(varchar, @ShiftEndTime, 22),11)))=10 then ''0''+right(convert(varchar, @ShiftEndTime, 22),10) else right(convert(varchar, @ShiftEndTime, 22),11) end
							set @Reason=''TimeSheet Entry - Automatic Time Updation''
							set @RouteId=0
							set @TimeStamp=GETDATE()
							set @UserId=@approvedby
							set @IsOnDuty=0
							set @IsImported=4
							--select  @ManualEntry_EmployeeId,@ManualEntry_Date,@InDate,@InTime,@InPunchType,@OutDate,
							--@OutTime,@OutPunchType,@InReader_Id,@OutReader_Id,@Reason,@RouteId,@status,@TimeStamp,@UserId,@YearSettings_Id,@IsOnDuty,@IsImported;
							if exists(select ManualTimeEntry_Id from TA_Tbl_ManualTimeEntry where ManualTimeEntry_Employee_Id=@ManualEntry_EmployeeId
							and ManualTimeEntry_InDate=@InDate and ManualTimeEntry_InPunchType=@InPunchType
							and ManualTimeEntry_OutDate=@OutDate and ManualTimeEntry_InPunchType=@OutPunchType and IsImported=@IsImported)
							BEGIN
								update TA_Tbl_ManualTimeEntry set ManualTimeEntry_InTime=@InTime,ManualTimeEntry_OutTime=@OutTime,Clk_Process=''N''
								where ManualTimeEntry_Employee_Id=@ManualEntry_EmployeeId
								and ManualTimeEntry_InDate=@InDate and ManualTimeEntry_InPunchType=@InPunchType
								and ManualTimeEntry_OutDate=@OutDate and ManualTimeEntry_InPunchType=@OutPunchType and IsImported=@IsImported
							END
							ELSE
							BEGIN
								Execute [Proc_TA_InsertManualTimeEntry]	@ManualEntry_EmployeeId,@ManualEntry_Date,@InDate,@InTime,@InPunchType,@OutDate,
								@OutTime,@OutPunchType,@InReader_Id,@OutReader_Id,@Reason,@RouteId,@status,@TimeStamp,@UserId,@YearSettings_Id,@IsOnDuty,@IsImported;
							end
						END
					END
				END
			END			
		END
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetAllShiftPatterns]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetAllShiftPatterns]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/* Abul: Gets all the shift patterns */
CREATE Proc [dbo].[Proc_TA_GetAllShiftPatterns]
As
select * from TA_Tbl_ShiftPattern
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Modified BY		: Manikandan.RR
Created Date	:	17-03-2018
-- Modified By:Manikandan.RR
-- Modified Date:12-Jul-2019 03:45 PM
Descriptions	:	Creating Proc_TA_FillingLeaveTypesforEmployeeMaster proc for loading leave type details for employee modifiy page
[Proc_TA_FillingLeaveTypesforEmployeeMaster] 4,2
*/
CREATE proc [dbo].[Proc_TA_FillingLeaveTypesforEmployeeMaster]
(
	@EmployeeId int,
	@YearSettingsId int
)
as
begin
	SET NOCOUNT ON;
	--Declaring variables
	declare @CurrentYear as int;
	declare @getFirstPreviousYearCount as int;
	declare @EndYear as int;
	declare @UsedCount as int;
	--Initializing variables
	set @EndYear=0;
	set @getFirstPreviousYearCount=0;
	set @CurrentYear=0;
	set @UsedCount=0;
	--getting current financial year
	select @CurrentYear=StartYear,@EndYear=EndYear from TA_Tbl_YearSetting where YearSettings_Id=@YearSettingsId and IsActive=1
	--select @getFirstPreviousYearCount=COUNT(*) from TA_Tbl_YearSetting where StartYear<@CurrentYear and EndYear<@EndYear
	--select @getFirstPreviousYearCount
	--Commented by Manikandan.RR for loading leaveType for every year concept. on 17-03-2018	
	--This point implemented for version 2.7 below version it wont load the controls for every year.i.e it will load for current year only.
	--if(@getFirstPreviousYearCount=0)
	--	begin
	Declare @PrevYear int
	set @PrevYear=0
	--if(@getFirstPreviousYearCount!=0)
	--begin
	Declare @PrevYearID int
	select top 1 @PrevYearID=YearSettings_Id from TA_Tbl_YearSetting where YearSettings_Id<@YearSettingsId order by YearSettings_Id desc
	if Exists(select YearClosed from TA_Tbl_YearClosure where Year_SettingID=@PrevYearID and YearClosed is not null)
	begin
		set @PrevYear=1
	end
	--end
	if(@PrevYear=0)
	begin
		if ((select count(LeaveTypeDetailsId) from ta_tbl_emp_LeaveTypedetails where EmployeeId=@EmployeeId and YearSettingsId=@YearSettingsId)>0)
			begin
				select LT.LeaveType_Id as Emp_LeaveType_Id,LeaveType=LT.LeaveDescription+'' (''+LT.LeaveType+'')'',LTD.PreviousYearBalance,LTD.NoOffLeaveAvailed from ta_tbl_emp_LeaveTypedetails LTD
				right join	ta_tbl_leaveType LT on LTD.LeaveTypeId=LT.LeaveType_Id
				where (LTD.EmployeeId=@EmployeeId and LTD.YearSettingsId=@YearSettingsId and lt.IsDeleted=0)
				or(LT.LeaveType_Id not in(select ELTemp.LeaveTypeId from ta_tbl_emp_LeaveTypedetails ELTemp))
				select ''true'' as valid
				select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
			end
		else
			begin
				select LeaveType_Id as Emp_LeaveType_Id,LeaveType=LeaveDescription+'' (''+LeaveType+'')'',0 as PreviousYearBalance,0 as NoOffLeaveAvailed from ta_tbl_leavetype where IsDeleted=0
				select ''false'' as valid
				select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
			end
	end
	else
		begin
			select LeaveType_Id as Emp_LeaveType_Id,LeaveType=LeaveDescription+'' (''+LeaveType+'')'',isnull(LEV.PreviousYearBalance,0) as PreviousYearBalance,isnull(LEV.NoOffLeaveAvailed,0) as NoOffLeaveAvailed from TA_Tbl_LeaveType
			left outer join ta_tbl_emp_LeaveTypedetails LEV on LEV.EmployeeId = @EmployeeId and TA_Tbl_LeaveType.LeaveType_Id = LEV.LeaveTypeId
			select ''false'' as valid
			select @UsedCount=COUNT(*) from TA_Tbl_LeaveApplication where Employee_Id=@EmployeeId and IsDeleted=0 and YearSettings_Id=@YearSettingsId
		end
	select @UsedCount as UsedCount;
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportTempShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportTempShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/* 
Procedure Name : Proc_TA_RptTempShiftAllocation  ''01/01/2008'',''12/27/2012'','''','''','''','''','''',''SuperAdmin'','''','''',0,0,''Both''
Tables  : TA_Tbl_Employee and TA_Tbl_TemporaryShiftAllocation  
Created By : Prabakaran  
Created on : 3-Aug-07 
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ExportTempShiftAllocation]  
(
 @Employee_ID int,
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10)	
)	
AS  
BEGIN  
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) AS LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Level INSERT in Temporary table
	INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	SELECT max(el.EffectiveDate) AS EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation INSERT in Temporary table
	INSERT INTO #EmpDesignation SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	SELECT max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type INSERT in Temporary table
	INSERT INTO #EmpType SELECT EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	SELECT max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category INSERT in Temporary table
	INSERT INTO #EmpCategory SELECT EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	SELECT max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 GROUP by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat AS nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @sqlQuery AS varchar(8000)  
	SET @sqlQuery=''''  
	SET @sqlQuery = ''SELECT e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') AS Employee_FirstName,e.employee_code_id AS employee_id,ts.Year,ts.Month,ts.Day1Shift,ts.Day2Shift,ts.Day3Shift,ts.Day4Shift,ts.Day5Shift,ts.Day6Shift,ts.Day7Shift,ts.Day8Shift,ts.Day9Shift,ts.Day10Shift,ts.Day11Shift,ts.Day12Shift,ts.Day13Shift,ts.Day14Shift,ts.Day15Shift,ts.Day16Shift,ts.Day17Shift,ts.Day18Shift,ts.Day19Shift,ts.Day20Shift,ts.Day21Shift,ts.Day22Shift,ts.Day23Shift,ts.Day24Shift,ts.Day25Shift,ts.Day26Shift,ts.Day27Shift,ts.Day28Shift,ts.Day29Shift,ts.Day30Shift,ts.Day31Shift,ts.emp_id,ts.TimeStamp,ts.DateShift,TA_Tbl_Title.TitleName AS TitleName,e.Gender,
	[dbo].[Func_TA_GetParentIds](Ta_Tbl_levelDetails.id) as ParentLevelId 
	from TA_Tbl_TemporaryShiftAllocation ts 
	inner join TA_Tbl_Employee e on e.Employee_Id=ts.EmployeeId ''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	SET @sqlQuery = @sqlQuery + '' where e.Isdeleted=0 and e.employee_Status=1 and e.Report_exclude=0 ''  
	SET @sqlQuery=@sqlQuery + '' and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat AS nvarchar(20)) + '''''', 102)) AS nvarchar(20))+''''/''''+ cast(1 AS nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat AS nvarchar(20)) +'''''', 102 ))AS nvarchar(10)),102) ''
	SET @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat AS nvarchar(20)) + '''''', 102)) AS nvarchar(20))+''''/''''+ cast(1 AS nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat AS nvarchar(20)) + '''''', 102 ))AS nvarchar(10)),102)''
	if not(@EmployeeName='''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName + '''' '''' +  isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' AS nvarchar(100)) + '''''')''
		END
	If Not (@EmpSwipeCard = '''')  
		BEGIN  
			Set @sqlQuery = @sqlQuery + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if not(@EmployeeId='''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId AS nvarchar(100)) + '''''')''  
		END  
	if(@Gender<>''Both'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender AS nvarchar(8)) + '''''' ''
		END	
	if(@DesignationID<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID AS nvarchar(8))
		END	
	if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END	
	if(@employeeType<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType AS nvarchar(8))
		END		
	if(@employeeCategory<>0)
		BEGIN
			SET @sqlQuery = @sqlQuery + '' and #EmpCategory.CategoryId = '' + cast(@employeeCategory AS nvarchar(8))
		END
	SET @sqlQuery = @sqlQuery + '' order by e.employee_code_id,e.Employee_FirstName,ts.Year,ts.Month''   
	create table #TempExportShift
	(
	Employee_FirstName varchar(250),
	employee_id varchar(50),
	Year int,
	Month int,
	Day1Shift int,
	Day2Shift int,
	Day3Shift int,
	Day4Shift int,
	Day5Shift int,
	Day6Shift int,
	Day7Shift int,
	Day8Shift int,
	Day9Shift int,
	Day10Shift int,
	Day11Shift int,
	Day12Shift int,
	Day13Shift int,
	Day14Shift int,
	Day15Shift int,
	Day16Shift int,
	Day17Shift int,
	Day18Shift int,
	Day19Shift int,
	Day20Shift int,
	Day21Shift int,
	Day22Shift int,
	Day23Shift int,
	Day24Shift int,
	Day25Shift int,
	Day26Shift int,
	Day27Shift int,
	Day28Shift int,
	Day29Shift int,
	Day30Shift int,
	Day31Shift int,
	emp_id int,
	TimeStamp datetime,
	DateShift datetime,
	TitleName varchar(250),
	Gender varchar(100),
	ParentLevelId int
	)	
	insert into #TempExportShift  
	exec(@sqlQuery)  
	create table #TempParentLevels
	(
	ParentId int,
	CompanyName varchar(300)
	)
	insert into #TempParentLevels
	select id,name from Ta_Tbl_levelDetails where parentId=0
	select Employee_FirstName,
	employee_id ,
	Year ,
	Month ,
	Day1Shift ,
	Day2Shift ,
	Day3Shift ,
	Day4Shift ,
	Day5Shift ,
	Day6Shift ,
	Day7Shift ,
	Day8Shift ,
	Day9Shift ,
	Day10Shift ,
	Day11Shift ,
	Day12Shift ,
	Day13Shift ,
	Day14Shift ,
	Day15Shift ,
	Day16Shift ,
	Day17Shift ,
	Day18Shift ,
	Day19Shift ,
	Day20Shift ,
	Day21Shift ,
	Day22Shift ,
	Day23Shift ,
	Day24Shift ,
	Day25Shift ,
	Day26Shift ,
	Day27Shift ,
	Day28Shift ,
	Day29Shift ,
	Day30Shift ,
	Day31Shift ,
	emp_id ,
	TimeStamp ,
	DateShift ,
	TitleName ,
	Gender ,LD.CompanyName as Company_Name from #TempExportShift
	inner join #TempParentLevels LD on LD.ParentId=#TempExportShift.ParentLevelId
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory
	--DROP TABLE #EmpPay
	DROP TABLE #LevelRights
	drop table #TempExportShift
	drop table #TempParentLevels
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportShiftAllocation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportShiftAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptShiftAllocation ''01/01/2014'',''12/31/2014'','''','''','''','''','''',''SuperAdmin'',1,'''',0,0,''Both''
Tables  : TA_Tbl_Employee and TA_Tbl_PermanentShiftAllocation  
Created By : Manjula.P  
Created on : 27-Aug-14    
-- Description	:	SQL Query Optimazation & Emp name filtering
exec Proc_TA_ExportShiftAllocation @fromDat=''2014-01-01 00:00:00'',
@ToDat=''2014-08-19 00:00:00'',@EmployeeName=N'''',@LevelID=N''1'',
@EmployeeId=N'''',@employeeCategory=0,@employeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',
@EmpSwipeCard=N'''',@ParentId=1,@DesignationID=0,@Gender=N''Both''
*/  
CREATE PROCEDURE [dbo].[Proc_TA_ExportShiftAllocation] 
(
 @Employee_ID int,
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000), 
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),
 @EmpSwipeCard varchar(20),
 @ParentId int,
 @DesignationID int,
 @Gender varchar(10)		
)	
AS  
BEGIN  
	SET NOCOUNT ON;
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Level insert in Temporary table
Declare @sqlEmpLevel nvarchar(4000)
Declare @sqlCommon nvarchar(4000)
set @sqlEmpLevel=
	''insert into #EmpLevel select * from [Func_TA_EmpLevel] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''')''
Execute(@sqlEmpLevel)
	--Employee Designation insert in Temporary table
Declare @sqlEmpDesi nvarchar(4000)
set @sqlEmpDesi=
''insert into #EmpDesignation select * from [Func_TA_EmpDesignation] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@DesignationID as nvarchar(8)) + '''''')''
Execute(@sqlEmpDesi)
--Employee Type insert in Temporary table
Declare @sqlEmpType nvarchar(4000)
set @sqlEmpType=
''insert into #EmpType select * from [Func_TA_EmpType] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeType as nvarchar(8)) + '''''')''	
Execute(@sqlEmpType)
--Employee Category insert in Temporary table
Declare @sqlEmpCategory nvarchar(4000)
set @sqlEmpCategory=
''insert into #EmpCategory select * from [Func_TA_EmpCategory] (CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102),'''''' + cast(@EmpSwipeCard as nvarchar(100)) + '''''','''''' + cast(@employeeCategory as nvarchar(8)) + '''''')''
Execute(@sqlEmpCategory)
--select * from #EmpLevel
	declare @sqlQuery as varchar(8000)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select  e.Employee_FirstName + space(1) +  isnull(e.Employee_LastName,'''''''') as Employee_FirstName,
	e.employee_code_id as employee_id,ps.Year,ps.Month,ps.Day1Shift,ps.Day2Shift,ps.Day3Shift,ps.Day4Shift,ps.Day5Shift,ps.Day6Shift,
	ps.Day7Shift,ps.Day8Shift,ps.Day9Shift,ps.Day10Shift,ps.Day11Shift,ps.Day12Shift,ps.Day13Shift,ps.Day14Shift,ps.Day15Shift,ps.Day16Shift,
	ps.Day17Shift,ps.Day18Shift,ps.Day19Shift,ps.Day20Shift,ps.Day21Shift,ps.Day22Shift,ps.Day23Shift,ps.Day24Shift,ps.Day25Shift,ps.Day26Shift,
	ps.Day27Shift,ps.Day28Shift,ps.Day29Shift,ps.Day30Shift,ps.Day31Shift,ps.emp_Id,ps.TimeStamp,ps.DateShift,T.TitleName as TitleName,e.Gender,
	[dbo].[Func_TA_GetParentIds](Ta_Tbl_levelDetails.id) as ParentLevelId
	from TA_Tbl_PermanentShiftAllocation ps inner join TA_Tbl_Employee e on e.Employee_Id=ps.EmployeeId''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title T ON #EmpDesignation.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade G ON T.GradeId = G.Grade_ID''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelId ''
	--set @sqlQuery = @sqlQuery + '' left outer join Ta_Tbl_levelDetails LD on LD.id=EL.LevelId  ''
	set @sqlQuery=@sqlQuery + '' where e.Isdeleted=0 and 
	 e.Report_exclude=0 and dateShift>=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, ''''''+  cast(@fromDat as nvarchar(20)) +'''''', 102 ))as nvarchar(10)),102) ''
	set @sqlQuery=@sqlQuery + '' and dateShift<=CONVERT(DATETIME,cast(month(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102)) as nvarchar(20))+''''/''''+ cast(1 as nvarchar(1)) +''''/''''+ cast(year(CONVERT(DATETIME, '''''' + cast(@ToDat as nvarchar(20)) + '''''', 102 ))as nvarchar(10)),102)''
	if not(@EmployeeName='''')  
		begin  
			--set @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		Declare @Tempname nvarchar(200)
         set @Tempname= ''(e.Employee_FirstName + '''' '''' + isnull(e.Employee_LastName,'''''''')''
	     set @sqlQuery = @sqlQuery + '' and ''+ @Tempname +''= '''''' + cast(@EmployeeName as nvarchar(100)) + '''''')'' 
		end  
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>='' + @GradeLevel  
		end
	if not(@EmployeeId='''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
		end
	set @sqlQuery = @sqlQuery + '' order by e.employee_code_id,e.Employee_FirstName,ps.Year,ps.Month''   
	create table #TempExportShift
	(
	Employee_FirstName varchar(250),
	employee_id varchar(50),
	Year int,
	Month int,
	Day1Shift int,
	Day2Shift int,
	Day3Shift int,
	Day4Shift int,
	Day5Shift int,
	Day6Shift int,
	Day7Shift int,
	Day8Shift int,
	Day9Shift int,
	Day10Shift int,
	Day11Shift int,
	Day12Shift int,
	Day13Shift int,
	Day14Shift int,
	Day15Shift int,
	Day16Shift int,
	Day17Shift int,
	Day18Shift int,
	Day19Shift int,
	Day20Shift int,
	Day21Shift int,
	Day22Shift int,
	Day23Shift int,
	Day24Shift int,
	Day25Shift int,
	Day26Shift int,
	Day27Shift int,
	Day28Shift int,
	Day29Shift int,
	Day30Shift int,
	Day31Shift int,
	emp_id int,
	TimeStamp datetime,
	DateShift datetime,
	TitleName varchar(250),
	Gender varchar(100),
	ParentLevelId int
	)	
	insert into #TempExportShift 
	exec(@sqlQuery)  
	create table #TempParentLevels
	(
	ParentId int,
	CompanyName varchar(300)
	)
	insert into #TempParentLevels
	select id,name from Ta_Tbl_levelDetails where parentId=0
	select Employee_FirstName,
	employee_id ,
	Year ,
	Month ,
	Day1Shift ,
	Day2Shift ,
	Day3Shift ,
	Day4Shift ,
	Day5Shift ,
	Day6Shift ,
	Day7Shift ,
	Day8Shift ,
	Day9Shift ,
	Day10Shift ,
	Day11Shift ,
	Day12Shift ,
	Day13Shift ,
	Day14Shift ,
	Day15Shift ,
	Day16Shift ,
	Day17Shift ,
	Day18Shift ,
	Day19Shift ,
	Day20Shift ,
	Day21Shift ,
	Day22Shift ,
	Day23Shift ,
	Day24Shift ,
	Day25Shift ,
	Day26Shift ,
	Day27Shift ,
	Day28Shift ,
	Day29Shift ,
	Day30Shift ,
	Day31Shift ,
	emp_id ,
	TimeStamp ,
	DateShift ,
	TitleName ,
	Gender ,LD.CompanyName as Company_Name from #TempExportShift
	inner join #TempParentLevels LD on LD.ParentId=#TempExportShift.ParentLevelId
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	--drop table #EmpPay
	drop table #LevelRights 	
	drop table #TempExportShift
	drop table #TempParentLevels
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_get_level_Org_Updated]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_get_level_Org_Updated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_get_level_Org_Updated 917,''533'',917,''SuperAdmin''
--Proc_TA_get_level_Org_Updated 40,''533'',40,''SuperAdmin''
--Proc_TA_get_level_Org_Updated 0,''533'',0,''SuperAdmin''
CREATE PROCEDURE [dbo].[Proc_TA_get_level_Org_Updated]
(
	@para1 int	,
	@LevelIDs nvarchar(2000),
	@ParentID int,
	@UserGroupName varchar(250)
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#LevelRights] 
	(
		[LevelId] ASC
	) ON [PRIMARY]		
	SELECT id,name,ParentId from Ta_Tbl_levelDetails 
	inner join #LevelRights on #LevelRights.LevelId=Ta_Tbl_levelDetails.id 
	where isdeleted=0 order by id
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
    -- =============================================    
Author:  Arun vinoth    
ALTER  date: 30/07/2007    
Description: select Emp Leave Policy     
Modified by : Prabakaran.P  
Modified on : 15-Feb-08  
Description : Display Employee Leave Policy of active year Based on employee Leave  
Policy Year Setting Id  
Modified By:Manikandan.RR
Modified Date:12-Jul-2019 03:45 PM
-- =============================================    
*/  
CREATE PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyLeaveDetails]     
	@EmpID INT    
AS   
BEGIN    
	SET NOCOUNT ON;    
	SELECT ELPD.Emp_LeavePolicyId,ELPD.Policy_ID,LP.PolicyName,ELPD.LeaveType_Id, L.LeaveType,ELPD.No_Of_Days ,LeaveDescription=LeaveDescription + '' (''+LeaveType+'')''
	FROM TA_Tbl_Emp_LeavePolicyDetails ELPD inner join Ta_tbl_LeavePolicy LP on ELPD.Policy_Id =LP.Policy_Id 
	inner join Ta_Tbl_Emp_LeavePolicy ELP on ELP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId 
	inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id 
	LEFT OUTER JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=ELPD.LeaveType_Id 
	WHERE ELPD.EmpID=@EmpID AND ELPD.Isdeleted=0  AND YS.Isactive=1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
    -- =============================================  
Author		:   	Prabakaran.P
ALTER  date	:   
Description	:	select Emp Leave Policy   
Modified by	:	
Modified on	:	
Description	:	Display Employee Leave Policy of active year Based on employee Leave
			Policy Year Setting Id
--Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure 152
-- =============================================  
*/
CREATE  PROCEDURE [dbo].[Proc_TA_EmpLeavePolicyDetailsForUpdateYearClosure]   
@EmpID INT  
AS 
BEGIN  
 SET NOCOUNT ON;  
SELECT ELPD.LeaveType_Id,L.LeaveType,isnull(sum(ELPD.No_Of_Days),0.0) as No_Of_Days FROM TA_Tbl_Emp_LeavePolicyDetails ELPD  inner join Ta_tbl_LeavePolicy LP on ELPD.Policy_Id =LP.Policy_Id inner join Ta_Tbl_Emp_LeavePolicy ELP on ELP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId inner join Ta_tbl_Yearsetting YS on ELP.YearSettingId=YS.YearSettings_Id LEFT OUTER JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=ELPD.LeaveType_Id WHERE EmpID=@EmpID AND ELPD.Isdeleted=0  AND YS.Isactive=1 group by ELPD.LeaveType_Id,L.LeaveType
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_delOrgLevels]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_delOrgLevels]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_delOrgLevels]
(
	@levID int,
	@opr varchar(1),
	@oprType nvarchar(20)=null
)
as
begin
	if @opr=''C''
		Begin
			declare @checkFlag  int
			set @checkFlag = 0
			declare @recCount as int
			set @recCount = (select count(*) from ta_tbl_leveldetails where parentId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from ta_tbl_employeeLevel where LevelId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Entrance where OrgLevel_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_MonthClosure where OrgLevel_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_RouteMaster where Level_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Title where LevelID=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_YearClosure where OrgLevelId=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
			set @recCount = (select count(*) from TA_Tbl_Additional_WeeklyOff where LevelId_Id=@levID)
			if (@recCount>0)
				Begin
					set @checkFlag=1
				End
		select @checkFlag as checkFlag
		end
	else		
		Begin
			if(@oprType=''TemporaryDelete'')
				Begin
					update ta_tbl_leveldetails set isdeleted=1 where id=@levID
				End
			if(@oprType=''PermanentDelete'')
				Begin
					delete from ta_tbl_leveldetails where id=@levID
				End
			if(@oprType=''CheckRestore'')
				Begin
					set @checkFlag = 0
					set @recCount = (select count(*) from ta_tbl_levelDetails where isdeleted=0 and id!=@levID and  name=(select name from ta_tbl_leveldetails where id=@levID and isdeleted=0) )
					if (@recCount>0)
						Begin
							set @checkFlag=1
						End
					select @checkFlag as checkFlag
				End
			if(@oprType=''Restore'')
				Begin
					update ta_tbl_leveldetails set isdeleted=0 where id=@levID
				End			
		End	
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_GetDiscrepanyForPayRollProcess ''01/01/2012'',''12/19/2012'',''1'',''superadmin'',0
CREATE   PROCEDURE [dbo].[Proc_TA_GetDiscrepanyForPayRollProcess]
(
    @FromDate Varchar(20),
    @EndDate Varchar(20),
    @Org_LevelID nVarchar(4000),
    @UserGroupName varchar(250),
	@ParentId int
)
AS
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	set @sqlQuery=''select *,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, clk_date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, clk_date, ''+cast(@dateFormat as varchar(100))+'') end	as clk_Date1, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, clk_indate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, clk_indate, ''+cast(@dateFormat as varchar(100))+'') end as clk_InDate1, 
	right(clk_Intime,8) as clk_intime1,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, clk_outdate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, clk_outdate, ''+cast(@dateFormat as varchar(100))+'') end as clk_outDate1, 
	right(clk_outtime,8) as clk_outtime1 
	from TA_Tbl_ClockDetails inner join #LevelRights on #LevelRights.LevelId=TA_Tbl_ClockDetails.Clk_CompId  where IsVoid=0 and (Clk_InDate is null or Clk_InTime is null or Clk_OutDate is null or Clk_OutTime is null) and Clk_Date between '''''' + @FromDate + '''''' and '''''' + @EndDate + ''''''''
	exec(@sqlQuery)' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignationByLevelId]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDesignationByLevelId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_GetDesignationByLevelId]        
@Leveld INT
AS        
BEGIN        
        SELECT TitleId,replace(TitleName,''&amp;'',''&'') as TitleName FROM TA_Tbl_Title 
		WHERE LevelId = @Leveld and isdeleted=0 order by TitleName
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDesignation]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDesignation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Proc_TA_GetDesignation
Modified By		:	Manjula.P
Modified On		:	15-Jan-2014
Descriptions	:	adding +''-''+ISNULL(LD.name,'''') as TitleName for getting level with designation name in reports filters
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetDesignation]        
AS        
BEGIN      
		--Adding left joins for getting organization name with designation name by MAnjula.P on 15-Jan-2014       
        SELECT TitleId,replace(TitleName,''&amp;'',''&'')+''-''+ISNULL(LD.name,'''') as TitleName		
		FROM TA_Tbl_Title  T
		left join Ta_Tbl_levelDetails LD on LD.id=T.LevelID	
		WHERE  T.isdeleted=0 order by TitleName
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetDashboardInformation '''', ''2020/07/20'', ''2020/07/20'',0,0,0,''SuperAdmin'',''0'',''0''
-- =============================================
create PROCEDURE [dbo].[Proc_TA_GetDashboardInformation_Old_11Aug20]
      @EMPLOYEECODEID	NVARCHAR(MAX) = NULL,
      @FROMDATE			DATETIME,
      @TODATE			DATETIME,
      @Session			INT,
      @ShiftID			INT,
      @ParentID			INT,
      @UserGroupName	NVARCHAR(100),
      @GradeLevel		NVARCHAR(20),
      @empId			NVARCHAR(MAX)
AS
BEGIN 
	set nocount on;	
	Declare @FromdateString nvarchar(20)
	declare @todat			nvarchar(20);
	Declare @NoShiftID int
	select @NoShiftID=Shift_Id from TA_Tbl_Shift where Level_Id=0 and Shift_ShortName=''NOS''
	set @todat=GETDATE();
	if @FROMDATE=''''
	begin
		  set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,GETDATE()))+''-''+CONVERT(nvarchar(20),DATEPART(month,getdate()))+''-''+
		  case when len(CONVERT(nvarchar(20),DATEPART(D,GETDATE())))=1 then ''0''+CONVERT(nvarchar(20),DATEPART(D,GETDATE()))
		  else CONVERT(nvarchar(20),DATEPART(D,GETDATE())) end
	end   
	else
	begin
		set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(nvarchar(20),DATEPART(month,@fromdate))+''-''+
		case when len(CONVERT(nvarchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(nvarchar(20),DATEPART(D,@fromdate))
		else CONVERT(nvarchar(20),DATEPART(D,@fromdate)) end
	end
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	Create table #FirstTableValue(TOPIC nvarchar(100),ValueCount int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #SecondDummyTableValue(TOPIC nvarchar(100),Count int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #ThirdDummyTableValue(Approval nvarchar(100),Approved int,Forwarded int,Pending nvarchar(100),ApprovedPercent nvarchar(30),ForwardedPercent nvarchar(30),PendingPercent nvarchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		select @groupid=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'''',''''
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	Declare @sqlEmpLevel nvarchar(4000) 
	set @sqlEmpLevel=
	''insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and emp.Employee_Code_Id<>''''18000000''''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) and EL.LevelId is not null''    
	if(@isReportingto > 0)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + '' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) ''  
		END   
	if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + '' and ELevel.EmployeeId in (''+CAST(@empId as nvarchar(10))+'')''
		END   
	execute(@sqlEmpLevel)
	--select * from #EmpLevel
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeecountQuery nvarchar(4000)
	Declare @EmployeePresentcountQuery nvarchar(4000)     
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode=''Present'' or ANAttendanceCode=''Present'') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  WHERE P.DATE=@FromdateString
			  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
	
	
	Declare @FirstBoard		nvarchar(MAX)
	Declare @FirstBoard1	nvarchar(MAX)
	Declare @SecondBoard	nvarchar(MAX)
	Declare @ThirdBoard		nvarchar(MAX)
	Declare @FourthBoard	nvarchar(MAX)
	Declare @FifthBoard		nvarchar(MAX)
	Declare @sixthBoard		nvarchar(MAX)
	Declare @Present_Filters nvarchar(MAX)
	Declare @Absetn_Filters	nvarchar(MAX)
	Declare @Leave_Filters	nvarchar(MAX)
	Declare @Union			nvarchar(MAX)
	set @Union='' Union All ''
	IF ((ISNULL(@FROMDATE, '''') <> ''''))
	BEGIN
		--First Gridview Control
		Declare @CommonJoinQueries nvarchar(MAX)         
		Declare @CommonSelectQueries nvarchar(MAX) 
		set @FirstBoard=''''      
		Declare @Firstboardexists int
		set @Firstboardexists=0
		set @CommonJoinQueries=''''
		set @CommonJoinQueries=@CommonJoinQueries+'' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
		INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
		INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
		Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
		set @CommonSelectQueries=''''
		set @CommonSelectQueries=@CommonSelectQueries+''select 
			  TOPIC,
			  COUNT,
			  HYPER,
			  REPORTNAME, 
			  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
						  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeeCount)+'' * 100)),0))+'''' %'''' 
			  End''
		Declare @Filters nvarchar(MAX)
		set @Filters=''''
		if(@ShiftID!=0)
		begin
			  set @Filters =@Filters+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
		end
		if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			  SET @Filters = @Filters + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END
		-- Added below line by manikandan.r on 16-11-2016
		-- if you remove below line it will bring wrong value for absent column.bug id:0035540
		if(@isReportingto > 0)
		BEGIN  
			  SET @Filters = @Filters + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
		End
		--Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  set @FirstBoard =@CommonSelectQueries+'' as PercentageValue from 
			  (
					SELECT DISTINCT ''''Present'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''MonthlyAttendance'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''       
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
					AND (FNAttendanceCode=''''Present'''' or ANAttendanceCode=''''PRESENT''''or (FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' and (intime<>''''00:00'''' or outtime<>''''00:00''''))
					or (FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''Holiday'''' and (intime<>''''00:00'''' or outtime<>''''00:00'''')))
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as Present''
			  set @Firstboardexists=1
		end
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard =@FirstBoard+@CommonSelectQueries+'' as AbsenteesPercent from 
			  (
					SELECT DISTINCT ''''Absent'''' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''''Absentees'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
					set @FirstBoard=@FirstBoard+@CommonJoinQueries        
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND 
					(ANAttendanceCode=''''ABSENT'''' AND FNAttendanceCode=''''Absent'''') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''
			  set @FirstBoard=@FirstBoard+@Filters+'') as Absent''
			  set @Firstboardexists=1
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin
			  declare @LeaveCount nvarchar(MAX)
			  --Getting Leave Data          
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+'' as LeavePercent from 
			  (
					SELECT DISTINCT ''''Approved Leave'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''Leave_Angler'''' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P''        
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
					AND 
					(
						  FNAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') or
						  ANAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')
					)
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as Leave''
			  set @Firstboardexists=1
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '' as OnDutyPercent from (
			  SELECT DISTINCT ''''Approved OnDuty'''' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''''OnDuty'''' AS REPORTNAME 
			  FROM Ta_Tbl_ManualTimeEntry M
			  inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
			  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and 
			  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
			  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) ''
			  SET @FirstBoard = @FirstBoard + '' WHERE (M.ManualTimeEntry_InDate >= ''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  <= ''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
			  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''''Approved'''' And OD.Onduty_Status =''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
			  and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as OnDuty''
			  set @Firstboardexists=1
		end
		--Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '' as PunctualityPercent from (
			  SELECT DISTINCT ''''Punctuality'''' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''''Punctuality'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P ''
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)=0 AND 
			  (ANAttendanceCode<>''''Weekly Off'''' or FNAttendanceCode<>''''Weekly Off'''') AND (p.LateIn=''''00:00'''' and p.InTime <> ''''00:00'''')
			  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and E.Employee_Code_Id<>''''18000000''''''
			  set @FirstBoard=@FirstBoard+@Filters+'') as Punctuality''
			  set @Firstboardexists=1
		end
		--Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ''  as RawDataPercent from (
			  Select ''''Attendance Summary'''' As TOPIC,COUNT(P.DATE) [COUNT],
			  6 as HYPER,''''AttendanceSummary'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
			  and E.Employee_Code_Id<>''''18000000''''''           
			  set @FirstBoard=@FirstBoard+@Filters+ '') as Attendance''
		end
		if(ISNULL(@FirstBoard,'''')!='''')
		begin
			  set @FirstBoard=''insert into #FirstTableValue '' + @FirstBoard
			  Execute(@FirstBoard)
		end
		select * from #FirstTableValue
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		--Second Table
		--Getting Late Entry Data
		Declare @WhereFilter nvarchar(MAX)
		set @ThirdBoard=''''
		Declare @ThirdBoardvalue int
		set @ThirdBoardvalue =0
		set @WhereFilter ='' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
		((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) 
		and E.Employee_Code_Id<>''''18000000''''''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
		begin
			  set @ThirdBoard=''  
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' 
					End as Percentage from (
			  SELECT DISTINCT ''''Late Entry'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''LateEntry'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)<>0 ''
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Early Exit Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'' 
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
					as Percentage from (                
			  SELECT DISTINCT ''''Early Exit'''' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''''EarlyExit'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + ''WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(EarlyOutMins,0)<>0 ''
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Less Hours worked Data
		--Getting Shift Not allocated Employee Record
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select	TOPIC,
						COUNT,
						HYPER,
						REPORTNAME,
						Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
						Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End as 
						Percentage from 
						(                   
							SELECT  DISTINCT ''''Shift Not Allocated'''' AS TOPIC, 
									isnull(sum(case when (isnull(P.Shift_id,''''0'''')=0 or isnull(P.Shift_id,''''0'''')='''''' + CONVERT(varchar(20),@NoShiftID) +'''''') then 1 else 0 end),0) [COUNT],
									3 AS HYPER, 
									''''Shift Not Allocated'''' AS REPORTNAME 
									FROM TA_TBL_PROCESSEDDATA P ''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''')''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Approved Overtime Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
					as Percentage from (                
			  SELECT DISTINCT ''''Approved Over Time'''' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''''OverTime'''' AS REPORTNAME 
			  FROM TA_TBL_PROCESSEDDATA P ''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ''  WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''''Approved'''' And E.CompOff_Eligible=0 And E.OT_Eligible=1 ''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1 
		end         
		--Getting Discrepancy Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME,  
						  Case  when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(DistinctCOUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
									  as Percentage from 
			  ( 
					SELECT      DISTINCT ''''Discrepancy'''' AS TOPIC, 
								COUNT(C.Clk_EmpId) [COUNT],
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''''Discrepancy'''' AS REPORTNAME 
					FROM ta_tbl_clockdetails C
					Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
			  SET @ThirdBoard = @ThirdBoard + ''  WHERE (C.Clk_Date =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) ''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+'') as A''
			  set @ThirdBoardvalue=1 
		end
		--Getting Non processed data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME, 
						  Case  when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
									  as Percentage 
			  from(
						  Select      ''''Non Processed Record'''' As TOPIC,
									  COUNT(*)[COUNT],
									  COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
									  6 as HYPER,
									  ''''Non Process'''' AS REPORTNAME 
						  FROM TA_Tbl_Clk_RawData C           
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  ''
			  SET @ThirdBoard = @ThirdBoard + '' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE =''''''+convert(nvarchar(MAX),@FromdateString)+''''''''
			  set @ThirdBoard=@ThirdBoard+'') as A''
		end
		--Execute(@ThirdBoard)
		if(ISNULL(@ThirdBoard,'''')!='''')
		begin
			--print (@ThirdBoard)
			Execute(@ThirdBoard)
		end
		else
		begin
			select * from #SecondDummyTableValue
		end
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		Declare @SecondBoardValue int
		set @SecondBoardValue=0
		set @FifthBoard='' ''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
		begin
			set @FifthBoard=@FifthBoard+''
			select 
				  ''''Leave'''' as Approval,
				  Approved,
				  Forwarded,
				  Pending,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as ApprovedPercent,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as ForwardedPercent,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as PendingPercent from
			(
					select      
								count(case  when L.Status=''''Approved'''' then 1  end)Approved,
								count(case  when L.Status=''''Forwarded'''' then 1 end)Forwarded,
								count(case  when L.Status=''''Pending''''  then 1  end)Pending
					from TA_Tbl_LeaveApplication L 
					Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
					Left outer join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=e.SwipeCardNo and P.Date='''''' + CONVERT(nvarchar(MAX),@FromdateString) +'''''')''
                       SET @FifthBoard = @FifthBoard + ''  where 
					(
						('''''' + CONVERT(nvarchar(MAX),@FromdateString) +'''''' between L.Leave_FromDate and L.Leave_ToDate)
						
					) 
					and L.IsDeleted=0''
					if(@ShiftID!=0)
						  begin
								set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
						  end               
					if(@UserGroupName<>''SuperAdmin'')
						  BEGIN
								SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
						  END
					if(@isReportingto > 0)
					BEGIN  
						  SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
					End         
					set @FifthBoard=@FifthBoard+'') as a''
					set @SecondBoardValue=1                         
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+ '' select 
					''''Onduty'''' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),(Approved*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as ApprovedPercent,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as ForwardedPercent,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as PendingPercent from
					(
								select                              
								count(case  when (M.ManualTimeEntry_Status =''''Approved'''' and OD.Onduty_Status =''''Approved'''') then 1 else null end) Approved,
								count(case  when (M.ManualTimeEntry_Status=''''Forwarded'''' and OD.Onduty_Status=''''Forwarded'''') then 1 else null end) Forwarded,
								count(case  when (M.ManualTimeEntry_Status=''''Pending'''' and OD.Onduty_Status=''''Pending'''')  then 1 else null end)  Pending
								from Ta_Tbl_ManualTimeEntry M 
								inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
								Inner join TA_Tbl_Employee E 
								on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
								Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
								INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
								INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
								Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
								----Newly added below left outer instead of innner join 13-Feb-2020
								Left Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
								(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
								(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  ''
			  SET @FifthBoard = @FifthBoard + '' where M.IsOnDuty=1 and M.isDeleted=0 and
			  M.ManualTimeEntry_InDate<=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and 
			  M.ManualTimeEntry_OutDate>=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and M.IsDeleted=0''
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>''SuperAdmin'')
					BEGIN
						  SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
			  End               
			  set @FifthBoard=@FifthBoard+'') as B ''
			  set @SecondBoardValue=1 
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+'' select ''''Permission'''' as Approval,
						  Approved,
					Forwarded,
					Pending,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as ApprovedPercent,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as ForwardedPercent,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as PendingPercent from
			  (
						  select 
									  count(case  when P.Permission_Status=''''Approved'''' then 1 else null end) Approved,
									  count(case  when P.Permission_Status=''''Forwarded'''' then  1 else null end)Forwarded,
									  count(case  when P.Permission_Status=''''Pending''''  then 1 else null end) Pending
						  from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
						  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
			  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  ''
			  SET @FifthBoard = @FifthBoard + '' where P.Permission_Date=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and P.IsDeleted=0''
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+'' and PD.Shift_Id=''+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>''SuperAdmin'')
					BEGIN
						  SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
			  End   
			  set @FifthBoard=@FifthBoard+'')as A''
		end
		if(ISNULL(@FifthBoard,'''')!='''')
		begin
			  Execute(@FifthBoard)
		end
		else
		begin
			  select * from #ThirdDummyTableValue
		end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
	drop table #EmpDesignation      
	drop table #EmployeeIds
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetDashboardInformation]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetDashboardInformation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetDashboardInformation '''', ''2020/07/20'', ''2020/07/20'',0,0,0,''SuperAdmin'',''0'',''0''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetDashboardInformation]
      @EMPLOYEECODEID	NVARCHAR(MAX) = NULL,
      @FROMDATE			DATETIME,
      @TODATE			DATETIME,
      @Session			INT,
      @ShiftID			INT,
      @ParentID			INT,
      @UserGroupName	NVARCHAR(100),
      @GradeLevel		NVARCHAR(20),
      @empId			NVARCHAR(MAX)
AS
BEGIN 
	set nocount on;	
	Declare @FromdateString nvarchar(20)
	declare @todat			nvarchar(20);
	Declare @NoShiftID int
	select @NoShiftID=Shift_Id from TA_Tbl_Shift where Level_Id=0 and Shift_ShortName=''NOS''
	set @todat=GETDATE();
	if @FROMDATE=''''
	begin
		  set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,GETDATE()))+''-''+CONVERT(nvarchar(20),DATEPART(month,getdate()))+''-''+
		  case when len(CONVERT(nvarchar(20),DATEPART(D,GETDATE())))=1 then ''0''+CONVERT(nvarchar(20),DATEPART(D,GETDATE()))
		  else CONVERT(nvarchar(20),DATEPART(D,GETDATE())) end
	end   
	else
	begin
		set @FromdateString=CONVERT(nvarchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(nvarchar(20),DATEPART(month,@fromdate))+''-''+
		case when len(CONVERT(nvarchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(nvarchar(20),DATEPART(D,@fromdate))
		else CONVERT(nvarchar(20),DATEPART(D,@fromdate)) end
	end
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id nvarchar(50),SwipeCard nvarchar(50))
	Create table #FirstTableValue(TOPIC nvarchar(100),ValueCount int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #SecondDummyTableValue(TOPIC nvarchar(100),Count int,Hyper int,ReportName nvarchar(100),PercentageValue nvarchar(30))
	Create table #ThirdDummyTableValue(Approval nvarchar(100),Approved int,Forwarded int,Pending nvarchar(100),ApprovedPercent nvarchar(30),ForwardedPercent nvarchar(30),PendingPercent nvarchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		select @groupid=groupId from TA_Tbl_Usergroup where groupName=@UserGroupName
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'''',''''
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	Declare @sqlEmpLevel nvarchar(4000) 
	set @sqlEmpLevel=
	''insert into #EmpLevel 
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select MAX(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and emp.Employee_Code_Id<>''''18000000''''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) and EL.LevelId is not null''    
	if(@isReportingto > 0)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + '' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) ''  
		END   
	if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
		BEGIN
			  set @sqlEmpLevel = @sqlEmpLevel + '' and ELevel.EmployeeId in (''+CAST(@empId as nvarchar(10))+'')''
		END   
	execute(@sqlEmpLevel)
	--select * from #EmpLevel
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeecountQuery nvarchar(4000)
	Declare @EmployeePresentcountQuery nvarchar(4000)     
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode=''Present'' or ANAttendanceCode=''Present'') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  WHERE P.DATE=@FromdateString
			  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
	
	
	Declare @FirstBoard		nvarchar(MAX)
	Declare @FirstBoard1	nvarchar(MAX)
	Declare @SecondBoard	nvarchar(MAX)
	Declare @ThirdBoard		nvarchar(MAX)
	Declare @FourthBoard	nvarchar(MAX)
	Declare @FifthBoard		nvarchar(MAX)
	Declare @sixthBoard		nvarchar(MAX)
	Declare @Present_Filters nvarchar(MAX)
	Declare @Absetn_Filters	nvarchar(MAX)
	Declare @Leave_Filters	nvarchar(MAX)
	Declare @Union			nvarchar(MAX)
	set @Union='' Union All ''
	IF ((ISNULL(@FROMDATE, '''') <> ''''))
	BEGIN
		--First Gridview Control
		Declare @CommonJoinQueries nvarchar(MAX)         
		Declare @CommonSelectQueries nvarchar(MAX) 
		set @FirstBoard=''''      
		Declare @Firstboardexists int
		set @Firstboardexists=0
		set @CommonJoinQueries=''''
		set @CommonJoinQueries=@CommonJoinQueries+'' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
		INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
		INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
		Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
		set @CommonSelectQueries=''''
		set @CommonSelectQueries=@CommonSelectQueries+''select 
			  TOPIC,
			  COUNT,
			  HYPER,
			  REPORTNAME, 
			  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
						  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeeCount)+'' * 100)),0))+'''' %'''' 
			  End''
		Declare @Filters nvarchar(MAX)
		set @Filters=''''
		if(@ShiftID!=0)
		begin
			  set @Filters =@Filters+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
		end
		if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			  SET @Filters = @Filters + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END
		-- Added below line by manikandan.r on 16-11-2016
		-- if you remove below line it will bring wrong value for absent column.bug id:0035540
		if(@isReportingto > 0)
		BEGIN  
			  SET @Filters = @Filters + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
		End
		--Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  set @FirstBoard =@CommonSelectQueries+'' as PercentageValue from 
			  (
					SELECT DISTINCT ''''Present'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''MonthlyAttendance'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''       
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
					AND (FNAttendanceCode=''''Present'''' or ANAttendanceCode=''''PRESENT''''or (FNAttendanceCode=''''Weekly Off'''' and ANAttendanceCode=''''Weekly Off'''' and (intime<>''''00:00'''' or outtime<>''''00:00''''))
					or (FNAttendanceCode=''''Holiday'''' and ANAttendanceCode=''''Holiday'''' and (intime<>''''00:00'''' or outtime<>''''00:00'''')))
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as Present''
			  set @Firstboardexists=1
		end
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard =@FirstBoard+@CommonSelectQueries+'' as AbsenteesPercent from 
			  (
					SELECT DISTINCT ''''Absent'''' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''''Absentees'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
					set @FirstBoard=@FirstBoard+@CommonJoinQueries        
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND 
					(ANAttendanceCode=''''ABSENT'''' AND FNAttendanceCode=''''Absent'''') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''
			  set @FirstBoard=@FirstBoard+@Filters+'') as Absent''
			  set @Firstboardexists=1
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin
			  declare @LeaveCount nvarchar(MAX)
			  --Getting Leave Data          
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+'' as LeavePercent from 
			  (
					SELECT DISTINCT ''''Approved Leave'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''Leave_Angler'''' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P''        
					set @FirstBoard=@FirstBoard+@CommonJoinQueries
					SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
					AND 
					(
						  FNAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') or
						  ANAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')
					)
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
					and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as Leave''
			  set @Firstboardexists=1
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '' as OnDutyPercent from (
			  SELECT DISTINCT ''''Approved OnDuty'''' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''''OnDuty'''' AS REPORTNAME 
			  FROM Ta_Tbl_ManualTimeEntry M
			  inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
			  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and 
			  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
			  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) ''
			  SET @FirstBoard = @FirstBoard + '' WHERE (M.ManualTimeEntry_InDate >= ''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  <= ''''''+convert(nvarchar(MAX),@FromdateString)+'''''') 
			  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''''Approved'''' And OD.Onduty_Status =''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
			  and E.Employee_Code_Id<>''''18000000''''''                       
			  set @FirstBoard=@FirstBoard+@Filters+'') as OnDuty''
			  set @Firstboardexists=1
		end
		--Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '' as PunctualityPercent from (
			  SELECT DISTINCT ''''Punctuality'''' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''''Punctuality'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P ''
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)=0 AND 
			  (ANAttendanceCode<>''''Weekly Off'''' or FNAttendanceCode<>''''Weekly Off'''') AND (p.LateIn=''''00:00'''' and p.InTime <> ''''00:00'''')
			  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and E.Employee_Code_Id<>''''18000000''''''
			  set @FirstBoard=@FirstBoard+@Filters+'') as Punctuality''
			  set @Firstboardexists=1
		end
		--Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			  if @Firstboardexists=1
			  begin
					set @FirstBoard =@FirstBoard+@Union
			  end
			  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ ''  as RawDataPercent from (
			  Select ''''Attendance Summary'''' As TOPIC,COUNT(P.DATE) [COUNT],
			  6 as HYPER,''''AttendanceSummary'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  SET @FirstBoard = @FirstBoard + @CommonJoinQueries
			  SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
			  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
			  and E.Employee_Code_Id<>''''18000000''''''           
			  set @FirstBoard=@FirstBoard+@Filters+ '') as Attendance''
		end
		if(ISNULL(@FirstBoard,'''')!='''')
		begin
			  set @FirstBoard=''insert into #FirstTableValue '' + @FirstBoard
			  Execute(@FirstBoard)
		end
		select * from #FirstTableValue
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		--Second Table
		--Getting Late Entry Data
		Declare @WhereFilter nvarchar(MAX)
		set @ThirdBoard=''''
		Declare @ThirdBoardvalue int
		set @ThirdBoardvalue =0
		set @WhereFilter ='' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
		((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) 
		and E.Employee_Code_Id<>''''18000000''''''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
		begin
			  set @ThirdBoard=''  
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' 
					End as Percentage from (
			  SELECT DISTINCT ''''Late Entry'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''LateEntry'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)<>0 ''
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Early Exit Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+'' 
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
					as Percentage from (                
			  SELECT DISTINCT ''''Early Exit'''' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''''EarlyExit'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + ''WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(EarlyOutMins,0)<>0 ''
			  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Less Hours worked Data
		--Getting Shift Not allocated Employee Record
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select	TOPIC,
						COUNT,
						HYPER,
						REPORTNAME,
						Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
						Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End as 
						Percentage from 
						(                   
							SELECT  DISTINCT ''''Shift Not Allocated'''' AS TOPIC, 
									isnull(sum(case when (isnull(P.Shift_id,''''0'''')=0 or isnull(P.Shift_id,''''0'''')='''''' + CONVERT(varchar(20),@NoShiftID) +'''''') then 1 else 0 end),0) [COUNT],
									3 AS HYPER, 
									''''Shift Not Allocated'''' AS REPORTNAME 
									FROM TA_TBL_PROCESSEDDATA P ''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''')''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1
		end
		--Getting Approved Overtime Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
					Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
					as Percentage from (                
			  SELECT DISTINCT ''''Approved Over Time'''' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''''OverTime'''' AS REPORTNAME 
			  FROM TA_TBL_PROCESSEDDATA P ''
			  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ''  WHERE (P.DATE=''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''''Approved'''' And E.CompOff_Eligible=0 And E.OT_Eligible=1 ''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
			  set @ThirdBoardvalue=1 
		end         
		--Getting Discrepancy Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME,  
						  Case  when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(DistinctCOUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
									  as Percentage from 
			  ( 
					SELECT      DISTINCT ''''Discrepancy'''' AS TOPIC, 
								COUNT(C.Clk_EmpId) [COUNT],
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''''Discrepancy'''' AS REPORTNAME 
					FROM ta_tbl_clockdetails C
					Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
			  SET @ThirdBoard = @ThirdBoard + ''  WHERE (C.Clk_Date =''''''+convert(nvarchar(MAX),@FromdateString)+'''''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) ''
			  set @ThirdBoard=@ThirdBoard+@WhereFilter+'') as A''
			  set @ThirdBoardvalue=1 
		end
		--Getting Non processed data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
		begin
			  if @ThirdBoardvalue=1
			  begin
					set @ThirdBoard =@ThirdBoard+@Union
			  end
			  set @ThirdBoard=@ThirdBoard+''
			  select      TOPIC,
						  COUNT,
						  HYPER,
						  REPORTNAME, 
						  Case  when ''+convert(nvarchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),(COUNT*$1/''+convert(nvarchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
									  as Percentage 
			  from(
						  Select      ''''Non Processed Record'''' As TOPIC,
									  COUNT(*)[COUNT],
									  COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
									  6 as HYPER,
									  ''''Non Process'''' AS REPORTNAME 
						  FROM TA_Tbl_Clk_RawData C           
			  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
			  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
			  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
			  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
			  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  ''
			  SET @ThirdBoard = @ThirdBoard + '' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE =''''''+convert(nvarchar(MAX),@FromdateString)+''''''''
			  set @ThirdBoard=@ThirdBoard+'') as A''
		end
		--Execute(@ThirdBoard)
		if(ISNULL(@ThirdBoard,'''')!='''')
		begin
			--print (@ThirdBoard)
			Execute(@ThirdBoard)
		end
		else
		begin
			select * from #SecondDummyTableValue
		end
		---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
		Declare @SecondBoardValue int
		set @SecondBoardValue=0
		set @FifthBoard='' ''
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
		begin
			set @FifthBoard=@FifthBoard+''
			select 
				  ''''Leave'''' as Approval,
				  Approved,
				  Forwarded,
				  Pending,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as ApprovedPercent,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as ForwardedPercent,
				  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
							  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
				  End as PendingPercent from
			(
					select      
								count(case  when L.Status=''''Approved'''' then 1  end)Approved,
								count(case  when L.Status=''''Forwarded'''' then 1 end)Forwarded,
								count(case  when L.Status=''''Pending''''  then 1  end)Pending
					from TA_Tbl_LeaveApplication L 
					Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
					INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
					INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
					INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
					Left outer join TA_Tbl_ProcessedData P on (P.Employee_Code_Id=e.SwipeCardNo and P.Date='''''' + CONVERT(nvarchar(MAX),@FromdateString) +'''''')''
                       SET @FifthBoard = @FifthBoard + ''  where 
					(
						('''''' + CONVERT(nvarchar(MAX),@FromdateString) +'''''' between L.Leave_FromDate and L.Leave_ToDate)
						
					) 
					and L.IsDeleted=0''
					if(@ShiftID!=0)
						  begin
								set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
						  end               
					if(@UserGroupName<>''SuperAdmin'')
						  BEGIN
								SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
						  END
					if(@isReportingto > 0)
					BEGIN  
						  SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
					End         
					set @FifthBoard=@FifthBoard+'') as a''
					set @SecondBoardValue=1                         
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+ '' select 
					''''Onduty'''' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),(Approved*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as ApprovedPercent,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as ForwardedPercent,
					Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
								Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
					End as PendingPercent from
					(
								select                              
								count(case  when (M.ManualTimeEntry_Status =''''Approved'''' and OD.Onduty_Status =''''Approved'''') then 1 else null end) Approved,
								count(case  when (M.ManualTimeEntry_Status=''''Forwarded'''' and OD.Onduty_Status=''''Forwarded'''') then 1 else null end) Forwarded,
								count(case  when (M.ManualTimeEntry_Status=''''Pending'''' and OD.Onduty_Status=''''Pending'''')  then 1 else null end)  Pending
								from Ta_Tbl_ManualTimeEntry M 
								inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
								Inner join TA_Tbl_Employee E 
								on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
								Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
								INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
								INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
								Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
								----Newly added below left outer instead of innner join 13-Feb-2020
								Left Outer join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
								(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
								(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  ''
			  SET @FifthBoard = @FifthBoard + '' where M.IsOnDuty=1 and M.isDeleted=0 and
			  M.ManualTimeEntry_InDate<=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and 
			  M.ManualTimeEntry_OutDate>=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and M.IsDeleted=0''
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>''SuperAdmin'')
					BEGIN
						  SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
			  End               
			  set @FifthBoard=@FifthBoard+'') as B ''
			  set @SecondBoardValue=1 
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
		begin
			  if @SecondBoardValue=1
			  begin
					set @FifthBoard =@FifthBoard+@Union
			  end
			  set @FifthBoard=@FifthBoard+'' select ''''Permission'''' as Approval,
						  Approved,
					Forwarded,
					Pending,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Approved)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as ApprovedPercent,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Forwarded)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as ForwardedPercent,
						  Case  when ''+convert(nvarchar(10),@EmployeeCount)+''=0 then ''''0 %''''
									  Else convert(nvarchar(20),Round(convert(nvarchar(20),((Pending)*$1/''+convert(nvarchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
						  End as PendingPercent from
			  (
						  select 
									  count(case  when P.Permission_Status=''''Approved'''' then 1 else null end) Approved,
									  count(case  when P.Permission_Status=''''Forwarded'''' then  1 else null end)Forwarded,
									  count(case  when P.Permission_Status=''''Pending''''  then 1 else null end) Pending
						  from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
						  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
								INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
			  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
			  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  ''
			  SET @FifthBoard = @FifthBoard + '' where P.Permission_Date=''''''+ CONVERT(nvarchar(MAX),@FromdateString) +'''''' and P.IsDeleted=0''
			  if(@ShiftID!=0)
					begin
						  set @FifthBoard=@FifthBoard+'' and PD.Shift_Id=''+convert(nvarchar(10),@shiftId)
					end         
			  if(@UserGroupName<>''SuperAdmin'')
					BEGIN
						  SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
					END   
			  if(@isReportingto > 0)
			  BEGIN  
					SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
			  End   
			  set @FifthBoard=@FifthBoard+'')as A''
		end
		if(ISNULL(@FifthBoard,'''')!='''')
		begin
			  Execute(@FifthBoard)
		end
		else
		begin
			  select * from #ThirdDummyTableValue
		end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
	drop table #EmpDesignation      
	drop table #EmployeeIds
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsUpdated]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetailsUpdated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsUpdated]
(
	@levelId int='''',
	@UserGroupName nVarchar(250)='''',
	@UserLevelId nvarchar(4000)='''',
	@ParentId int
)
as
Begin
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @Query as varchar(7000)
	--IF(@UserGroupName = ''SuperAdmin'')
	--	BEGIN
	--		select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId, b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId order by childLevelName
	--	End
	--Else
	--	Begin
	--		--select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
	--if (@UserLevelId='''' or @userLevelId is null)
	--		begin 
	--			set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 order by childLevelName'' 
	--				--and b.id in ('' + @UserLevelId + '')''
	--		End
	--else
	--	begin
			--set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 and b.id in ('' + @UserLevelId + '') order by childLevelName''
			set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 order by childLevelName''
		--End
exec(@Query)
drop table #LevelRights
		--End
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getChildLevelDetailsForSearch]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getChildLevelDetailsForSearch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_getChildLevelDetailsForSearch 1,0,''SuperAdmin'',''10''
CREATE  PROCEDURE [dbo].[Proc_TA_getChildLevelDetailsForSearch]
(
      @levelId int='''',
      @ParentLevelId int='''',
      @UserGroupName nVarchar(250)='''',
      @UserLevelId nvarchar(4000)=''''
)
as
Begin
      create table #LevelRights(LevelId int)
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId
      declare @Query as varchar(8000)           
      IF(@ParentLevelId!=0)
            BEGIN
                  IF(@UserGroupName = ''SuperAdmin'')
                        BEGIN
                              select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId,case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted 
                              from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid 
                              where a.levelid=@levelId and b.parentId=@ParentLevelId and b.id is not null order by childLevelName
                        End
                  Else
                        Begin
                              --select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , b.IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.Isdeleted=0
                              if (@UserLevelId='''' or @userLevelId is null)
                                    begin 
                                          set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.parentId='' + cast (@ParentLevelId as nvarchar(20)) + '' and b.Isdeleted=0 and b.id is not null order by childLevelName'' 
                                          --and b.id in ('' + @UserLevelId + '')''
                                    End
                              else
                                    begin
                                          set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 and b.id in ('' + @UserLevelId + '') and b.id is not null order by childLevelName''
                                    End
                        End   
            END
      ELSE
            BEGIN
                  IF(@UserGroupName = ''SuperAdmin'')
                        BEGIN
                              select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId,case when b.IsDeleted=1 then ''True'' else ''False'' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid=@levelId and b.id is not null order by childLevelName
                        End
                  Else
                        Begin
                              if (@UserLevelId='''' or @userLevelId is null)
                                    begin 
                                          set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 and b.id is not null order by childLevelName'' 
                                          --and b.id in ('' + @UserLevelId + '')''
                                    End
                              else
                                    begin
                                          set @Query = ''select a.levelid,a.levelname,b.id,b.name as childLevelName,b.parentId,b.description,b.levelid as childId , case when b.IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted from ta_tbl_level a left outer join ta_tbl_levelDetails b  on a.levelid=b.levelid inner join #LevelRights on #LevelRights.LevelId=b.id  where a.levelid='' + cast (@levelId as nvarchar(20)) + '' and b.Isdeleted=0 and b.id is not null order by childLevelName''
                                    End
                        End
            END         
      exec(@Query)
      drop table #LevelRights
End
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroup_Designation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroup_Designation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the Designation based on the organization for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroup_Designation] 
@LevelID int
AS
BEGIN
	SET NOCOUNT ON;
    select distinct TitleId as DesignationId,TitleName as DesignationName from TA_Tbl_title T
    inner join  TA_Tbl_EmployeeDesignation ED on ED.DesignationId=T.TitleId
    inner join  TA_tbl_EmployeeLevel EL on EL.EmployeeID=ED.EmployeeID
    where EL.LevelID=@LevelID and T.IsDeleted=0 order by TitleName
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDateForService]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMonthClosureEndDateForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 05-01-2015
-- Description:	To Get the MonthClosure date for processing
-- [Proc_Ta_GetMonthClosureEndDateForService]1,''20171231''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDateForService]
	@CompanyId int,
	@DefaultMonthClosureDate datetime	
AS
BEGIN
	SET NOCOUNT ON;
	Declare @MonthClosure_EndDate datetime
	SELECT @MonthClosure_EndDate= Max(MonthClosure_EndDate) FROM TA_Tbl_MonthClosure where OrgLevel_Id=@CompanyId and IsDeleted = 0 and Process = ''P''
	if (@MonthClosure_EndDate!='''' and @MonthClosure_EndDate is not null)
	begin
		set @MonthClosure_EndDate=DATEADD(d,1,@MonthClosure_EndDate)
	end
	else
	begin
		if (@DefaultMonthClosureDate!='''' and @DefaultMonthClosureDate is not null)
			begin
				set @MonthClosure_EndDate=DATEADD(d,1,@DefaultMonthClosureDate)
			end
		else
			begin
				set @MonthClosure_EndDate=GETDATE()
			end
	end
	----This condition added newly. on 28-May-2019 06:43 PM
	--IF(DATEDIFF(MONTH,@MonthClosure_EndDate,GETDATE())>12)
	--BEGIN
	--	 select @MonthClosure_EndDate=DATEADD(YEAR, DATEDIFF(Year, 0, GETDATE())-1,0)
	--END
	--select @MonthClosure_EndDate
	
	DELETE FROM TA_Tbl_DataProcessTemp
	;WITH CTE AS
	(    
		SELECT @MonthClosure_EndDate as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,convert(datetime,convert(varchar(11),[DATE])))FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GetMonthClosureEndDate]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GetMonthClosureEndDate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GetMonthClosureEndDate]
	-- Add the parameters for the stored procedure here
	@CompanyId int,
	@DefaultMonthClosureDate datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    Declare @MonthClosure_EndDate datetime
	SELECT @MonthClosure_EndDate= Max(MonthClosure_EndDate) FROM TA_Tbl_MonthClosure where OrgLevel_Id=@CompanyId and IsDeleted = 0 and Process = ''P''
	if (@MonthClosure_EndDate='''' or @MonthClosure_EndDate is null)
		begin
			set @MonthClosure_EndDate=@DefaultMonthClosureDate
		end
	if (@MonthClosure_EndDate!='''' or @MonthClosure_EndDate is not null)
		begin
			set @MonthClosure_EndDate=@DefaultMonthClosureDate
		end
	else
		begin
			set @MonthClosure_EndDate=GETDATE()
		end	
	DELETE FROM TA_Tbl_DataProcessTemp
    -- Insert statements for procedure here
	;WITH CTE AS
	(    
		SELECT @MonthClosure_EndDate as [DATE]
		UNION ALL
		SELECT DATEADD(D,1,[DATE])FROM CTE WHERE [DATE]<GETDATE()-1
	)
	Insert into TA_Tbl_DataProcessTemp SELECT *FROM CTE 
	option(maxrecursion 0);
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Description		: Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee    
[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin] '''','''',''Pending'',''04/01/2016'',''12/31/2020'',0,'''','''','''',''SuperAdmin'',''0'',0,0
*/    
CREATE   PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetailsForSuperAdmin] 
@Employee_ID int,   
@LevelId varchar(2000),    
@Status varchar(100) =null,    
@Leave_FromDate varchar(20)=null,    
@Leave_ToDate varchar(20) =null,    
@Isdeleted bit = 0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250),
@ParentID int,
@EmployeeCategory int, 
@EmployeeType int
as    
begin
	set nocount on
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	Declare @SuccessiveTodate datetime	
	Declare @LevelId1 varchar(2000)
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @LevelId1=@ParentID
		while((select Id from TA_tbl_LevelDetails where id=@LevelId1) <> '''') 
			BEGIN 							
				if((select levelID from TA_tbl_LevelDetails where Id=@LevelId1) <> 1)
					begin						
						set @LevelId1 = (select parentId from TA_tbl_LevelDetails where id=@LevelId1)						
					end
				else
					begin
						break
					end
			ENd
	set @LevelId=@LevelId1
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=DATEADD(d,@SuccessiveDays,TODATE) from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveTodate=TODATE from TA_Tbl_YearSetting where IsActive=1	
	create table #LevelRights(LevelId int)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
    
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
    
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @sqlQuery as nvarchar(4000)
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	--select * from #TempPermissionDetails
	
	
	
	set @sqlQuery=''''
	set @sqlQuery = ''select	E.Employee_Code_Id as employeeid,
							ld.name,
							(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,LA.LeaveApplication_Id,
							LA.Status,
							case when LT.LeaveType is not null then LT.LeaveType + '''' - ''''+ LA.Type else LA.Type end as Type,	
							case when ''+cast(@dateFormat as varchar(100))+''=106 then	REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
								 else CONVERT(VARCHAR, LA.Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') 
							end  AS Leave_ApplicationDate,
							case when ''+cast(@dateFormat as varchar(100))+''=106 then REPLACE(CONVERT(VARCHAR, LA.Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
								 else CONVERT(VARCHAR, LA.Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') 
							end 
							+ '''' - '''' +
							case when ''+cast(@dateFormat as varchar(100))+''=106 then	REPLACE(CONVERT(VARCHAR, LA.Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
								 else CONVERT(VARCHAR, LA.Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') 
							end +'''' (''''+ convert(varchar(10),NumberOfDays)+ case when NumberOfDays<=1 then '''' day'''' else '''' days'''' end+'''')''''
	AS Duration,la.NumberOfDays,LA.Reason
							from #TempPermissionDetails E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId ''    
	set @sqlQuery = @sqlQuery + '' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  el.LevelId=ld.id ''    
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=el.levelID ''
	set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and LA.IsDeleted=0 '' 
	set @sqlQuery = @sqlQuery + '' and el.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) ''
	If not(@strEmployeeCodeId = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		End
	If Not (@strSwipeCardNo = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' ''  
		End 
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If not(@strEmployeeName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName +'''' ''''+ isnull(E.Employee_LastName,'''''''') like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + '''''')''
		End	
	--if not(@Status is null or @Status='''' or @Status=''All'')
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and LA.Status IN ('''''' + @Status  + '''''')''
	--	End
	if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((LA.Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
				set @sqlQuery = @sqlQuery + '' or (LA.Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)+''))''
			end
	end
	else 
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))''
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((LA.Status IN (''''Pending''''))''
				set @sqlQuery = @sqlQuery + '' or (LA.Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')))''
			end
	End	
	
	
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
		end
	if not(cast(@Leave_FromDate as nvarchar(11))='''' or cast(@Leave_FromDate as nvarchar(11))=''0'')
		begin
			--commented on 13-Feb-2020 06:24 PM in scufe client. by maniknadan.rr
			--set @sqlQuery = @sqlQuery + '' and LA.Leave_FromDate>=CONVERT(DATETIME, '''''' + cast(@Leave_FromDate as nvarchar(11)) + '''''', 102)''
			set @sqlQuery = @sqlQuery + '' and ((CONVERT(DATETIME, '''''' + cast(@Leave_FromDate as nvarchar(11)) + '''''', 102) between LA.Leave_FromDate and LA.Leave_ToDate) or''
			set @sqlQuery = @sqlQuery + '' (CONVERT(DATETIME, '''''' + cast(@Leave_ToDate as nvarchar(11)) + '''''', 102) between LA.Leave_FromDate and LA.Leave_ToDate)
			or 
			(LA.Leave_FromDate>=CONVERT(DATETIME, '''''' + cast(@Leave_FromDate as nvarchar(11)) + '''''', 102)and LA.Leave_ToDate<=CONVERT(DATETIME, '''''' + cast(@Leave_ToDate as nvarchar(11)) + '''''', 102))
			)''
		End
	--if(@Leave_ToDate >= @ToDate)
	--	begin
	--		set @Leave_ToDate=@ToDate
	--	end
	--if(@SuccessiveTodate=@Leave_ToDate)
	--	begin
	--		set @Leave_ToDate=@ToDate
	--	end
	--if not(cast(@Leave_ToDate as nvarchar(11))='''' or cast(@Leave_ToDate as nvarchar(11))=''0'')
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and LA.Leave_ToDate<=CONVERT(DATETIME, '''''' + cast(@Leave_ToDate as nvarchar(11)) + '''''', 102)''
	--	End
	set @sqlQuery = @sqlQuery + '' Order by LeaveApplication_Id desc''
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetails_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : 
Proc_TA_GetLeaveSanctionDetails ''161'',''107'',''Pending,Forwarded,Rejected'',''01/Nov/2014'',''26/Dec/2014'',0,'''','''','''',''Project Leader - MS'',''107''
select * from ta_tbl_leaveapplication
Description : Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee
Created By : Prabakaran
Created On : 23-Jul-07
Modified By : Prabakaran
Modified On : 24-Jul-07, 14May14 by Gopinath
 // Modified the datetime format conversion due to Bug no.24001
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails_Angler] 
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(100) =null,
@Leave_FromDate varchar(20) =null,
@Leave_ToDate varchar(20) =null,
@Isdeleted bit =0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250), 
@ParentId int 
as
begin
	SET NOCOUNT ON;
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery1=''''
	set @sqlQuery = ''select ld.name,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,LA.LeaveApplication_Id,LA.Status,LA.Type,case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, LA.Leave_ApplicationDate, ''+cast(@dateFormat as varchar(100))+'') end  AS Leave_ApplicationDate,
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, LA.Leave_FromDate, ''+cast(@dateFormat as varchar(100))+'') end 
		+ '''' - '''' +
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, LA.Leave_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, LA.Leave_ToDate, ''+cast(@dateFormat as varchar(100))+'') end 	
		AS Duration from #TempPermissionDetails E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''
	set @sqlQuery = @sqlQuery + '' where'' 
	set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''
	set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate and LA.Leave_FromDate >= CONVERT(DATETIME,''''''+cast(@Leave_FromDate as nvarchar(20))+'''''', 102) and LA.Leave_ToDate <= CONVERT(DATETIME,''''''+cast(@Leave_ToDate as nvarchar(20))+'''''', 102) order by EffectiveDate desc) ''
	If not(@strEmployeeCodeId = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		End
	If Not (@strSwipeCardNo = '''') 
		Begin 
			Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' '' 
		End 
	If not(@strEmployeeName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName +'''' ''''+ isnull(E.Employee_LastName,'''''''') like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + '''''')''
		End
		 if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))''	
			end
		else if not(@Status is null or @Status='''' or @Status=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status  + ''''''))''
			End
			exec(@sqlQuery)
		drop table #LevelRights
		drop table #TempPermissionDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveSanctionDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveSanctionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : 
Proc_TA_GetLeaveSanctionDetails ''6'',''1'',''All'',''11/01/2019'',''01/31/2020'',0,'''','''','''',''Project Manager'',''1'',0,0
select * from ta_tbl_leaveapplication
Description : Get Leave Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included : TA_Tbl_LeaveApplication,Ta_tbl_leveldetails and TA_TBL_Employee
Created By : Prabakaran
Created On : 23-Jul-07
Modified By : Prabakaran
Modified On : 24-Jul-07
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetLeaveSanctionDetails] 
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(max) =null,
@Leave_FromDate datetime =null,
@Leave_ToDate datetime =null,
@Isdeleted bit =0,
@strSwipeCardNo varchar(15)=null,
@strEmployeeName varchar(100)=null,
@strEmployeeCodeId varchar(15)=null,
@UserGroupName varchar(250), 
@ParentId int,
@EmployeeCategory int, 
@EmployeeType int
as
Begin
	SET NOCOUNT ON;
	if(substring(CONVERT(varchar(20),@Leave_FromDate),1,5)=''01/01'' and substring(CONVERT(varchar(20),@Leave_ToDate),1,5)=''31/12'')
	begin		
		set @Leave_ToDate=substring(CONVERT(varchar(20),@Leave_ToDate),4,2)+''/''+substring(CONVERT(varchar(20),@Leave_ToDate),1,2)+''/''+
		substring(CONVERT(varchar(20),@Leave_ToDate),7,4)
	end
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
		 --Get current date time format.
    DECLARE @dateFormat as INT
    set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
    declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	--Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
	
	--select * from #TempPermissionDetails 
	--	Insert Into #TempPermissionDetails 
	--	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery1=''''
	set @sqlQuery = ''select e.employee_code_id as employeeid,ld.name,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,
	LA.LeaveApplication_Id,
	LA.Status,
	case when LT.LeaveType is not null then LT.LeaveType + '''' - ''''+ LA.Type else LA.Type end as Type, 
	case when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, LA.Leave_ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') else CONVERT(VARCHAR, LA.Leave_ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') end AS Leave_ApplicationDate,
	case when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, la.Leave_FromDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') else CONVERT(VARCHAR, la.Leave_FromDate, ''+CONVERT(varchar,@dateFormat)+'') end + '''' - '''' + case when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, la.Leave_ToDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') else CONVERT(VARCHAR, la.Leave_ToDate, ''+CONVERT(varchar,@dateFormat)+'') end +'''' (''''+ convert(varchar(10),NumberOfDays)+ case when NumberOfDays<=1 then '''' day'''' else '''' days'''' end+'''')'''' AS Duration,''
	set @sqlQuery = @sqlQuery + '' NumberOfDays=convert(varchar(20),LA.NumberOfDays),ReportTo,LeaveSanction,E.Employee_id,LA.Reason from #TempPermissionDetails E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''
	set @sqlQuery = @sqlQuery + '' where'' 
	--set @sqlQuery = @sqlQuery + '' or and ''
	set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''
	set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) ''
	If not(@strEmployeeCodeId = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		End
	If Not (@strSwipeCardNo = '''') 
		Begin 
			Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' '' 
		End 
	If not(@strEmployeeName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName +'''' ''''+ isnull(E.Employee_LastName,'''''''') like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + '''''')''
		End		 
	if(@isReportingto > 0)
			BEGIN
			   set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (LA.Status IN ('''''' + @Status + ''''''))and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((LA.Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
				set @sqlQuery = @sqlQuery + '' or (LA.Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)+''))''
			end
	end
	else 
	begin
		set @sqlQuery = @sqlQuery + '' and (LA.Status IN (select value from split('''''' + @Status  + '''''','''','''')))''
	End		
	--print(@sqlQuery)		
	--select value from split(@Status,'','')
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop Table #TempPermissionDetails
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetailsById]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveMasterDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_GetLeaveMasterDetailsById]        
(         
 @id int       
)         
As        
 DECLARE @Isdel int        
 SET @Isdel=1        
BEGIN   
	SET NOCOUNT ON;     
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,  
 S.Section_Name,S.Section_Id,T.TitleName,T.TitleId,L.LeaveType,L.LeaveDescription,L.LeaveType_Id, A.LOP From TA_Tbl_LeaveMaster A  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                
    join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                
    join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id                
    JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id        
    JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id        
    JOIN TA_Tbl_Title T ON T.TitleId=A.Title_Id     
    JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=A.LeaveType_Id  
WHERE A.IsDeleted=1  AND A.id=@id        
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveMasterDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveMasterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[Proc_TA_GetLeaveMasterDetails] as          
BEGIN        
SET NOCOUNT ON;  
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,      
 S.Section_Name,S.Section_Id,T.TitleName,T.TitleId,L.LeaveType,L.LeaveType_Id, A.LOP,A.[id] From TA_Tbl_LeaveMaster A      
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                    
    join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                    
    join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id                    
    JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id            
    JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id            
    JOIN TA_Tbl_Title T ON T.TitleId=A.Title_Id         
    JOIN TA_Tbl_LeaveType L ON L.LeaveType_Id=A.LeaveType_Id      
   -- JOIN TA_Tbl_LeaveMasterLOP LP ON LP.id=A.LeaveType_Id    
WHERE A.IsDeleted=1  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetLeaveCountSanctionDetails]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetLeaveCountSanctionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
[Proc_TA_GetLeaveCountSanctionDetails] ''65'',''Project Manager''
*/
create PROCEDURE [dbo].[Proc_TA_GetLeaveCountSanctionDetails] 
@Employee_Id int,
@UserGroupName varchar(250) 
as
Begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId 
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
		 --Get current date time format.
      DECLARE @dateFormat as INT
      set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
    Insert Into #TempPermissionDetails 
		select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
		from ta_tbl_employee where Isdeleted=0 and Employee_Status=1
declare @sqlQuery as nvarchar(max)
declare @sqlQuery1 as nvarchar(max)
set @sqlQuery=''''
set @sqlQuery1=''''
set @sqlQuery = ''select  
                                    count(case  when LA.Status=''''Approved'''' and E.LeaveSanction='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1  end)Approved,
                                    count(case  when LA.Status=''''Forwarded'''' and E.LeaveSanction='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1 end)Forwarded,
                                    count(case  when LA.Status=''''Pending'''' and (E.ReportTo='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' or E.LeaveSanction='''''' +cast(@Employee_Id as nvarchar(50))   + '''''') then 1  end)Pending from #TempPermissionDetails E ''
set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on E.Employee_Id=LA.Employee_Id ''
set @sqlQuery = @sqlQuery + '' left outer join ta_tbl_leavetype LT on LA.LeaveType_Id=LT.LeaveType_Id ''
set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on EL.LevelId=ld.id ''
set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''
set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''
set @sqlQuery = @sqlQuery + '' where'' 
set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''
set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <= LA.Leave_ApplicationDate order by EffectiveDate desc) ''
	if(@Employee_Id!='''')
	begin
		set @sqlQuery = @sqlQuery + '' and (E.ReportTo='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' or E.LeaveSanction='''''' +cast(@Employee_Id as nvarchar(50))   + '''''')''
	end
	--print(@sqlQuery)
		exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop Table #TempPermissionDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_GetTransportationVehicleMappingDetailsById]                  
(                   
 @VehicleId int                  
)                   
As                  
BEGIN             
SELECT C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,RO.Route_Name , RO.ID,V.VehicleNo,V.VehicleId        
 FROM TA_Tbl_Transportation_Mapping A                  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id                  
  join TA_Tbl_Region R ON R.Region_Id=A.Region_Id                  
  join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id             
  join TA_Tbl_RouteMaster RO ON RO.Id=A.RouteId                   
  join TA_Tbl_Transportation_Vehicle V ON V.VehicleId=A.VehicleId             
 Where A.VehicleId=@VehicleId          
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
Procedure Name 	:	Proc_TA_GetTransportationRouteMasterDetailsById    
Description 	:	Get Transportation Route Details based on Route Id
Tables Included :	TA_Tbl_Leveldetails,TA_Tbl_RouteMaster and TA_Tbl_Transportation_Vehicle  
Created By 	:	    
Created On 	:	
Modified By 	:	Prabakaran.P
Modified On 	:	07-Feb-08    
*/
CREATE   Procedure [dbo].[Proc_TA_GetTransportationRouteMasterDetailsById]
(               
 @RouteId int              
)               
As                     
BEGIN              
SELECT V.VehicleNo,R.Level_Id,L.Name,R.Route_Name ,R.Route_Description,(CASE WHEN R.Isdeleted = 0 THEN ''False'' ELSE ''True'' END) Isdeleted
FROM TA_Tbl_RouteMaster R              
LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle V ON V.VehicleId=R.VehicleID     
LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=R.Level_Id  
Where R.Id =@RouteId   
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportationRouteDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportationRouteDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  Procedure [dbo].[Proc_TA_GetTransportationRouteDetailsById]        
(         
 @RouteId int        
)         
As               
BEGIN        
-- SELECT Company_Id,Region_Id,Branch_Id,Route_Name,Route_Description FROM TA_Tbl_RouteMaster WHERE  IsDeleted=@Isdel AND [Id]=@RouteId        
SELECT C.Company_Name,R.Region_Name,B.Branch_Name,RO.Route_Name ,RO.Route_Description       
 FROM TA_Tbl_Transportation_Mapping A        
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id        
  join TA_Tbl_Region R ON R.Region_Id=A.Region_Id        
  join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id        
  --join TA_Tbl_RouteMaster V ON V.VehicleId=A.VehicleId        
  join TA_Tbl_RouteMaster RO ON RO.Id=A.RouteId         
 --Where A.RouteId=@RouteId AND RO.IsDeleted=1 -- AND RO.IsMapped=1  
  Where A.RouteId=@RouteId 
END    
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure_Arabic]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure ''1,2,3,47,113,133,134,135,137,138,140,150'',''1/1/2009'',''05/08/2009'','''','''',''''
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds varchar(8000),
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''''  
  set @sqlQuery = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id ''  
  --set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''    
  set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery = @sqlQuery + '' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery = @sqlQuery + '' and (LA.Leave_FromDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery = @sqlQuery + '' or LA.Leave_ToDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery = @sqlQuery + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery = @sqlQuery + '' and (LA.Status IN ( ''''Forwarded'''',''''Pending''''))'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery = @sqlQuery + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + '' and Month('''''' + cast( @dtClosingMonth as varchar(20)) + '''''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))''  
  set @sqlQuery1=''''  
  set @sqlQuery1 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id ''  
  --set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id ''    
  set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery1 = @sqlQuery1 + '' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery1 = @sqlQuery1 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery1 = @sqlQuery1 + '' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery1 = @sqlQuery1 + '' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery1 = @sqlQuery1 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery1 = @sqlQuery1 + '' and (mt.Clk_Process = ''''N'''') and (mt.ManualTimeEntry_Status != ''''Rejected'''')'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''''  
  set @sqlQuery2 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery2 = @sqlQuery2 + '' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id ''  
  --set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery2 = @sqlQuery2 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery2 = @sqlQuery2 + '' AND E.Isdeleted=0''  
  --set @sqlQuery2 = @sqlQuery2 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery2 = @sqlQuery2 + '' and pd.Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery2 = @sqlQuery2 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery2 = @sqlQuery2 + '' and (pd.ProcessFlag =0 )'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery2 = @sqlQuery2 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''''  
  set @sqlQuery3 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery3 = @sqlQuery3 + '' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery3 = @sqlQuery3 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery3 = @sqlQuery3 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery3 = @sqlQuery3 + '' AND E.Isdeleted=0''  
  --set @sqlQuery3 = @sqlQuery3 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery3 = @sqlQuery3 + '' and crd.Clk_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery3 = @sqlQuery3 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery3 = @sqlQuery3 + '' and (crd.Clk_Flag =0 or crd.Clk_Process =0)'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery3 = @sqlQuery3 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''''  
  set @sqlQuery4 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id ''  
  --set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery4 = @sqlQuery4 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id ''
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery4 = @sqlQuery4 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery4 = @sqlQuery4 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery4 = @sqlQuery4 + '' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery4 = @sqlQuery4 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery4 = @sqlQuery4 + '' and pm.Permission_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery4 = @sqlQuery4 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery4 = @sqlQuery4 + '' and (pm.Permission_Status IN ( ''''Forwarded'''',''''Pending''''))''  
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery4 = @sqlQuery4 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=N''?? ??? ???????? ''
if(@gintRawCount>0)
	begin
	set @Result=@Result + N''?????? ''
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + '',''
	end
set @Result=@Result + N''?????? ????? ''
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + '',''
			end
		set @Result=@Result + N''?????? ''
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + '',''
					end
		set @Result=@Result + N''????? ''
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + '',''
							end
		set @Result=@Result + N''????? ????? ?????? ''
	end
set @Result=@Result + N''???? ?????? ''
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''''
end
select @Result as Result
drop table #LevelRights
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE    PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountYearClsoure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountYearClsoure ''323'',''1/1/2011'',''12/31/2011'','''',''SuperAdmin'',323
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds varchar(8000),
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''''  
  set @sqlQuery = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id ''  
  --set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''    
  set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery = @sqlQuery + '' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery = @sqlQuery + '' and (LA.Leave_FromDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery = @sqlQuery + '' or LA.Leave_ToDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery = @sqlQuery + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery = @sqlQuery + '' and (LA.Status IN ( ''''Forwarded'''',''''Pending''''))'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery = @sqlQuery + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + '' and Month('''''' + cast( @dtClosingMonth as varchar(20)) + '''''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))''  
  set @sqlQuery1=''''  
  set @sqlQuery1 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id ''  
  --set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id ''    
  set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery1 = @sqlQuery1 + '' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery1 = @sqlQuery1 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery1 = @sqlQuery1 + '' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery1 = @sqlQuery1 + '' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery1 = @sqlQuery1 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery1 = @sqlQuery1 + '' and (mt.Clk_Process = ''''N'''') and (mt.ManualTimeEntry_Status != ''''Rejected'''')'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''''  
  set @sqlQuery2 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery2 = @sqlQuery2 + '' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id ''  
  --set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery2 = @sqlQuery2 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery2 = @sqlQuery2 + '' AND E.Isdeleted=0''  
  --set @sqlQuery2 = @sqlQuery2 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery2 = @sqlQuery2 + '' and pd.Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery2 = @sqlQuery2 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery2 = @sqlQuery2 + '' and (pd.ProcessFlag =0 )'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery2 = @sqlQuery2 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''''  
  set @sqlQuery3 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery3 = @sqlQuery3 + '' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery3 = @sqlQuery3 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery3 = @sqlQuery3 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery3 = @sqlQuery3 + '' AND E.Isdeleted=0''  
  --set @sqlQuery3 = @sqlQuery3 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery3 = @sqlQuery3 + '' and crd.Clk_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery3 = @sqlQuery3 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery3 = @sqlQuery3 + '' and (crd.Clk_Flag =0 or crd.Clk_Process =0)'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery3 = @sqlQuery3 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''''  
  set @sqlQuery4 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id ''  
  --set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery4 = @sqlQuery4 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id ''
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery4 = @sqlQuery4 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery4 = @sqlQuery4 + '' inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId '' 
  set @sqlQuery4 = @sqlQuery4 + '' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery4 = @sqlQuery4 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery4 = @sqlQuery4 + '' and pm.Permission_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery4 = @sqlQuery4 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery4 = @sqlQuery4 + '' and (pm.Permission_Status IN ( ''''Forwarded'''',''''Pending''''))''  
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery4 = @sqlQuery4 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=''Non Processed ''
if(@gintRawCount>0)
	begin
	set @Result=@Result + '' Device ''
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + '',''
	end
set @Result=@Result + '' Data Process ''
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + '',''
			end
		set @Result=@Result + '' Leave ''
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + '',''
					end
		set @Result=@Result + '' Permission ''
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + '',''
							end
		set @Result=@Result + '' Manual Entry ''
	end
set @Result=@Result + '' Data Exists''
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''''
end
drop table #LevelRights
drop table #EmpLevel
drop table #ReprocessEmployees
drop table #tblProcessRaw
drop table #tblProcessProcessData
drop table #tblProcessLeave
drop table #tblProcessPermission
drop table #tblProcessManualEntry
drop table #TempProcessedData
drop table #Clk_RawData
select @Result as Result' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure_Arabic]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountMonthClsoure ''1,2,3,47,113,133,134,135,137,138,140,150'',''1/1/2009'',''05/08/2009'',''''[''emp008'',''emp009'']    
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds xml,
@UserGroupName varchar(250), 
@ParentId int 
as  
create table #LevelRights(LevelId int)
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
create table #ReprocessEmployees(EmployeeCodeId varchar(15))
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
create table #tblProcessRaw(intCount bigint)
create table #tblProcessProcessData(intCount bigint)
create table #tblProcessLeave(intCount bigint)
create table #tblProcessPermission(intCount bigint)
create table #tblProcessManualEntry(intCount bigint)
CREATE TABLE #TempProcessedData
		(
			[Process_Rec_ID] bigint,
			[Employee_Code_Id] nvarchar(20),
			[Date] datetime,
			[Shift_Id] int,
			[InTime] nvarchar(25),
			[OutTime] nvarchar(25),
			[HrsWork] nvarchar(10),
			[HrsOT] nvarchar(10),
			[NormOT] nvarchar(10),
			[OffOT] nvarchar(10),
			[HolOT] nvarchar(10),
			[EarlyOut] nvarchar(10),
			[LateIn] nvarchar(10),
			[Attendance] nvarchar(20),
			[WorkHrs] nvarchar(10),
			[HrsLess] nvarchar(10),
			[HrsExtra] nvarchar(10),
			[LateInMins] float,
			[EarlyOutMins] float,
			[ExtraMins] float,
			[OtMins] float,
			[OvertimeStatus] nvarchar(50),
			[TotalDays] numeric(18, 1),
			[LeaveCode] nvarchar(20),
			[LateEntryReason] nvarchar(260),
			[EarlyOutReason] nvarchar(260),
			[ProcessFlag] bit,
			[Status] nvarchar(50),
			[FNAttendanceCode] nvarchar(15),
			[ANAttendanceCode] nvarchar(15)
	  )
	  /****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
		(
			[Employee_Code_Id] ASC
		) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData(
	[CLK_ID] [bigint] NOT NULL,
	[CLK_CARDID] [nvarchar](20) NULL,
	[CLK_DEVICEID] [nvarchar](20) NULL,
	[CLK_DATE] [datetime] NULL,
	[CLK_TIME] [nvarchar](25) NULL,
	[CLK_TYPE] [nvarchar](15) NULL,
	[CLK_FLAG] [int] NULL,
	[CLK_PROCESS] [int] NULL,
	[TimecheckDateTime] [datetime] NULL,
	[TimeStamp] [datetime] NOT NULL)
declare @gintRawCount bigint
declare @gintProcessCount bigint
declare @gintLeaveCount bigint
declare @gintPermissionCount bigint
declare @gintManualEntryCount bigint
  declare @sqlQuery as varchar(8000)  
  declare @sqlQuery1 as varchar(8000) 
  declare @sqlQuery2 as varchar(8000) 
  declare @sqlQuery3 as varchar(8000)
  declare @sqlQuery4 as varchar(8000) 
declare @Result as varchar(1000) 
Declare @Index int
Set @Index = 0;
EXEC sp_xml_preparedocument @Index OUTPUT, @EmployeeCodeIds
insert into #ReprocessEmployees (EmployeeCodeId)
select EmployeeId
from OpenXML(@Index, ''/NewDataSet/ReprocessEmployees'')
With (EmployeeId varchar(15) ''EmployeeId'')
Exec sp_xml_removedocument @Index		  
 insert into #TempProcessedData 
 select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
insert into #Clk_RawData
select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
from TA_Tbl_CLK_RAWDATA
where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
  set @sqlQuery=''''  
  set @sqlQuery = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id ''  
  --set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''    
  set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''    
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery = @sqlQuery + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery = @sqlQuery + '' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery = @sqlQuery + '' and (LA.Leave_FromDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery = @sqlQuery + '' or LA.Leave_ToDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery = @sqlQuery + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery = @sqlQuery + '' and (LA.Status IN ( ''''Forwarded'''',''''Pending''''))'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery = @sqlQuery + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessLeave exec(@sqlQuery)
set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
--  set @sqlQuery = @sqlQuery + '' and Month('''''' + cast( @dtClosingMonth as varchar(20)) + '''''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))''  
  set @sqlQuery1=''''  
  set @sqlQuery1 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id ''  
  --set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id ''    
   set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery1 = @sqlQuery1 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery1 = @sqlQuery1 + '' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery1 = @sqlQuery1 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery1 = @sqlQuery1 + '' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery1 = @sqlQuery1 + '' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
  --set @sqlQuery1 = @sqlQuery1 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery1 = @sqlQuery1 + '' and (mt.Clk_Process = ''''N'''') and (mt.ManualTimeEntry_Status != ''''Rejected'''')'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
insert into #tblProcessManualEntry exec(@sqlQuery1)
set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
  set @sqlQuery2=''''  
  set @sqlQuery2 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery2 = @sqlQuery2 + '' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id ''  
  --set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery2 = @sqlQuery2 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery2 = @sqlQuery2 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
  set @sqlQuery2 = @sqlQuery2 + '' AND E.Isdeleted=0''  
  --set @sqlQuery2 = @sqlQuery2 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery2 = @sqlQuery2 + '' and pd.Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery2 = @sqlQuery2 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery2 = @sqlQuery2 + '' and (pd.ProcessFlag =0 )'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery2 = @sqlQuery2 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessProcessData exec(@sqlQuery2)
set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
  set @sqlQuery3=''''  
  set @sqlQuery3 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery3 = @sqlQuery3 + '' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery3 = @sqlQuery3 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
   if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery3 = @sqlQuery3 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
  set @sqlQuery3 = @sqlQuery3 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery3 = @sqlQuery3 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
  set @sqlQuery3 = @sqlQuery3 + '' AND E.Isdeleted=0''  
  --set @sqlQuery3 = @sqlQuery3 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery3 = @sqlQuery3 + '' and crd.Clk_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery3 = @sqlQuery3 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery3 = @sqlQuery3 + '' and (crd.Clk_Flag =0 or crd.Clk_Process =0)'' 
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery3 = @sqlQuery3 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessRaw exec(@sqlQuery3)
set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
set @sqlQuery4=''''  
  set @sqlQuery4 = ''select Count(*) as Count from TA_TBL_Employee E ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id ''  
  --set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
  --set @sqlQuery4 = @sqlQuery4 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
  set @sqlQuery4 = @sqlQuery4 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id ''
  if exists(select * from #ReprocessEmployees)
  begin
  set @sqlQuery4 = @sqlQuery4 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
  end
   set @sqlQuery4 = @sqlQuery4 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
  --set @sqlQuery4 = @sqlQuery4 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
  set @sqlQuery4 = @sqlQuery4 + '' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1''  
  --set @sqlQuery4 = @sqlQuery4 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
  --set @sqlQuery4 = @sqlQuery4 + '' and pm.Permission_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
  --set @sqlQuery4 = @sqlQuery4 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
  set @sqlQuery4 = @sqlQuery4 + '' and (pm.Permission_Status IN ( ''''Forwarded'''',''''Pending''''))''  
--if not(@EmployeeCodeIds='''')
--begin
-- set @sqlQuery4 = @sqlQuery4 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
--end
insert into  #tblProcessPermission exec(@sqlQuery4)
set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
set @Result=N''?? ??? ???????? ''
if(@gintRawCount>0)
	begin
	set @Result=@Result + N'' ?????? ''
	end 
if(@gintProcessCount>0)
begin
	if(@gintRawCount>0)
	begin
	set @Result=@Result + '',''
	end
set @Result=@Result + N'' ?????? ????? '' 
end
if(@gintLeaveCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0)
			begin
			set @Result=@Result + '',''
			end
		set @Result=@Result + N'' ?????? ''
	end
if(@gintPermissionCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
					begin
					set @Result=@Result + '',''
					end
		set @Result=@Result + N'' ?????  ''
	end
if(@gintManualEntryCount>0)
	begin
		if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
							begin
							set @Result=@Result + '',''
							end
		set @Result=@Result + N'' ????? ????? ?????? ''
	end
set @Result=@Result + N'' ???? ?????? ''
if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
begin
set @Result=@Result
end
else
begin
set @Result=''''
end
drop table #LevelRights
drop table #ReprocessEmployees
drop table #tblProcessRaw
drop table #tblProcessProcessData
drop table #tblProcessLeave
drop table #tblProcessPermission
drop table #tblProcessManualEntry
drop table #TempProcessedData
drop table #Clk_RawData
select @Result as Result
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--[Proc_TA_GetUnProcessedDataCountMonthClsoure]70,''2012/01/01'',''2012/01/31'',''<NewDataSet />'',''SuperAdmin'',70
CREATE    PROCEDURE [dbo].[Proc_TA_GetUnProcessedDataCountMonthClsoure]  
/****************************************************************************************/          
-- Name    : Proc_TA_GetUnProcessedDataCountMonthClsoure ''1'',''2/1/2012'',''02/22/2012'',''<NewDataSet></NewDataSet>'',''SuperAdmin'',1  
-- Desc    :       
-- Company : Angler Technologies          
-- Author  : P.Prabakaran          
-- Date    : 17-Mar-2009          
-- Update History :   [Date Updated By (Initials) Reason]          
/****************************************************************************************/          
@vcLevelId varchar(8000),  
@dtFromDate datetime =null,
@dtToDate datetime =null,
@EmployeeCodeIds xml,
@UserGroupName varchar(250), 
@ParentId int 
as  
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
	[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
	[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
	[EmployeeId] ASC
	)ON [PRIMARY]
	create table #ReprocessEmployees(EmployeeCodeId varchar(15))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@dtToDate as nvarchar(50)), 102) and EL.LevelId is not null
	inner join #LevelRights on #LevelRights.LevelId=EL.levelId
	create table #tblProcessRaw(intCount bigint)
	create table #tblProcessProcessData(intCount bigint)
	create table #tblProcessLeave(intCount bigint)
	create table #tblProcessPermission(intCount bigint)
	create table #tblProcessManualEntry(intCount bigint)
	CREATE TABLE #TempProcessedData([Process_Rec_ID] bigint,[Employee_Code_Id] nvarchar(20),[Date] datetime,[Shift_Id] int,
	[InTime] nvarchar(25),[OutTime] nvarchar(25),[HrsWork] nvarchar(10),[HrsOT] nvarchar(10),[NormOT] nvarchar(10),[OffOT] nvarchar(10),[HolOT] nvarchar(10),[EarlyOut] nvarchar(10),
	[LateIn] nvarchar(10),[Attendance] nvarchar(20),[WorkHrs] nvarchar(10),[HrsLess] nvarchar(10),[HrsExtra] nvarchar(10),[LateInMins] float,[EarlyOutMins] float,[ExtraMins] float,
	[OtMins] float,[OvertimeStatus] nvarchar(50),[TotalDays] numeric(18, 1),[LeaveCode] nvarchar(20),[LateEntryReason] nvarchar(260),[EarlyOutReason] nvarchar(260),[ProcessFlag] bit,[Status] nvarchar(50),
	[FNAttendanceCode] nvarchar(15),[ANAttendanceCode] nvarchar(15))
	/****** Object:  Index [IDX_Date]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Date] ON [dbo].[#TempProcessedData] 
	(
	[Employee_Code_Id] ASC
	) ON [PRIMARY]		
	CREATE TABLE #Clk_RawData([CLK_ID] [bigint] NOT NULL,[CLK_CARDID] [nvarchar](20) NULL,[CLK_DEVICEID] [nvarchar](20) NULL,[CLK_DATE] [datetime] NULL,[CLK_TIME] [nvarchar](25) NULL,[CLK_TYPE] [nvarchar](15) NULL,[CLK_FLAG] [int] NULL,[CLK_PROCESS] [int] NULL,[TimecheckDateTime] [datetime] NULL,[TimeStamp] [datetime] NOT NULL)
	declare @gintRawCount bigint
	declare @gintProcessCount bigint
	declare @gintLeaveCount bigint
	declare @gintPermissionCount bigint
	declare @gintManualEntryCount bigint
	declare @sqlQuery as varchar(8000)  
	declare @sqlQuery1 as varchar(8000) 
	declare @sqlQuery2 as varchar(8000) 
	declare @sqlQuery3 as varchar(8000)
	declare @sqlQuery4 as varchar(8000) 
	declare @Result as varchar(1000) 
	Declare @Index int
	Set @Index = 0;
	EXEC sp_xml_preparedocument @Index OUTPUT, @EmployeeCodeIds
	insert into #ReprocessEmployees (EmployeeCodeId)select EmployeeId from OpenXML(@Index, ''/NewDataSet/ReprocessEmployees'') With (EmployeeId varchar(15) ''EmployeeId'')
	Exec sp_xml_removedocument @Index		  
	insert into #TempProcessedData 
		select [Process_Rec_ID],[Employee_Code_Id],[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
		[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
		[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode] from TA_Tbl_ProcessedData PD
		where PD.Date between @dtFromDate and @dtToDate and ProcessFlag=0
	insert into #Clk_RawData
		select CLK_ID, CLK_CARDID, CLK_DEVICEID, CLK_DATE, CLK_TIME, CLK_TYPE, CLK_FLAG, CLK_PROCESS, TimecheckDateTime,[TimeStamp]
		from TA_Tbl_CLK_RAWDATA
		where Clk_Date between @dtFromDate and @dtToDate and Clk_Process=0
--select * from #Clk_RawData
--select * from #ReprocessEmployees
--select * from #TempProcessedData
	set @sqlQuery=''''  
	set @sqlQuery = ''select Count(*) as Count from TA_TBL_Employee E ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_LeaveApplication LA on  E.Employee_Id=LA.Employee_Id ''  
	--set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
	--set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=LA.YearSettings_Id ''    
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	--set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId ''    
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery = @sqlQuery + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
		end
	set @sqlQuery = @sqlQuery + '' AND E.Isdeleted=0 and LA.IsDeleted=0 and ys.IsActive=1''  
	--set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
	set @sqlQuery = @sqlQuery + '' and (LA.Leave_FromDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
	set @sqlQuery = @sqlQuery + '' or LA.Leave_ToDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
	--set @sqlQuery = @sqlQuery + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
	set @sqlQuery = @sqlQuery + '' and (LA.Status IN ( ''''Forwarded'''',''''Pending''''))'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery = @sqlQuery + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
	insert into  #tblProcessLeave exec(@sqlQuery)
	set @gintLeaveCount=(select sum(isnull(intCount,0)) from #tblProcessLeave)
	--  set @sqlQuery = @sqlQuery + '' and Month('''''' + cast( @dtClosingMonth as varchar(20)) + '''''') in (Month(LA.Leave_FromDate),Month(LA.Leave_ToDate))''  
	set @sqlQuery1=''''  
	set @sqlQuery1 = ''select Count(*) as Count from TA_TBL_Employee E ''  
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_TBL_ManualTimeEntry mt on  E.Employee_Code_Id=mt.ManualTimeEntry_Employee_Id ''  
	--set @sqlQuery1 = @sqlQuery1 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
	--set @sqlQuery1 = @sqlQuery1 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
	set @sqlQuery1 = @sqlQuery1 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=mt.YearSettings_Id ''    
	set @sqlQuery1 = @sqlQuery1 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	--set @sqlQuery1 = @sqlQuery1 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery1 = @sqlQuery1 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
		end
	set @sqlQuery1 = @sqlQuery1 + '' AND E.Isdeleted=0 and mt.IsDeleted=0 and ys.IsActive=1''  
	--set @sqlQuery1 = @sqlQuery1 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
	set @sqlQuery1 = @sqlQuery1 + '' and (mt.ManualTimeEntry_InDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
	set @sqlQuery1 = @sqlQuery1 + '' or mt.ManualTimeEntry_OutDate between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102)) ''    
	--set @sqlQuery1 = @sqlQuery1 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
	set @sqlQuery1 = @sqlQuery1 + '' and (mt.Clk_Process = ''''N'''') and (mt.ManualTimeEntry_Status != ''''Rejected'''')'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery1 = @sqlQuery1 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
	insert into #tblProcessManualEntry exec(@sqlQuery1)
	set @gintManualEntryCount=(select sum(isnull(intCount,0)) from #tblProcessManualEntry)
	set @sqlQuery2=''''  
	set @sqlQuery2 = ''select Count(*) as Count from TA_TBL_Employee E ''  
	set @sqlQuery2 = @sqlQuery2 + '' inner join #TempProcessedData pd on  E.SwipeCardNo=pd.Employee_Code_Id ''  
	--set @sqlQuery2 = @sqlQuery2 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
	--set @sqlQuery2 = @sqlQuery2 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery2 = @sqlQuery2 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
		end
	set @sqlQuery2 = @sqlQuery2 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	--set @sqlQuery2 = @sqlQuery2 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
	set @sqlQuery2 = @sqlQuery2 + '' AND E.Isdeleted=0''  
	--set @sqlQuery2 = @sqlQuery2 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
	set @sqlQuery2 = @sqlQuery2 + '' and pd.Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
	--set @sqlQuery2 = @sqlQuery2 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
	set @sqlQuery2 = @sqlQuery2 + '' and (pd.ProcessFlag =0 )'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery2 = @sqlQuery2 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
	insert into  #tblProcessProcessData exec(@sqlQuery2)
	set @gintProcessCount=(select sum(isnull(intCount,0)) from #tblProcessProcessData)
	--select * from #tblProcessProcessData
	set @sqlQuery3=''''  
	set @sqlQuery3 = ''select Count(*) as Count from TA_TBL_Employee E ''  
	set @sqlQuery3 = @sqlQuery3 + '' inner join #Clk_RawData crd on  E.SwipeCardNo=crd.clk_CardId ''  
	--set @sqlQuery3 = @sqlQuery3 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
	--set @sqlQuery3 = @sqlQuery3 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id '' 
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery3 = @sqlQuery3 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
		end
	set @sqlQuery3 = @sqlQuery3 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	--set @sqlQuery3 = @sqlQuery3 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
	set @sqlQuery3 = @sqlQuery3 + '' AND E.Isdeleted=0''  
	--set @sqlQuery3 = @sqlQuery3 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
	set @sqlQuery3 = @sqlQuery3 + '' and crd.Clk_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
	--set @sqlQuery3 = @sqlQuery3 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
	set @sqlQuery3 = @sqlQuery3 + '' and (crd.Clk_Flag =0 or crd.Clk_Process =0)'' 
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery3 = @sqlQuery3 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
	insert into  #tblProcessRaw exec(@sqlQuery3)
	set @gintRawCount=(select sum(isnull(intCount,0)) from #tblProcessRaw)
	--select * from #tblProcessRaw
	set @sqlQuery4=''''  
	set @sqlQuery4 = ''select Count(*) as Count from TA_TBL_Employee E ''  
	set @sqlQuery4 = @sqlQuery4 + '' inner join TA_TBL_Permission pm on  E.Employee_Id=pm.Employee_Id ''  
	--set @sqlQuery4 = @sqlQuery4 + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''  
	--set @sqlQuery4 = @sqlQuery4 + '' inner join Ta_tbl_leveldetails ld on  EL.LevelId=ld.id ''  
	set @sqlQuery4 = @sqlQuery4 + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=pm.YearSettings_Id ''
	if exists(select * from #ReprocessEmployees)
		begin
			set @sqlQuery4 = @sqlQuery4 + '' inner join #ReprocessEmployees ON #ReprocessEmployees.EmployeeCodeId = E.Employee_Code_Id '' 
		end
	set @sqlQuery4 = @sqlQuery4 + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	--set @sqlQuery4 = @sqlQuery4 + '' inner join #LevelRights on #LevelRights.LevelId=EL.LevelId '' 
	set @sqlQuery4 = @sqlQuery4 + '' AND E.Isdeleted=0 and pm.IsDeleted=0 and ys.IsActive=1''  
	--set @sqlQuery4 = @sqlQuery4 + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=  CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) order by EffectiveDate desc) ''  
	set @sqlQuery4 = @sqlQuery4 + '' and pm.Permission_Date between CONVERT(DATETIME, '''''' + cast(@dtFromDate as nvarchar(11)) + '''''', 102) and CONVERT(DATETIME, '''''' + cast(@dtToDate as nvarchar(11)) + '''''', 102) ''
	--set @sqlQuery4 = @sqlQuery4 + '' and (EL.LevelId IN ('' + @vcLevelId  + ''))''  
	set @sqlQuery4 = @sqlQuery4 + '' and (pm.Permission_Status IN ( ''''Forwarded'''',''''Pending''''))''  
	--if not(@EmployeeCodeIds='''')
	--begin
	-- set @sqlQuery4 = @sqlQuery4 + '' and (e.Employee_Code_Id IN ('' + @EmployeeCodeIds  + ''))''  
	--end
	insert into  #tblProcessPermission exec(@sqlQuery4)
	set @gintPermissionCount=(select sum(isnull(intCount,0)) from #tblProcessPermission)
	--select * from #tblProcessPermission 
	set @Result=''Non Processed ''
	if(@gintRawCount>0)
		begin
			set @Result=@Result + '' Device ''
		end 
	if(@gintProcessCount>0)
		begin
			if(@gintRawCount>0)
				begin
					set @Result=@Result + '',''
				end
			set @Result=@Result + ''Data Process ''
		end
	if(@gintLeaveCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0)
				begin
					set @Result=@Result + '',''
				end
			set @Result=@Result + ''Leave''
		end
	if(@gintPermissionCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0)
				begin
					set @Result=@Result + '',''
				end
			set @Result=@Result + ''Permission ''
		end
	if(@gintManualEntryCount>0)
		begin
			if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0)
				begin
					set @Result=@Result + '',''
				end
			set @Result=@Result + ''Manual Entry ''
		end
	set @Result=@Result + ''Data Exists''
	if(@gintRawCount>0 or @gintProcessCount>0 or @gintLeaveCount>0 or @gintPermissionCount>0 or @gintManualEntryCount>0)
		begin
			set @Result=@Result
		end
	else
		begin
			set @Result=''''
		end
	drop table #LevelRights
	drop table #EmpLevel
	drop table #ReprocessEmployees
	drop table #tblProcessRaw
	drop table #tblProcessProcessData
	drop table #tblProcessLeave
	drop table #tblProcessPermission
	drop table #tblProcessManualEntry
	drop table #TempProcessedData
	drop table #Clk_RawData
	select @Result as Result
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_VehicleDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_VehicleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified by	:	P.Prabakaran
Modified on	:	7-Feb-08
*/
CREATE  Proc [dbo].[Proc_TA_GetTransportation_VehicleDetails]
@UserGroupName nvarchar(250)
as
Create table #TempTransportation(VehicleId int,VehicleNo nvarchar(40),VehicleDescription nvarchar(500),Isdeleted bit,flag int)
if(@UserGroupName=''SuperAdmin'')	
	BEGIN
		insert into #TempTransportation
		SELECT VehicleId,VehicleNo,VehicleDescription,Isdeleted,0 FROM TA_Tbl_Transportation_Vehicle 
	END
else
	BEGIN
		insert into #TempTransportation
		SELECT VehicleId,VehicleNo,VehicleDescription,Isdeleted,0 FROM TA_Tbl_Transportation_Vehicle Where IsDeleted=0
	END
	Update #TempTransportation set flag=1 from #TempTransportation TT inner join TA_Tbl_RouteMaster Rm on TT.VehicleId=Rm.VehicleID 	where TT.Isdeleted =0
	Select * from #TempTransportation
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetailsByID]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_RouteDetailsByID]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  Proc [dbo].[Proc_TA_GetTransportation_RouteDetailsByID] (@ID int) as      
SELECT R.[Id],R.Level_Id,R.VehicleID,
V.VehicleNo,L.Name,R.Route_Name,R.Route_Description FROM TA_Tbl_RouteMaster R
LEFT OUTER JOIN TA_Tbl_Transportation_Vehicle V ON V.VehicleId=R.VehicleID
LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=R.Level_Id
Where R.id=@ID
 --Where R.IsDeleted= 0 AND R.id=@ID
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_RouteDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_RouteDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name 	:	Proc_TA_GetTransportation_RouteDetails        
Description 	:	Get Transportation Route Details    
Tables Included :	TA_Tbl_RouteMaster and TA_Tbl_Transportation_Vehicle      
Created By 	:	        
Created On 	:	    
Modified By 	:	Prabakaran.P    
Modified On 	:	07-Feb-08   
*/  
CREATE  Proc [dbo].[Proc_TA_GetTransportation_RouteDetails] 
	@usergroupname nvarchar(50)
as     
Create table #TempTransportation(Id int,Route_Name nvarchar(100),Route_Description varchar(500),VehicleNo nvarchar(40),IsDeleted bit,flag int)
if(@usergroupname=''SuperAdmin'')
	BEGIN
		Insert into #TempTransportation
		SELECT R.Id as Id,R.Route_Name as Route_Name,R.Route_Description as Route_Description,tv.VehicleNo as VehicleNo,R.IsDeleted,0
		FROM TA_Tbl_RouteMaster R
		inner join TA_Tbl_Transportation_Vehicle tv on tv.VehicleId=R.VehicleID
	END
else
	BEGIN          
		Insert into #TempTransportation
		SELECT R.Id as Id,R.Route_Name as Route_Name,R.Route_Description as Route_Description,tv.VehicleNo as VehicleNo,R.IsDeleted,0
		FROM TA_Tbl_RouteMaster R
		inner join TA_Tbl_Transportation_Vehicle tv on tv.VehicleId=R.VehicleID
		Where R.IsDeleted= 0  and tv.Isdeleted=0
	END
	update #TempTransportation set flag =1 from #TempTransportation TT inner join
	ta_tbl_employee E on E.Bus_Id=TT.Id --where E.Isdeleted=0
	select * from #TempTransportation
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTransportation_MappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTransportation_MappingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetTransportation_MappingDetails] as          
SELECT  A.id,A.VehicleId,A.RouteId,B.VehicleNo,C.Route_Name        
FROM  TA_Tbl_Transportation_Mapping A        
INNER JOIN TA_Tbl_Transportation_Vehicle B ON B.VehicleId=A.VehicleId         
JOIN TA_Tbl_RouteMaster C ON C.[Id]=A.RouteId  
Where A.IsDeleted=1
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleNameById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleNameById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_GetTitleNameById] as   
SELECT TitleId,TitleName FROM TA_Tbl_Title Where IsDeleted=1 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleMappingDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Procedure [dbo].[Proc_TA_GetTitleMappingDetailsById]    
(     
 @id int   
)     
As    
 DECLARE @Isdel int    
 SET @Isdel=1    
BEGIN    
 SELECT  C.Company_Name,C.Company_Id,R.Region_Name,R.Region_Id,B.Branch_Name,B.Branch_Id,D.Department_Name,D.Department_Id,
		S.Section_Name,S.Section_Id,T.TitleName, T.TitleId FROM TA_Tbl_TitleMapping A    
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id            
   join TA_Tbl_Region R ON R.Region_Id=A.Region_Id            
   join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id            
   JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id    
   JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id    
   JOIN TA_Tbl_Title T ON T.TitleId=A.TitleId    
WHERE A.IsDeleted=1  AND A.id=@id    
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleMappingDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleMappingDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE Proc [dbo].[Proc_TA_GetTitleMappingDetails] as  
SELECT  C.Company_Name,R.Region_Name,B.Branch_Name,D.Department_Name,S.Section_Name,T.TitleName,T.TitleId,A.[id] FROM TA_Tbl_TitleMapping A  
  Inner join TA_Tbl_CompanyDetails C ON C.Company_Id = A.Company_Id          
   join TA_Tbl_Region R ON R.Region_Id=A.Region_Id          
   join TA_Tbl_Branch B ON B.Branch_Id=A.Branch_Id          
   JOIN TA_Tbl_Department D ON D.Department_Id=A.Department_Id  
   JOIN TA_Tbl_Section S ON S.Section_Id=A.Section_Id  
   JOIN TA_Tbl_Title T ON T.TitleId=A.TitleId  
WHERE A.IsDeleted=1  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleFirstDetailsById]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleFirstDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[Proc_TA_GetTitleFirstDetailsById]  
(   
	@TitleId int,
	@UserGroupName nVarchar(250)  
)   
As   
BEGIN  
	DECLARE @Isdel int  
	SET @Isdel=0  
	IF(@UserGroupName = ''SuperAdmin'')
	BEGIN
		SELECT T.TitleId,T.TitleName,T.TitleDescription,T.levelID,L.Name,T.LeavePolicyId,P.PolicyName,T.GradeID,G.Grade_Name,T.IsDeleted FROM TA_Tbl_Title T  
		LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=T.LevelID  
		LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID  
		LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID  
		WHERE TitleId=@TitleId  
	END
	ELSE
	BEGIN
		SELECT T.TitleId,T.TitleName,T.TitleDescription,T.levelID,L.Name,T.LeavePolicyId,P.PolicyName,T.GradeID,G.Grade_Name,T.IsDeleted FROM TA_Tbl_Title T  
		LEFT OUTER JOIN TA_Tbl_Leveldetails L ON L.ID=T.LevelID  
		LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID  
		LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID  
		WHERE T.IsDeleted=@Isdel AND TitleId=@TitleId  
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTitleDetails]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTitleDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--	Proc_TA_GetTitleDetails ''SuperAdmin'',''''
--Modified By		:  Manjula.P  
--Modified On		:  06-Jan-2014
--Descriptions		:  Adding LD.name for displaying levels details
CREATE    Proc [dbo].[Proc_TA_GetTitleDetails] 
(
   @UserGroupName	nVarchar(250), 
   @Designation		nVarchar(100) 
)
AS
BEGIN
	set nocount on
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	SELECT	distinct T.TitleId,
			T.TitleName,
			T.TitleDescription,
			LD.name as LevelName,
			P.PolicyName,
			G.Grade_Name,
			T.IsDeleted,
			G.Grade_Level,
			flag=case when isnull(ED.DesignationID,0)=0 then 0 else 1 end
	FROM TA_Tbl_Title T  
	Left JOIN TA_Tbl_LevelDetails LD ON LD.Id = T.LevelID  
	Left JOIN #LevelRights ON #LevelRights.LevelId = T.LevelID 
	LEFT OUTER JOIN TA_Tbl_LeavePolicy P ON P.Policy_Id=T.LeavePolicyID 
	LEFT OUTER JOIN TA_Tbl_Grade G ON G.Grade_ID=T.GradeID 
	LEFT OUTER join TA_tbl_EmployeeDesignation ED on T.TitleId=ED.DesignationID
	where (isnull(@Designation,'''')='''' or T.TitleName like @Designation+''%'') and(@UserGroupName=''Superadmin'' or T.IsDeleted=0)
	order by T.TitleName
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==========================================================================================
-- Author:		R.Manikandan
-- Create date: 29-12-2015
-- Description:	Getting Shift Details using Employee Swipe card Number
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingShiftDetailsUsingEmpCardNumber]
@EmployeeCodeId varchar(50)
AS
BEGIN	
	SET NOCOUNT ON;
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	Declare @levelId int	
	set @levelId=
	(
		SELECT top 1 EL.LEVELID FROM 
		(
			SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EMPLOYEEID,EMP.Employee_Code_Id FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 	
			WHERE EMP.ISDELETED=0 and Employee_Code_Id=@EmployeeCodeId
			group by EmployeeId,Employee_Code_Id
		) ELEVEL
		INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID	
		AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,CAST(getdate() AS NVARCHAR(50)), 102) AND EL.LEVELID IS NOT NULL
	)
	while((select parentId from Ta_Tbl_levelDetails where id=@levelId)!=0)
	begin
		select @levelId=parentId from Ta_Tbl_levelDetails where id=@levelId
	end
	Declare @ShiftPatternExist int
	Declare @ShiftRosterExist int
	select @ShiftPatternExist=Pattern,@ShiftRosterExist=Roster from TA_Tbl_ApprovalSettings where CompanyId=@levelId
	Select Employee_Id,Employee_FirstName + '' '' + Employee_LastName AS ''EmployeeName'',@ShiftPatternExist as pattern,@ShiftRosterExist as Roaster
	from TA_Tbl_Employee Where Isdeleted=0 and Employee_Code_Id=@EmployeeCodeId
	select Shift_Id,Shift_ShortName + '' ( '' +Shift_StartTime + '' - '' + Shift_EndTime + '' ) '' as Shift_ShortName from TA_Tbl_Shift where Level_Id=@levelId and Isdeleted=0
	select * from TA_Tbl_ShiftPattern where Level_Id=@levelId and Isdeleted=0
	select * from TA_Tbl_ShiftRoaster where Level_Id=@levelId and Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_GettingHolidayDetailsUsingHolidayId]
	-- Add the parameters for the stored procedure here
	@HolidayId int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT distinct Holiday_Description from TA_Tbl_Holiday H inner join
	TA_Tbl_HolidayChildTable HCT on H.Holiday_Id=HCT.Holiday_Id where H.Isdeleted=0 and H.Holiday_Id=@HolidayId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
select * from TA_Tbl_Usergroup where groupName=''Project Manager''
Proc_TA_GetTimeSheetEntryDetails_Sanction 10,1,''Forwarded'','''','''',0,0,''2020/01/01'',''2020/07/30'',''superadmin'',1
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetTimeSheetEntryDetails_Sanction]
	@login_EmployeeID int,
	@LevelId varchar(2000),
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmpCategory int, 
	@EmpType int,
	@FromDate varchar(20)=null,    
	@ToDate varchar(20) =null,
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	
	if(@isReportingto=1)
	begin
		if(@Status!=''Forwarded'')
		BEGIN
			insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@login_EmployeeID) as EmpAutoId  
		END
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@login_EmployeeID) as EmpAutoId
		delete from #EmployeeIds where EmpAutoId=@login_EmployeeID
	end
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
	(
		select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'''')='''' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'''')='''' or (emp.Employee_FirstName + '' '' + isnull(emp.Employee_LastName,'''''''') like @EmployeeName+''%''))
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	
	--Employee Type insert in Temporary table
	insert into #EmpType 
	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from 
	(
		select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'''')='''' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'''')='''' or (emp.Employee_FirstName + '' '' + isnull(emp.Employee_LastName,'''''''') like @EmployeeName+''%''))
		and(ISNULL(@EmpType,0)=0 or et.TypeId=@EmpType)
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from 
	(
		select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		where emp.Isdeleted=0 
		and((isnull(@EmployeeId,'''')='''' or emp.Employee_Id=@EmployeeId))
		and(isnull(@EmployeeName,'''')='''' or (emp.Employee_FirstName + '' '' + isnull(emp.Employee_LastName,'''''''') like @EmployeeName+''%''))
		and(ISNULL(@EmpCategory,0)=0 or ec.CategoryId=@EmpCategory)
		and(isnull(@isReportingto,-1)=0 or (isnull(@isReportingto,-1)=1 and(emp.Employee_ID IN (select * from #EmployeeIds))))
		group by EmployeeId
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1	
	
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	select	E.Employee_Code_Id EmployeeID,
			isnull(E.Employee_FirstName,'''')+ isnull(E.Employee_MiddleName,'''')+isnull(E.Employee_LastName,'''') EmployeeName,
			case	when cast(@dateFormat as varchar(100))=106 then
							REPLACE(CONVERT(VARCHAR(11), tp.ShiftDate,@dateFormat),'''',''-'') 
					else CONVERT(VARCHAR, tp.ShiftDate, @dateFormat)
			end ShiftDate,
			P.Project_Name ProjectName,
			ptl.TaskName,
			tp.TaskHours,
			tp.TaskDescription,
			tp.SpentHours,
			tp.TaskDetailID,
			case when isnull(ts.ApprovedHours,'''')<>'''' then ts.ApprovedHours else tp.SpentHours end as ApprovedHours,
			tp.Status,
			E.Employee_Id,			
			RecordID=Dense_Rank()over(order by Employee_Code_Id,Shiftdate)
	from TA_TBL_Employee E
	inner join ta_tbl_taskprogressdetails tp on  E.Employee_Id=tp.TaskSubmittedBy
	left outer join ta_tbl_taskprogressStatus ts on tp.TaskDetailID=ts.TaskDetailID
	inner join TA_Tbl_Project P on P.Project_Id=tp.ProjectID
	inner join TA_tbl_ProjectTaskList PTL on (PTL.ProjectID=P.Project_Id and tp.TaskID=PTL.TaskID)
	Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id
	Inner join #EmpType on #EmpType.employeeid = E.Employee_Id
	Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id
	Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID
	inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id
	where E.Isdeleted=0
	and(ISNULL(@Status,'''')='''' or ISNULL(@Status,'''')=''All'' or tp.Status=ISNULL(@Status,''''))
	order by Employee_Id,convert(datetime,ShiftDate)
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end' 
END
GO

/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Working]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTheDashboardInformation_Working]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR         :     A.K.T.MOORTHI
-- CREATE DATE    :     01-AUG-2014
-- DESCRIPTION    :     GET THE DASHBOARD INFORMATION BASED ON FILTER 12/11/2014 2015/09/02
-- Proc_TA_GetTheDashboardInformation_Working '''', ''2020/08/10'', ''2020/08/10'',0,0,0,''superadmin'',''0'',''0''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Working]
      -- ADD THE PARAMETERS FOR THE STORED PROCEDURE HERE
      @EMPLOYEECODEID VARCHAR(MAX) = NULL,
      @FROMDATE datetime,
      @TODATE datetime,
      @Session INT,
      @ShiftID int,
      @ParentID int,
      @UserGroupName nvarchar(100),
      @GradeLevel NVARCHAR(20),
      @empId NVARCHAR(max)
AS
BEGIN 
	set nocount on;
	
	Declare @FromdateString varchar(20)
	declare @todat as nvarchar(20);
	set @todat=GETDATE();
	if @FROMDATE=''''
		begin
			  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+''-''+CONVERT(varchar(20),DATEPART(month,getdate()))+''-''+
			  case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,GETDATE()))
			  else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
		end   
	else
		begin
			  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(varchar(20),DATEPART(month,@fromdate))+''-''+
			  case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,@fromdate))
			  else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
	
	create table #TempProcessedPresentdata(ProcessRecId bigint)
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	Create table #FirstTableValue(TOPIC varchar(100),ValueCount int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
	Create table #SecondDummyTableValue(TOPIC varchar(100),Count int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
	Create table #ThirdDummyTableValue(Approval varchar(100),Approved int,Forwarded int,Pending varchar(100),ApprovedPercent varchar(30),ForwardedPercent varchar(30),PendingPercent varchar(30))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	if(@ParentID=0)
	begin
		Declare @groupid int
		set @groupid=(select groupId from TA_Tbl_Usergroup where groupName=@UserGroupName)
		insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
	end
	else
	begin 
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--insert into #LevelRights select LocationId from TA_tbl_ShiftAdd_Location where LocationId = @ParentID
	end
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'''',''''
	declare @isReportingto as int
	declare @IndividualUsers int
	select @isReportingto=ReportsBasedOn,@IndividualUsers=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@isReportingto>0 or @UserGroupName=''Superadmin'')
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
	end
	
	Insert into #EmpLevel
	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
	(
		select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
		inner join #LevelRights on #LevelRights.LevelId= el.LevelId
		where emp.Isdeleted=0 AND emp.Report_Exclude=0 and
		(isnull(@isReportingto,0)=0 or el.EmployeeId IN (select * from #EmployeeIds))
		and
		(isnull(@empId,0)=0 or @empid='''' or (@IndividualUsers=1 and Employee_Id=@empId))
		and
		((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,@FromdateString,102))) and emp.Employee_Code_Id<>''18000000''
		group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@FROMDATE as nvarchar(50)), 102) and EL.LevelId is not null
    
	Declare @Employeecount int
	Declare @EmployeePresentcount int
	Declare @EmployeePresentcountQuery nvarchar(4000)
	
	SELECT @Employeecount=count(Process_Rec_Id),
	@EmployeePresentcount=COUNT(case  when(FNAttendanceCode=''Present'' or ANAttendanceCode=''Present'') then 1 else 0 end)
	FROM TA_TBL_PROCESSEDDATA P
		  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
		  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
		  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
		  WHERE P.DATE=convert(varchar(max),@FromdateString)
		  and(ISNULL(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
		  
	IF ((ISNULL(@FROMDATE, '''') <> ''''))
    BEGIN
        --Getting Present Data
		if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
		begin
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			  End as PercentageValue from 
			  (
					SELECT	DISTINCT ''Present'' AS TOPIC, 
							COUNT(P.DATE) TotalEmployeeCount,
							1 AS HYPER, ''MonthlyAttendance'' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id						
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  WHERE (P.DATE=@FROMDATE) 
					AND (ANAttendanceCode=''PRESENT'' or FNAttendanceCode=''Present'')
					AND E.Report_Exclude=0 and E.Isdeleted=0 
					and 
					(
						(E.Employee_Status=1) or
						(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
					)
					and E.Employee_Code_Id<>''18000000''
					and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
					and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			   )as Present
		end	    
		--Getting Absent Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
		begin                 
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
						  Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			  End as AbsenteesPercent from 
			  (
					SELECT	DISTINCT ''Absent'' AS TOPIC, 
							COUNT(*) TotalEmployeeCount,
							2 AS HYPER, 
							''Absentees'' AS REPORTNAME 
					FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
					Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
					Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  
					WHERE (P.DATE=@FROMDATE) AND (ANAttendanceCode=''ABSENT'' AND FNAttendanceCode=''Absent'') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
					((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
					and E.Employee_Code_Id<>''18000000''
					and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
					and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			   ) as Absent
		end
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
		begin                
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			End as LeavePercent from 
			(
				SELECT	DISTINCT ''Approved Leave'' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						1 AS HYPER, ''Leave_Angler'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id  
				WHERE (P.DATE=@FROMDATE) 
				AND
				(
					FNAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'') or
					ANAttendanceCode not in(''Present'',''Absent'',''Weekly Off'',''Holiday'',''RH'')
				)
				AND E.Report_Exclude=0 and E.Isdeleted=0 
				and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Leave
		end
		--Getting Onduty Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
		begin 
			  insert into #FirstTableValue
			  select 
			  TOPIC,
			  TotalEmployeeCount,
			  HYPER,
			  REPORTNAME, 
			  Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			  End as OnDutyPercent from 
			  (
				SELECT	DISTINCT ''Approved OnDuty'' AS TOPIC, 
						COUNT(M.ManualTimeEntry_InDate) TotalEmployeeCount,
						4 AS HYPER, 
						''OnDuty'' AS REPORTNAME 
				FROM Ta_Tbl_ManualTimeEntry M
				inner join ta_tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
				Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id					
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
				(
					((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
					(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)
				)  
				WHERE (M.ManualTimeEntry_InDate <= @FROMDATE) AND (M.ManualTimeEntry_OutDate  >= @FROMDATE)
				AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''Approved'' And OD.Onduty_Status =''Approved'' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				(
					(E.Employee_Status=1) or
					( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				)
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as OnDuty
		end
        ----Getting Punctuality Data
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
		begin
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
					Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			End as PunctualityPercent from 
			(
				SELECT	DISTINCT ''Punctuality'' AS TOPIC, 
				COUNT(P.DATE) TotalEmployeeCount,
				6 AS HYPER, ''Punctuality'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE =@FROMDATE) AND ISNULL(LATEINMINS,0)=0 AND 
				(ANAttendanceCode<>''Weekly Off'' or FNAttendanceCode<>''Weekly Off'') AND (isnull(p.LateIn,''00:00'')<>''00:00'')
				AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				(
					(E.Employee_Status=1) or
					(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				) and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Punctuality
		end
				----Getting Rawdata
		if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
		begin
			insert into #FirstTableValue
			select 
			TOPIC,
			TotalEmployeeCount,
			HYPER,
			REPORTNAME, 
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
			End  as RawDataPercent from 
			(
				Select	''Attendance Summary'' As TOPIC,
				COUNT(P.DATE) TotalEmployeeCount,
				6 as HYPER,
				''AttendanceSummary'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND E.Report_Exclude=0 and E.Isdeleted=0 and       
				(
					(E.Employee_Status=1) or
					(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))
				)
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as Attendance
		end
		select * from #FirstTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        --ThirdBoard Table
        --Getting Late Entry Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
        begin
			 insert into #SecondDummyTableValue
             select	TOPIC,
						TotalEmployeeCount,
						HYPER,
						REPORTNAME,
						Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
								Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
						End as Percentage 
			  from 
			  (
				SELECT	DISTINCT ''Late Entry'' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						1 AS HYPER, ''LateEntry'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE =@FROMDATE) AND ISNULL(LATEINMINS,0)<>0  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			  ) as A

        end
        --Getting Early Exit Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
					End as Percentage 
			from 
			(                
				SELECT	DISTINCT ''Early Exit'' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						2 AS HYPER, ''EarlyExit'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P 
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND ISNULL(EarlyOutMins,0)<>0  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
        end
        --Getting Less Hours worked Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
        begin
            insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %'' 
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
					End as Percentage 
			from 
			(
				SELECT	DISTINCT ''Less Hours Worked'' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						3 AS HYPER, 
						''LessHoursWorked'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND P.HrsLess is not null and P.HrsLess<>''00:00'' and P.HrsLess<>'''' AND CHARINDEX(''-'',p.HrsLess)=0  
				AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			)as A

        end
        --Getting Approved Overtime Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
        begin
            insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
					End 
			as Percentage from 
			(
				SELECT	DISTINCT ''Approved Over Time'' AS TOPIC, 
						COUNT(P.DATE) TotalEmployeeCount,
						4 AS HYPER, 
						''OverTime'' AS REPORTNAME 
				FROM TA_TBL_PROCESSEDDATA P  
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				WHERE (P.DATE=@FROMDATE) AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''Approved'' 
				And E.CompOff_Eligible=0 And E.OT_Eligible=1  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
				((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102))) 
				and E.Employee_Code_Id<>''18000000''
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
        end         
        --Getting Discrepancy Data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME,  
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %'' 
							Else convert(varchar(20),Round(convert(varchar(20),(DistinctCOUNT*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
					End 
					as Percentage from 
					( 
						SELECT	DISTINCT ''Discrepancy'' AS TOPIC, 
								COUNT(C.Clk_EmpId) TotalEmployeeCount,
								COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
								5 AS HYPER, 
								''Discrepancy'' AS REPORTNAME 
						FROM ta_tbl_clockdetails C
						Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
						Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
						INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
						INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
						INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
						Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id   WHERE (C.Clk_Date =@FROMDATE) AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null)  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
						((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,@FROMDATE,102)))
						and E.Employee_Code_Id<>''18000000''
						and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
					) as A
        end
        --Getting Non processed data
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
        begin
			insert into #SecondDummyTableValue
			select	TOPIC,
					TotalEmployeeCount,
					HYPER,
					REPORTNAME, 
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),(TotalEmployeeCount*$1/isnull(@EmployeeCount,0) * 100)),0))+'' %'' 
					End as Percentage 
			from
			(
				Select	''Non Processed Record'' As TOPIC,
						COUNT(*)TotalEmployeeCount,
						COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
						6 as HYPER,
						''Non Process'' AS REPORTNAME 
				FROM TA_Tbl_Clk_RawData C           
				Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID   
				where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE =@FROMDATE
				--and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
			) as A
 
        end
        select * from #SecondDummyTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
        begin 
			insert into #ThirdDummyTableValue      
			select 
			''Leave'' as Approval,
			Approved,
			Forwarded,
			Pending,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/isnull(@EmployeeCount,0)) * 100),0))+'' %'' 
			End as ApprovedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0)) * 100),0))+'' %'' 
			End as ForwardedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0)) * 100),0))+'' %'' 
			End as PendingPercent from
			(
				select      
				count(case  when L.Status=''Approved'' then 1  end)Approved,
				count(case  when L.Status=''Forwarded'' then 1 end)Forwarded,
				count(case  when L.Status=''Pending''  then 1  end)Pending
				from TA_Tbl_LeaveApplication L 
				Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=e.SwipeCardNo and 
				(((l.Leave_FromDate BETWEEN P.Date AND P.Date) OR (l.Leave_ToDate BETWEEN P.Date AND P.Date)) OR 
				(P.Date BETWEEN l.Leave_FromDate AND l.Leave_ToDate))    where 
				L.Leave_FromDate <=@FROMDATE and 
				L.Leave_ToDate >=@FROMDATE and L.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'''')=''SuperAdmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			) as a  
        end
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
        begin
			insert into #ThirdDummyTableValue
			select 
			''Onduty'' as Approval,
			Approved,
			Forwarded,
			Pending,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),(Approved*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
			End as ApprovedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
			End as ForwardedPercent,
			Case  when isnull(@EmployeeCount,0)=0 then ''0 %''
			Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
			End as PendingPercent from
			(
				select                              
				count(case  when (M.ManualTimeEntry_Status =''Approved'' and OD.Onduty_Status =''Approved'') then 1 else null end) Approved,
				count(case  when (M.ManualTimeEntry_Status=''Forwarded'' and OD.Onduty_Status=''Forwarded'') then 1 else null end) Forwarded,
				count(case  when (M.ManualTimeEntry_Status=''Pending'' and OD.Onduty_Status=''Pending'')  then 1 else null end)  Pending
				from Ta_Tbl_ManualTimeEntry M 
				inner join TA_Tbl_OndutyEntry OD on (M.Onduty_ID=OD.Onduty_ID)
				Inner join TA_Tbl_Employee E 
				on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
				Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
				(((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
				(P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))   where M.IsOnDuty=1 and M.isDeleted=0 and
				M.ManualTimeEntry_InDate<=@FROMDATE and 
				M.ManualTimeEntry_OutDate>=@FROMDATE and M.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or P.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'''')=''SuperAdmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			) as B 

        end
        if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
        begin
			insert into #ThirdDummyTableValue
			select	''Permission'' as Approval,
					Approved,
					Forwarded,
					Pending,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
					End as ApprovedPercent,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
					End as ForwardedPercent,
					Case	when isnull(@EmployeeCount,0)=0 then ''0 %''
							Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/isnull(@EmployeeCount,0))*100),0))+'' %'' 
					End as PendingPercent 
			from
			(
				select 
				count(case  when P.Permission_Status=''Approved'' then 1 else null end) Approved,
				count(case  when P.Permission_Status=''Forwarded'' then  1 else null end)Forwarded,
				count(case  when P.Permission_Status=''Pending''  then 1 else null end) Pending
				from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
				Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
				INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
				INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
				INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
				Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
				Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date   
				where P.Permission_Date=@FROMDATE and P.IsDeleted=0 AND TA_Tbl_Grade.Grade_Level>=0
				and(isnull(@ShiftID,0)=0 or PD.Shift_Id=@ShiftID)
				and(ISNULL(@isReportingto,0)=0 or E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds))
				and(ISNULL(@UserGroupName,'''')=''SuperAdmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			)as A

        end
		select * from #ThirdDummyTableValue
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
	END
	Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
	drop table #EmpLevel
	drop table #LevelRights
	drop table #FirstTableValue
	drop table #SecondDummyTableValue
	drop table #ThirdDummyTableValue
	drop table #TempProcessedPresentdata
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetTheDashboardInformation_Surguru]    Script Date: 03/25/2021 10:22:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetTheDashboardInformation_Surguru]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <27_Aug_2019 02:33 PM>
-- Description:	<This procedure gives dashbaord informations created especially for surguru, four results set added with work location filter>
-- [Proc_TA_GetTheDashboardInformation_Surguru] '''', ''2019-08-30 00:00:00.000'', ''2019-08-30 00:00:00.000'',0,0,1,''SuperAdmin'',''0'',''0'',4
--select * from testDashboardSurguru
--select * from Ta_Tbl_levelDetails
	  --insert into testDashboardSurguru values
	  --(
	  --@EMPLOYEECODEID,
   --   @FROMDATE,
   --   @TODATE,
   --   @Session,
   --   @ShiftID,
   --   @ParentID,
   --   @UserGroupName,
   --   @GradeLevel,
   --   @empId,
	  --@WorkLocation 
	  --)
	--  	Create table testDashboardSurguru (

	--  EMPLOYEECODEID VARCHAR(MAX),
 --     FROMDATE datetime,
 --     TODATE datetime,
 --     Session INT,
 --     ShiftID int,
 --     ParentID int,
 --     UserGroupName nvarchar(100),
 --     GradeLevel NVARCHAR(20),
 --     empId NVARCHAR(max),
	--  WorkLocation int
	--)
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_GetTheDashboardInformation_Surguru] 
	-- Add the parameters for the stored procedure here
	  @EMPLOYEECODEID VARCHAR(MAX) = NULL,
      @FROMDATE datetime,
      @TODATE datetime,
      @Session INT,
      @ShiftID int,
      @ParentID int,
      @UserGroupName nvarchar(100),
      @GradeLevel NVARCHAR(20),
      @empId NVARCHAR(max),
	  @WorkLocation int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	  SET NOCOUNT ON;
	  Declare @FirstBoard varchar(max)
      Declare @FirstBoard1 varchar(max)
      Declare @SecondBoard varchar(max)
      Declare @ThirdBoard varchar(max)
      Declare @FourthBoard varchar(max)
      Declare @FifthBoard varchar(max)
      Declare @sixthBoard varchar(max)
      Declare @Present_Filters varchar(max)
      Declare @Absetn_Filters varchar(max)
      Declare @Leave_Filters varchar(max)
      Declare @Union varchar(max)
      set @Union='' Union All ''
      Declare @FromdateString varchar(20)
      declare @todat as nvarchar(20);
      set @todat=GETDATE();
      if @FROMDATE=''''
            begin
                  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+''-''+CONVERT(varchar(20),DATEPART(month,getdate()))+''-''+
                  case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,GETDATE()))
                  else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
            end   
      else
            begin
                  set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(varchar(20),DATEPART(month,@fromdate))+''-''+
                  case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,@fromdate))
                  else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
            end
      create table #TempProcesseddata(ProcessRecId bigint,PresentCount bigint)
      create table #TempProcessedPresentdata(ProcessRecId bigint)
      create table #LevelRights(LevelId int)
      create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
      Create table #FirstTableValue(TOPIC varchar(100),ValueCount int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
      Create table #SecondDummyTableValue(TOPIC varchar(100),Count int,Hyper int,ReportName varchar(100),PercentageValue varchar(30))
      Create table #ThirdDummyTableValue(Approval varchar(100),Approved int,Forwarded int,Pending varchar(100),ApprovedPercent varchar(30),ForwardedPercent varchar(30),PendingPercent varchar(30))
      CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
      if(@ParentID=0)
      begin
            Declare @groupid int
            set @groupid=(select groupId from TA_Tbl_Usergroup where groupName=@UserGroupName)
            insert into  #LevelRights select LevelId from TA_Tbl_LevelRights where GroupId=@groupid
      end
      else
      begin 
            insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId		
      end
	    INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'''',''''
		declare @isReportingto as int
		select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
		create table #EmployeeIds(EmpAutoId int)
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@empId) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@empId) as EmpAutoId
      Declare @sqlEmpLevel nvarchar(4000) 
      set @sqlEmpLevel=
      ''insert into #EmpLevel 
      select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
      (
            select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
            inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
            INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=emp.Employee_Id
            inner join #LevelRights on #LevelRights.LevelId= el.LevelId
            where emp.Isdeleted=0 AND emp.Report_Exclude=0 and 
            ((emp.Employee_Status=1) or( emp.Employee_Status=0 and convert(nvarchar(11),emp.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and emp.Employee_Code_Id<>''''18000000''''
            group by el.EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo
      ) ELevel
      inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102) and EL.LevelId is not null''    
      if(@isReportingto > 0)
            BEGIN
                  set @sqlEmpLevel = @sqlEmpLevel + '' and (Elevel.EmployeeId IN (select * from #EmployeeIds)) ''  
            END   
      if(@empId > 0 and (select IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName)=1)
            BEGIN
                  set @sqlEmpLevel = @sqlEmpLevel + '' and ELevel.EmployeeId in (''+CAST(@empId as nvarchar(10))+'')''
            END   
      execute(@sqlEmpLevel)
      Declare @Employeecount int
      Declare @EmployeePresentcount int
      Declare @EmployeecountQuery nvarchar(4000)
      Declare @EmployeePresentcountQuery nvarchar(4000)     
      set @EmployeecountQuery = ''insert into #TempProcesseddata SELECT count(Process_Rec_Id),
      COUNT(case  when(FNAttendanceCode=''''Present'''' or ANAttendanceCode=''''Present'''') then 1 else 0 end)
      FROM TA_TBL_PROCESSEDDATA P
                  Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
                  WHERE P.DATE=''''''+convert(varchar(max),@FromdateString)+''''''''
      if(@ShiftID!=0)
      begin
            set @EmployeecountQuery =@EmployeecountQuery +'' and P.Shift_Id=''+convert(varchar(10),@shiftId)
      end   
      execute (@EmployeecountQuery)
      select @Employeecount=ProcessRecId,@EmployeePresentcount=PresentCount from #TempProcesseddata
      IF ((ISNULL(@FROMDATE, '''') <> ''''))
            BEGIN
            --First Gridview Control
            Declare @CommonJoinQueries varchar(max)         
            Declare @CommonSelectQueries varchar(max) 
            set @FirstBoard=''''      
            Declare @Firstboardexists int
            set @Firstboardexists=0
            set @CommonJoinQueries=''''
            set @CommonJoinQueries=@CommonJoinQueries+'' Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
            Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
            INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
            INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
            INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID           
			left outer join ta_tbl_shiftadd_location LOC on LOC.EmployeeId = E.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102)''
			-- Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
            set @CommonSelectQueries=''''
            set @CommonSelectQueries=@CommonSelectQueries+''select 
                  TOPIC,
                  COUNT,
                  HYPER,
                  REPORTNAME, 
                  Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                              Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeeCount)+'' * 100)),0))+'''' %'''' 
                  End''
            Declare @Filters varchar(max)
            set @Filters=''''
            if(@ShiftID!=0)
            begin
                  set @Filters =@Filters+'' and P.Shift_Id=''+convert(varchar(10),@shiftId)
            end
            if(@UserGroupName<>''SuperAdmin'')
            BEGIN
                  SET @Filters = @Filters + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
            END
			--for Surguru--
			if(@WorkLocation<>0)
            BEGIN
                  SET @Filters = @Filters + '' AND LOC.LocationId='' + convert(varchar(100),@WorkLocation)
            END
            -- Added below line by manikandan.r on 16-11-2016
            -- if you remove below line it will bring wrong value for absent column.bug id:0035540
            if(@isReportingto > 0)
            BEGIN  
                  SET @Filters = @Filters + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
            End
            --Getting Present Data
            if((select ViewPrev from ta_tbl_DashboardUserrights DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=1)=1)
            begin
                  set @FirstBoard =@CommonSelectQueries+'' as PercentageValue from 
                  (
                        SELECT DISTINCT ''''Present'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''MonthlyAttendance'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''       
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries
                        SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') 
                        AND (ANAttendanceCode=''''PRESENT'''' or FNAttendanceCode=''''Present'''')
                        AND E.Report_Exclude=0 and E.Isdeleted=0 
                        and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
                        and E.Employee_Code_Id<>''''18000000''''''                       
                  set @FirstBoard=@FirstBoard+@Filters+'') as Present''
                  set @Firstboardexists=1
            end
            --Getting Absent Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=2)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard =@FirstBoard+@CommonSelectQueries+'' as AbsenteesPercent from 
                  (
                        SELECT DISTINCT ''''Absent'''' AS TOPIC, COUNT(*) [COUNT],2 AS HYPER, ''''Absentees'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries        
                        SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') AND 
                        (ANAttendanceCode=''''ABSENT'''' AND FNAttendanceCode=''''Absent'''') AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                        ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
                        and E.Employee_Code_Id<>''''18000000''''''
                  set @FirstBoard=@FirstBoard+@Filters+'') as Absent''
                  set @Firstboardexists=1
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=3)=1)
            begin
                  declare @LeaveCount varchar(max)
                  --Getting Leave Data          
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard=@FirstBoard+@CommonSelectQueries+'' as LeavePercent from 
                  (
                        SELECT DISTINCT ''''Approved Leave'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''Leave_Angler'''' AS REPORTNAME 
                        FROM TA_TBL_PROCESSEDDATA P''        
                        set @FirstBoard=@FirstBoard+@CommonJoinQueries
                        SET @FirstBoard = @FirstBoard + '' WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') 
                        AND 
                        (
                              FNAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''') or
                              ANAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''Holiday'''',''''RH'''')
                        )
                        AND E.Report_Exclude=0 and E.Isdeleted=0 
                        and ((E.Employee_Status=1) or(E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
                        and E.Employee_Code_Id<>''''18000000''''''                       
                  set @FirstBoard=@FirstBoard+@Filters+'') as Leave''
                  set @Firstboardexists=1
            end
            --Getting Onduty Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=4)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard =@FirstBoard+@Union
                  end
                  set @FirstBoard=@FirstBoard+@CommonSelectQueries+ '' as OnDutyPercent from (
                  SELECT DISTINCT ''''Approved OnDuty'''' AS TOPIC, COUNT(M.ManualTimeEntry_InDate) [COUNT],4 AS HYPER, ''''OnDuty'''' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
                  Inner join TA_Tbl_Employee E on E.Employee_Code_Id=M.ManualTimeEntry_Employee_Id
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
				  left outer join ta_tbl_shiftadd_location LOC on LOC.EmployeeId = E.Employee_Id and LOC.ShiftDate = CONVERT(DATETIME,''''''+cast(@FROMDATE as nvarchar(50))+'''''', 102)
                  Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo  and
                  (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
                  (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate)) ''
                  SET @FirstBoard = @FirstBoard + '' WHERE (M.ManualTimeEntry_InDate <= ''''''+convert(varchar(max),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  >= ''''''+convert(varchar(max),@FromdateString)+'''''') 
                  AND ISNULL(M.IsOnDuty,0)=1 And M.ManualTimeEntry_Status =''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
                  and E.Employee_Code_Id<>''''18000000''''''                       
                  set @FirstBoard=@FirstBoard+@Filters+'') as OnDuty''
                  set @Firstboardexists=1
            end
            --Getting Punctuality Data
			set @FirstBoard1 = ''''
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=5)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard1 =@FirstBoard1+@Union
                  end
                  set @FirstBoard1=@FirstBoard1+@CommonSelectQueries+ '' as PunctualityPercent from (
                  SELECT DISTINCT ''''Punctuality'''' AS TOPIC, COUNT(P.DATE) [COUNT],6 AS HYPER, ''''Punctuality'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P ''
                  SET @FirstBoard1 = @FirstBoard1 + @CommonJoinQueries
                  SET @FirstBoard1 = @FirstBoard1 + '' WHERE (P.DATE =''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)=0 AND 
                  (ANAttendanceCode<>''''Weekly Off'''' or FNAttendanceCode<>''''Weekly Off'''') AND (p.LateIn=''''00:00'''' and p.InTime <> ''''00:00'''')
                  AND E.Report_Exclude=0 and E.Isdeleted=0 and 
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) and E.Employee_Code_Id<>''''18000000''''''
                  set @FirstBoard1=@FirstBoard1+@Filters+'') as Punctuality''
                  set @Firstboardexists=1				
            end
            --Getting Rawdata
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=6)=1)
            begin
                  if @Firstboardexists=1
                  begin
                        set @FirstBoard1 =@FirstBoard1+@Union
                  end
                  set @FirstBoard1=@FirstBoard1+@CommonSelectQueries+ ''  as RawDataPercent from (
                  Select ''''Attendance Summary'''' As TOPIC,COUNT(P.DATE) [COUNT],
                  6 as HYPER,''''AttendanceSummary'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
                  SET @FirstBoard1 = @FirstBoard1 + @CommonJoinQueries
                  SET @FirstBoard1 = @FirstBoard1 + '' WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') AND E.Report_Exclude=0 and E.Isdeleted=0 and       
                  ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102)))
                  and E.Employee_Code_Id<>''''18000000''''''           
                  set @FirstBoard1=@FirstBoard1+@Filters+ '') as Attendance''
            end
            if(ISNULL(@FirstBoard,'''')!='''' and ISNULL(@FirstBoard1,'''')!='''')
            begin	 
                 Execute(''insert into #FirstTableValue '' + @FirstBoard + @FirstBoard1)
            end
            select * from #FirstTableValue
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            --Second Table
            --Getting Late Entry Data
            Declare @WhereFilter varchar(max)
            set @ThirdBoard=''''
            Declare @ThirdBoardvalue int
            set @ThirdBoardvalue =0
            set @WhereFilter ='' AND E.Report_Exclude=0 and E.Isdeleted=0 and 
            ((E.Employee_Status=1) or( E.Employee_Status=0 and convert(nvarchar(11),E.InActiveDate,102)>=convert(datetime,''''''+@FromdateString+'''''',102))) 
            and E.Employee_Code_Id<>''''18000000''''''
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=10)=1)
            begin
                  set @ThirdBoard=''  
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' 
                        End as Percentage from (
                  SELECT DISTINCT ''''Late Entry'''' AS TOPIC, COUNT(P.DATE) [COUNT],1 AS HYPER, ''''LateEntry'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE =''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(LATEINMINS,0)<>0 ''
                  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
                  set @ThirdBoardvalue=1
            end
            --Getting Early Exit Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=11)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+'' 
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
                        as Percentage from (                
                  SELECT DISTINCT ''''Early Exit'''' AS TOPIC, COUNT(P.DATE) [COUNT],2 AS HYPER, ''''EarlyExit'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P''
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries + ''WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(EarlyOutMins,0)<>0 ''
                  set @ThirdBoard = @ThirdBoard+@WhereFilter+@Filters+'') as A''
                  set @ThirdBoardvalue=1
            end
            --Getting Less Hours worked Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=12)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+''
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End as 
                        Percentage from (                   
                  SELECT DISTINCT ''''Less Hours Worked'''' AS TOPIC, COUNT(P.DATE) [COUNT],3 AS HYPER, ''''LessHoursWorked'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P ''
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ '' WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') AND P.HrsLess is not null and P.HrsLess<>''''00:00'''' and P.HrsLess<>'''''''' AND CHARINDEX(''''-'''',p.HrsLess)=0 ''
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
                  set @ThirdBoardvalue=1
            end
            --Getting Approved Overtime Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=13)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+''
                  select TOPIC,COUNT,HYPER,REPORTNAME,Case when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                        Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
                        as Percentage from (                
                  SELECT DISTINCT ''''Approved Over Time'''' AS TOPIC, COUNT(P.DATE) [COUNT],4 AS HYPER, ''''OverTime'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P ''
                  set @ThirdBoard=@ThirdBoard+@CommonJoinQueries+ ''  WHERE (P.DATE=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.OtMins,0)<>0 AND P.OverTimeStatus =''''Approved'''' And E.CompOff_Eligible=0 And E.OT_Eligible=1 ''
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+@Filters+'') as A''
                  set @ThirdBoardvalue=1 
            end         
            --Getting Discrepancy Data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=14)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+''
                  select      TOPIC,
                              COUNT,
                              HYPER,
                              REPORTNAME,  
                              Case  when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                                          Else convert(varchar(20),Round(convert(varchar(20),(DistinctCOUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
                                          as Percentage from 
                  ( 
                        SELECT      DISTINCT ''''Discrepancy'''' AS TOPIC, 
                                    COUNT(C.Clk_EmpId) [COUNT],
                                    COUNT(Distinct C.Clk_EmpId) [DistinctCOUNT],
                                    5 AS HYPER, 
                                    ''''Discrepancy'''' AS REPORTNAME 
                        FROM ta_tbl_clockdetails C
                        Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.Clk_EmpId 
                        Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                        INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                        INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                        INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                        Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
                  SET @ThirdBoard = @ThirdBoard + ''  WHERE (C.Clk_Date =''''''+convert(varchar(max),@FromdateString)+'''''') AND C.IsVoid=0 and (C.clk_inTime is null or C.clk_outTime is null) ''
                  set @ThirdBoard=@ThirdBoard+@WhereFilter+'') as A''
                  set @ThirdBoardvalue=1 
            end
            --Getting Non processed data
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=15)=1)
            begin
                  if @ThirdBoardvalue=1
                  begin
                        set @ThirdBoard =@ThirdBoard+@Union
                  end
                  set @ThirdBoard=@ThirdBoard+''
                  select      TOPIC,
                              COUNT,
                              HYPER,
                              REPORTNAME, 
                              Case  when ''+convert(varchar(10),@EmployeePresentcount)+''=0 then ''''0 %''''
                                          Else convert(varchar(20),Round(convert(varchar(20),(COUNT*$1/''+convert(varchar(10),@EmployeePresentcount)+'' * 100)),0))+'''' %'''' End 
                                          as Percentage 
                  from(
                              Select      ''''Non Processed Record'''' As TOPIC,
                                          COUNT(*)[COUNT],
                                          COUNT(Distinct CLK_CARDID) [DistinctCOUNT],
                                          6 as HYPER,
                                          ''''Non Process'''' AS REPORTNAME 
                              FROM TA_Tbl_Clk_RawData C           
                  Inner join TA_Tbl_Employee E on E.SwipeCardNo=C.CLK_CARDID
                  Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                  INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                  INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                  INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID  ''
                  SET @ThirdBoard = @ThirdBoard + '' where CLK_FLAG=1 and CLK_PROCESS=0 and ReasonId in (1,2,3,4) and CLK_DATE =''''''+convert(varchar(max),@FromdateString)+''''''''
                  set @ThirdBoard=@ThirdBoard+'') as A''
            end
            --Execute(@ThirdBoard)
            if(ISNULL(@ThirdBoard,'''')!='''')
            begin
           -- print (@ThirdBoard)
                  Execute(@ThirdBoard)
            end
            else
            begin
                  select * from #SecondDummyTableValue
            end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            Declare @SecondBoardValue int
            set @SecondBoardValue=0
            set @FifthBoard='' ''
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=7)=1)
            begin
            set @FifthBoard=@FifthBoard+''
            select 
                  ''''Leave'''' as Approval,
                  Approved,
                  Forwarded,
                  Pending,
                  Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                              Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/''+convert(varchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
                  End as ApprovedPercent,
                  Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                              Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/''+convert(varchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
                  End as ForwardedPercent,
                  Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                              Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/''+convert(varchar(10),@EmployeeCount)+'') * 100),0))+'''' %'''' 
                  End as PendingPercent from
            (
                        select      
                                    count(case  when L.Status=''''Approved'''' then 1  end)Approved,
                                    count(case  when L.Status=''''Forwarded'''' then 1 end)Forwarded,
                                    count(case  when L.Status=''''Pending''''  then 1  end)Pending
                        from TA_Tbl_LeaveApplication L 
                        Inner join TA_Tbl_Employee E on E.Employee_Id=L.Employee_Id 
                        Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                        INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                        INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                        INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                        Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
                        Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=e.SwipeCardNo and 
                        (((l.Leave_FromDate BETWEEN P.Date AND P.Date) OR (l.Leave_ToDate BETWEEN P.Date AND P.Date)) OR 
                        (P.Date BETWEEN l.Leave_FromDate AND l.Leave_ToDate))  ''
                        SET @FifthBoard = @FifthBoard + ''  where 
                        L.Leave_FromDate <='''''' + CONVERT(varchar(max),@FromdateString) +'''''' and 
                        L.Leave_ToDate >='''''' + CONVERT(varchar(max),@FromdateString) +'''''' and L.IsDeleted=0''
                        if(@ShiftID!=0)
                              begin
                                    set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(varchar(10),@shiftId)
                              end               
                        if(@UserGroupName<>''SuperAdmin'')
                              BEGIN
                                    SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
                              END
                        if(@isReportingto > 0)
                        BEGIN  
                              SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
                        End         
                        set @FifthBoard=@FifthBoard+'') as a''
                        set @SecondBoardValue=1                         
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=8)=1)
            begin
                  if @SecondBoardValue=1
                  begin
                        set @FifthBoard =@FifthBoard+@Union
                  end
                  set @FifthBoard=@FifthBoard+ '' select 
                        ''''Onduty'''' as Approval,
                        Approved,
                        Forwarded,
                        Pending,
                        Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                    Else convert(varchar(20),Round(convert(varchar(20),(Approved*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                        End as ApprovedPercent,
                        Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                    Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                        End as ForwardedPercent,
                        Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                    Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                        End as PendingPercent from
                        (
                                    select                              
                                    count(case  when M.ManualTimeEntry_Status =''''Approved'''' then 1 else null end) Approved,
                                    count(case  when M.ManualTimeEntry_Status=''''Forwarded'''' then 1 else null end) Forwarded,
                                    count(case  when M.ManualTimeEntry_Status=''''Pending''''  then 1 else null end)  Pending
                                    from Ta_Tbl_ManualTimeEntry M Inner join TA_Tbl_Employee E 
                                    on E.Employee_Code_id=M.ManualTimeEntry_Employee_Id
                                    Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
                                    INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                                    INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                                    INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID 
                                    Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
                                    Inner join TA_Tbl_ProcessedData P on P.Employee_Code_Id=E.SwipeCardNo and 
                                    (((M.ManualTimeEntry_InDate BETWEEN P.Date AND P.Date) OR (M.ManualTimeEntry_OutDate BETWEEN P.Date AND P.Date)) OR 
                                    (P.Date BETWEEN M.ManualTimeEntry_InDate AND M.ManualTimeEntry_OutDate))  ''
                  SET @FifthBoard = @FifthBoard + '' where M.IsOnDuty=1 and M.isDeleted=0 and
                  M.ManualTimeEntry_InDate<=''''''+ CONVERT(varchar(max),@FromdateString) +'''''' and 
                  M.ManualTimeEntry_OutDate>=''''''+ CONVERT(varchar(max),@FromdateString) +'''''' and M.IsDeleted=0''
                  if(@ShiftID!=0)
                        begin
                              set @FifthBoard=@FifthBoard+'' and P.Shift_Id=''+convert(varchar(10),@shiftId)
                        end         
                  if(@UserGroupName<>''SuperAdmin'')
                        BEGIN
                              SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
                        END   
                  if(@isReportingto > 0)
                  BEGIN  
                        SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
                  End               
                  set @FifthBoard=@FifthBoard+'') as B ''
                  set @SecondBoardValue=1 
            end
            if((select ViewPrev from ta_tbl_DashboardUserrights  DUR inner join TA_Tbl_Usergroup ug on ug.groupId=DUR.Usergroupid where ug.groupName=@UserGroupName and DUR.Boardid=9)=1)
            begin
                  if @SecondBoardValue=1
                  begin
                        set @FifthBoard =@FifthBoard+@Union
                  end
                  set @FifthBoard=@FifthBoard+'' select ''''Permission'''' as Approval,
                              Approved,
                        Forwarded,
                        Pending,
                              Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Approved)*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                              End as ApprovedPercent,
                              Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Forwarded)*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                              End as ForwardedPercent,
                              Case  when ''+convert(varchar(10),@EmployeeCount)+''=0 then ''''0 %''''
                                          Else convert(varchar(20),Round(convert(varchar(20),((Pending)*$1/''+convert(varchar(10),@EmployeeCount)+'')*100),0))+'''' %'''' 
                              End as PendingPercent from
                  (
                              select 
                                          count(case  when P.Permission_Status=''''Approved'''' then 1 else null end) Approved,
                                          count(case  when P.Permission_Status=''''Forwarded'''' then  1 else null end)Forwarded,
                                          count(case  when P.Permission_Status=''''Pending''''  then 1 else null end) Pending
                              from TA_Tbl_Permission P Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id 
                              Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id 
                              INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id
                              INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId
                                    INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID
                  Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id 
                  Inner join TA_Tbl_ProcessedData PD on PD.Employee_Code_Id=E.SwipeCardNo and P.Permission_Date=PD.Date  ''
                  SET @FifthBoard = @FifthBoard + '' where P.Permission_Date=''''''+ CONVERT(varchar(max),@FromdateString) +'''''' and P.IsDeleted=0''
                  if(@ShiftID!=0)
                        begin
                              set @FifthBoard=@FifthBoard+'' and PD.Shift_Id=''+convert(varchar(10),@shiftId)
                        end         
                  if(@UserGroupName<>''SuperAdmin'')
                        BEGIN
                              SET @FifthBoard = @FifthBoard + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
                        END   
                  if(@isReportingto > 0)
                  BEGIN  
                        SET @FifthBoard = @FifthBoard + '' and E.Employee_Id in  (select distinct EmpAutoId from #EmployeeIds) ''
                  End   
                  set @FifthBoard=@FifthBoard+'')as A''
            end
            if(ISNULL(@FifthBoard,'''')!='''')
            begin
                  Execute(@FifthBoard)
            end
            else
            begin
                  select * from #ThirdDummyTableValue
            end
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
      END
      Select @Employeecount as Employeecount,@EmployeePresentcount as EmployeePresentcount    
      drop table #EmpLevel
      drop table #LevelRights
      drop table #FirstTableValue
      drop table #SecondDummyTableValue
      drop table #ThirdDummyTableValue
      drop table #TempProcesseddata
      drop table #TempProcessedPresentdata
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetailsById]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftRoasterDetailsById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	17-Dec-2013
-- Description	:	Get The Shift Roster Value By Id
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetailsById]
	@ShiftRosterId BIGINT
AS
BEGIN
	SELECT SR.*,LD.name FROM TA_Tbl_ShiftRoaster SR 
		INNER JOIN TA_Tbl_Leveldetails LD ON SR.Level_Id = LD.id  
	WHERE SR.ShiftRoaster_Id = @ShiftRosterId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftRoasterDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftRoasterDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
	Created By		:	A.K.T.MOORTHI
	Created Date	:	17-Dec-2013
	Description		:	Get The Shift Roster Details
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetShiftRoasterDetails]
	@UserGroupName NVARCHAR(250),	
	@ParentId BIGINT
AS
BEGIN
	CREATE TABLE #LevelRights(LevelId INT)
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	SELECT
		SR.ShiftRoaster_Id,
		SR.ShiftRoaster_Name,
		SR.NumberOfPatterns,
		LD.name,
		(CASE WHEN SR.IsDeleted = 1 THEN ''True'' ELSE ''False'' END) IsDeleted
	FROM TA_Tbl_ShiftRoaster SR
		INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SR.Level_Id
		INNER JOIN #LevelRights on #LevelRights.LevelId=SR.Level_Id
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetShiftExchangeDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetShiftExchangeDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_GetShiftExchangeDetails  
Description : To get the Shift Exchange Employee Details
Tables Included : TA_Tbl_Employee,Ta_Tbl_ShiftExchange,ta_tbl_shift
Created By : Sasireka  
Created On : 13-Jan-2009 
Modified By :  
Modified On :  
*/  
--exec [Proc_TA_GetShiftExchangeDetails] ''S'','' '','' '',''Super Admin'',''1'',''1,47,136,145,146,147,151,152,153,154,1,137,138,2,3,140,47,113,132,133,134,135,150,155,159,160,161,162''
CREATE  PROCEDURE [dbo].[Proc_TA_GetShiftExchangeDetails]
@Employee_ID int,
@mode char(1),
@fromdate datetime,
@todate datetime,
@UserGroupName varchar(250), 
@GradeLevel varchar(1000), 
@LevelRights varchar(8000),
@ParentId int 
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
declare @sql as varchar(8000)
set @sql=''''
BEGIN
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	IF(@mode = ''A'')
	BEGIN
		SET @sql =''select 
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, ta_tbl_shiftExchange.Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, ta_tbl_shiftExchange.Date, ''+cast(@dateFormat as varchar(100))+'') end	as date ,
		e1.Employee_Code_Id + '''' - '''' + e1.employee_Firstname + '''' '''' + e1.Employee_LastName as Employee1Name, ''
		SET @sql = @sql + '' isnull(s1.shift_Shortname,''''Weekly Off'''') as ShiftName1 ,e2.Employee_Code_Id + '''' - '''' + e2.employee_Firstname +  '''' '''' + e2.Employee_LastName  as Employee2Name,isnull(s2.Shift_ShortName,''''Weekly Off'''') as ShiftName2 ,ld.name as LevelName''
		SET @sql = @sql + '' from ta_tbl_shiftExchange ''
		set @sql = @sql + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=ta_tbl_shiftExchange.YearSettings_Id ''
		SET @sql = @sql + '' inner join ta_tbl_LevelDetails ld on ta_tbl_shiftexchange.Level_Id=ld.id ''
		SET @sql = @sql + '' inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id ''
		SET @sql = @sql + '' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id ''
		SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel el1 ON e1.Employee_Id = el1.EmployeeId ''
		SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel el2 ON e2.Employee_Id = el2.EmployeeId ''
		SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation edes1 ON e1.Employee_Id = edes1.EmployeeId ''
		SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation edes2 ON e2.Employee_Id = edes2.EmployeeId ''	
		SET @sql = @sql + '' INNER JOIN TA_Tbl_Title tit1 ON tit1.TitleId=edes1.DesignationId ''
		SET @sql = @sql + '' INNER JOIN TA_Tbl_Title tit2 ON tit2.TitleId=edes2.DesignationId '' 
		SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade grd1 ON grd1.Grade_ID = tit1.GradeId '' 
		SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade grd2 ON grd2.Grade_ID = tit2.GradeId ''
		SET @sql = @sql + '' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift ''
		SET @sql = @sql + '' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift ''
		SET @sql = @sql + '' INNER JOIN #LevelRights LR1 ON LR1.LevelId = el1.LevelId '' 
		SET @sql = @sql + '' INNER JOIN #LevelRights LR2 ON LR2.LevelId = el2.LevelId ''
		SET @sql = @sql + '' where ys.IsActive=1 ''
		if(@UserGroupName<>''SuperAdmin'')
			begin
				SET @sql = @sql + '' AND grd1.Grade_Level>='' + @GradeLevel + ''''
				SET @sql = @sql + '' AND grd2.Grade_Level>='' + @GradeLevel + ''''
			end
		if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (e1.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		SET @sql = @sql + '' And el1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
		SET @sql = @sql + '' And el2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
		SET @sql = @sql + '' And edes1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
		SET @sql = @sql + '' And edes2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
		exec (@sql)
	END
	IF(@mode = ''S'')
		BEGIN
			SET @sql =''select case when ''+cast(@dateFormat as varchar(100))+''=106 then
			REPLACE(CONVERT(VARCHAR, ta_tbl_shiftExchange.Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
			else CONVERT(VARCHAR, ta_tbl_shiftExchange.Date, ''+cast(@dateFormat as varchar(100))+'') end as date		
			 ,e1.Employee_Code_Id + '''' - '''' + e1.employee_Firstname as Employee1Name, ''
			SET @sql = @sql + '' isnull(s1.shift_Shortname,''''Weekly Off'''') as ShiftName1,e2.Employee_Code_Id + '''' - '''' + e2.employee_Firstname as Employee2Name,isnull(s2.Shift_ShortName,''''Weekly Off'''') as ShiftName2 ,ld.name as LevelName ''
			SET @sql = @sql + '' from ta_tbl_shiftExchange ''
			set @sql = @sql + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=ta_tbl_shiftExchange.YearSettings_Id ''
			SET @sql = @sql + '' inner join ta_tbl_LevelDetails ld on ta_tbl_shiftexchange.Level_Id=ld.id ''
			SET @sql = @sql + '' inner join ta_tbl_employee e1 on ta_tbl_shiftexchange.employee1_id=e1.employee_id ''
			SET @sql = @sql + '' inner join ta_tbl_employee e2 on ta_tbl_shiftexchange.employee2_id=e2.employee_id ''
			SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel el1 ON e1.Employee_Id = el1.EmployeeId ''
			SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeLevel el2 ON e2.Employee_Id = el2.EmployeeId ''
			SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation edes1 ON e1.Employee_Id = edes1.EmployeeId ''
			SET @sql = @sql + '' INNER JOIN TA_Tbl_EmployeeDesignation edes2 ON e2.Employee_Id = edes2.EmployeeId ''	
			SET @sql = @sql + '' INNER JOIN TA_Tbl_Title tit1 ON tit1.TitleId=edes1.DesignationId ''
			SET @sql = @sql + '' INNER JOIN TA_Tbl_Title tit2 ON tit2.TitleId=edes2.DesignationId '' 
			SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade grd1 ON grd1.Grade_ID = tit1.GradeId '' 
			SET @sql = @sql + '' INNER JOIN TA_Tbl_Grade grd2 ON grd2.Grade_ID = tit2.GradeId ''
			SET @sql = @sql + '' inner join ta_tbl_shift s1 on s1.shift_id=ta_tbl_shiftExchange.Employee1_actualshift ''
			SET @sql = @sql + '' inner join ta_tbl_shift s2 on s2.shift_id=ta_tbl_shiftExchange.Employee2_actualshift ''
			SET @sql = @sql + '' INNER JOIN #LevelRights LR1 ON LR1.LevelId = el1.LevelId '' 
			SET @sql = @sql + '' INNER JOIN #LevelRights LR2 ON LR2.LevelId = el2.LevelId ''
			SET @sql = @sql + '' where ys.IsActive=1 and (ta_tbl_shiftExchange.Date >= CONVERT(DATETIME,'''''' + cast(@fromdate as varchar(20)) + '''''', 102))  and ''
			SET @sql = @sql + '' (ta_tbl_shiftExchange.Date <= CONVERT(DATETIME,'''''' + cast(@todate as varchar(20)) + '''''',102)) ''
			if(@UserGroupName<>''SuperAdmin'')
				begin
					SET @sql = @sql + '' AND grd1.Grade_Level>='' + @GradeLevel + ''''			
					SET @sql = @sql + '' AND grd2.Grade_Level>='' + @GradeLevel + ''''
				end
			if(@isReportingto > 0)
            BEGIN
               set @sql = @sql + '' and (e1.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
			SET @sql = @sql + '' And el1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
			SET @sql = @sql + '' And el2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
			SET @sql = @sql + '' And edes1.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e1.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
			SET @sql = @sql + '' And edes2.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeDesignation where EmployeeId = e2.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(),102) order by EffectiveDate desc)''
			exec (@sql)
			drop table #LevelRights
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- [Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear] 179,-1,2
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesForSuccessiveYear]
(
	@Employee_Id int,
	@LeaveType_Id int,
	@YearSettingId int
)
AS
Begin
	SET NOCOUNT ON;
	declare @LeaveApplicationCount as decimal(18,1)
	declare @LOPCount as decimal(18,1)
	declare @CurrentyearSettingId int
	Declare @SuccessiveYearSettingId int
	Declare @SuccesiveLeavepolicyCount float
	Declare @MaxapplicableDays float
	Declare @CurrentYearStartDate datetime
	declare @isWFH int
	select @CurrentyearSettingId=yearsettings_Id,@CurrentYearStartDate=FromDate from ta_tbl_yearsetting where Isactive=1	
	select top 1 @SuccessiveYearSettingId = yearsettings_Id from ta_tbl_yearsetting where yearSettings_Id > (select Yearsettings_Id from ta_tbl_yearsetting where Isactive=1)
	Declare @DateofJoining datetime
	Select @DateofJoining=DateOfJoining from TA_Tbl_Employee where Employee_Id=@Employee_Id and Isdeleted=0 and Employee_Status=1
	Select @isWFH=isWFH from TA_Tbl_LeaveType where LeaveType_Id=@LeaveType_Id
	if(@LeaveType_Id<>-1)
	begin
		select @LeaveApplicationCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
		where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id 
		and la.Employee_Id=@Employee_Id and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
		and la.status not in(''Rejected'') and la.isdeleted=0 and la.IsBorrow=0
		select @LOPCount=sum(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
		inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
		where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id 
		and la.Employee_Id=@Employee_Id and la.Type in (''LOP'') 
		and la.status not in(''Rejected'') and la.isdeleted=0 and la.IsBorrow=0
		if(@YearSettingId = @CurrentyearSettingId)
		begin
			if(@LeaveApplicationCount > 0)
			begin
				Select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeavesCurrentYear,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed,
				case when(CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										end *LPD.MaxDays_Month
						end			
					else
						case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										end *LPD.MaxDays_Month
						end
			end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											end *LPD.MaxDays_Month
							end			
						else
							case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
							end
				end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end 
				RemainingNoOfLeaves	,isnull(@isWFH,0) as isWFH
				from TA_tbl_Yearclosure yc
				inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
				inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId and yc.employee_Id=la.Employee_id and la.YearSettings_Id=ys.YearSettings_Id
				inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
				inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId  and LPD.LeaveType_Id=yc.LeaveTypeID)
				left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
				where yc.employee_Id=@Employee_Id and LPD.LeaveType_Id=@LeaveType_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 and la.Status in (''Pending'',''Forwarded'',''Approved'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.IsBorrow=0 
				Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			end
			else 
			begin
				declare @TempYearSettingsId int
				--print''s''
				set @TempYearSettingsId= (select Yearsettings_Id from ta_tbl_yearSetting where Isactive=1)				
				select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) as RemainingNoOfLeavesCurrentYear,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed,
				case when (CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end
					else
						case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,@DateofJoining,getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end					
			end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 			
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end
						else
							case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end					
				end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end RemainingNoOfLeaves,isnull(@isWFH,0) as isWFH
				from TA_tbl_Yearclosure yc
				inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
				inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
				inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId  and LPD.LeaveType_Id=yc.LeaveTypeID)
				left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
				where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId				
				Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			end
		end
		else if(@YearSettingId=@SuccessiveYearSettingId)
		begin	
			select top 1 @MaxapplicableDays=MaxDays_applicable from ta_tbl_leavepolicydetails where policy_Id=(select top 1 Leavepolicy_Id from ta_tbl_emp_leavepolicy where EmployeeId=@Employee_Id and LeaveType_Id=@LeaveType_Id order by ta_tbl_emp_leavepolicy.ToDate desc)
			select @SuccesiveLeavepolicyCount=sum(NumberofDays) from ta_tbl_LeaveApplication where YearSettings_Id=@YearSettingId and Isdeleted=0 and status <> ''Rejected'' and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
			and Employee_Id=@Employee_Id and LeaveType_Id=@LeaveType_Id
			if @SuccesiveLeavepolicyCount is null
			begin
				set @SuccesiveLeavepolicyCount=0.0
			end	
			select @MaxapplicableDays - @SuccesiveLeavepolicyCount as RemainingNoOfLeaves,ISNULL(@LeaveApplicationCount,0) as availed,ISNULL(@LOPCount,0) as LOPavailed
		end
	end
	else
	begin
		if(@YearSettingId = @CurrentyearSettingId)
		begin
			Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as ''Number of Days / year'',
			case when(CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										end *LPD.MaxDays_Month
						end			
					else
						case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
								when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										end *LPD.MaxDays_Month
						end
			end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case	when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
											end *LPD.MaxDays_Month
							end			
						else
							case	when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
									when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											 end *	LPD.MaxDays_Month-ISNULL(sum(la.NumberOfDays),0.0))>LPD.No_Of_Days then LPD.No_Of_Days
									else	case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
													else DATEDIFF(month,@DateofJoining,getdate())+1
											end *LPD.MaxDays_Month
							end
				end - (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end 
			as ''Number of Days''
			from TA_tbl_Yearclosure yc
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
			inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId and LPD.LeaveType_Id=lt.LeaveType_Id)
			left outer join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lt.LeaveType_Id and la.YearSettings_Id=ys.YearSettings_Id
			left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
			where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 
			and la.Status in (''Pending'',''Forwarded'',''Approved'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
			and la.IsBorrow=0 
			Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType,LPD.MaxDays_Month,ys.FromDate,LPD.No_Of_Days,NoOffLeaveAvailed,ltd.PreviousYearBalance
			union
			Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as ''Number of Days / year'',
			case when (CASE	WHEN DATEPART(d,@DateofJoining)>15 then
						case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end
					else
						case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
							 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
							else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
										else DATEDIFF(month,@DateofJoining,getdate())+1
								 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
						end					
			end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0))<=0 then 0
			else 			
				CASE	WHEN DATEPART(d,@DateofJoining)>15 then
							case when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining))<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,DATEADD(d,-DATEPART(d,@DateofJoining)+1,dateadd(MONTH,1,@DateofJoining)),getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end
						else
							case when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))<0 then 0 
								 when	(case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
												else DATEDIFF(month,@DateofJoining,getdate())+1
										 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0))>LPD.No_Of_Days then LPD.No_Of_Days
								else case	when @DateofJoining<=ys.FromDate then DATEDIFF(month,ys.fromdate,getdate())+1
											else DATEDIFF(month,@DateofJoining,getdate())+1
									 end *LPD.MaxDays_Month- ISNULL(yc.Encashment,0.0)
							end					
				end-ISNULL(ltd.NoOffLeaveAvailed,0)+ISNULL(yc.carry_PrevYear,0.0)+ISNULL(ltd.PreviousYearBalance,0.0)
			end
			as ''Number of Days''
			from TA_tbl_Yearclosure yc
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=yc.Employee_Id and LP.YearSettingId=yc.Year_SettingID)
			inner join TA_Tbl_Emp_LeavePolicyDetails LPD on (LP.LeavePolicy_Id=LPD.Policy_ID and LP.Emp_LeavePolicyId=LPD.Emp_LeavePolicyId and LPD.LeaveType_Id=lt.LeaveType_Id)
			left outer join ta_tbl_emp_LeaveTypedetails LTD on (LP.EmployeeId=LTD.EmployeeId and LTD.LeaveTypeId=LPD.LeaveType_Id and yc.Year_SettingID=LTD.YearSettingsId)
			where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (
			select LeaveType_Id from Ta_Tbl_LeaveApplication la
			inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id
			where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
			and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and Status not in (''Rejected'') and ys.IsActive=1)
			and ys.YearSettings_Id=@YearSettingId
		end
		else if (@YearSettingId=@SuccessiveYearSettingId)
		begin	
			Select lt.LeaveType as ''Leave Type'',(ISNULL(LPD.MaxDays_Applicable,0.0))
			- (ISNULL(sum(la.NumberOfDays),0.0)) as ''Number of Days / year'',LPD.MaxDays_Month,
			case when (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month- (ISNULL(sum(la.NumberOfDays),0.0))<0 then 0
			else (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month- (ISNULL(sum(la.NumberOfDays),0.0)) 
			end as ''Number of Days''
			from ta_tbl_leavepolicydetails LPD
			inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=@CurrentyearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=LPD.LeaveType_Id
			left outer join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =lt.LeaveType_Id and la.YearSettings_Id=ys.YearSettings_Id
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=elp.EmployeeId and LP.YearSettingId=elp.YearSettingId)			
			where elp.EmployeeId=@Employee_Id 
			and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@CurrentyearSettingId and la.Isdeleted=0 
			and la.Status in (''Pending'',''Forwarded'',''Approved'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
			and la.IsBorrow=0 
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid 
			where TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id and TA_Tbl_YearSetting.IsActive=1 order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
			Group by lt.LeaveType_Id,LPD.MaxDays_Applicable,lt.LeaveType,LPD.MaxDays_Month,ys.FromDate
			union
			Select lt.LeaveType as ''Leave Type'',(ISNULL(LPD.MaxDays_Applicable,0.0)) as ''Number of Days / year'',LPD.MaxDays_Month,
			case when (DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month>ELPD.No_Of_Days then ELPD.No_Of_Days else  
			(DATEDIFF(month,@CurrentYearStartDate,getdate())+1)*LPD.MaxDays_Month
			end
			as ''Number of Days''
			from ta_tbl_leavepolicydetails LPD 
			inner join TA_Tbl_Emp_LeavePolicy elp on elp.LeavePolicy_Id=lpd.Policy_Id 
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=@CurrentyearSettingId
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=LPD.LeaveType_Id
			inner join TA_Tbl_Emp_LeavePolicy LP on (LP.EmployeeId=elp.EmployeeId and LP.YearSettingId=elp.YearSettingId)
			inner join TA_Tbl_Emp_LeavePolicyDetails ELPD on 
			(LP.Emp_LeavePolicyId=ELPD.Emp_LeavePolicyId and ELPD.LeaveType_Id=lt.LeaveType_Id and ELPD.EmpID=LP.EmployeeId)
			where elp.EmployeeId=@Employee_Id and LPD.Leavetype_Id not in(
			select LeaveType_Id from Ta_Tbl_LeaveApplication la
			where la.Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
			and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and Status not in (''Rejected'')and la.YearSettings_Id=@CurrentyearSettingId)
			and ys.YearSettings_Id=@CurrentyearSettingId
			and elp.ToDate =(select top 1 TA_Tbl_Emp_LeavePolicy.ToDate from TA_Tbl_Emp_LeavePolicy
			inner join TA_Tbl_YearSetting on TA_Tbl_YearSetting.YearSettings_Id=TA_Tbl_Emp_LeavePolicy.YearSettingid 
			where TA_Tbl_Emp_LeavePolicy.EmployeeId=@Employee_Id and TA_Tbl_YearSetting.IsActive=1 order by TA_Tbl_Emp_LeavePolicy.ToDate desc)
		end
	end
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetRemainingNumberOfLeaves 10849
Description		:	Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	09-Aug-07
Modified By		:	Prabakaran
Modified On		:	13-Aug-07
*/
Create PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeavesforEncashment]
@Employee_Id int,
@LeaveType_Id int
AS
declare @LeaveApplicationCount as int
if(@LeaveType_Id<>-1)
	begin
	set @LeaveApplicationCount=(select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
					inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
					where ys.IsActive=1 and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.status not in(''Rejected'')  and la.isdeleted=0 and la.IsBorrow=0)
	if(@LeaveApplicationCount > 0)
		begin
		Select (ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
		inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.IsActive=1 and la.Isdeleted=0 and la.Status in (''Pending'',''Forwarded'',''Approved'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment
		end
	else 
		begin
		Select ((ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves 
		from TA_tbl_Yearclosure yc
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
		where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.IsActive=1  Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment
		end
	end
else
	begin
	-- For Leave Quota Popup Page
	Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as ''Number of Days''
	from TA_tbl_Yearclosure yc
	inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id 
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
	left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id
	where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.IsActive=1 and la.Isdeleted=0 
	and la.Status in (''Pending'',''Forwarded'',''Approved'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
	and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType
	union
	Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as ''Number of Days''
	from TA_tbl_Yearclosure yc
	inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
	inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID
	where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (
	select LeaveType_Id from Ta_Tbl_LeaveApplication la
	inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id
	where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0 
	and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and Status not in (''Rejected'') and ys.IsActive=1)
	and ys.IsActive=1  
	end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfLeaves]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfLeaves]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N' /*  
Procedure Name : Proc_TA_GetRemainingNumberOfLeaves 35,1,0,''01/28/2019'' 
Select ISNULL(NumberOfDays,0.0) from Ta_Tbl_LeaveApplication where LeaveApplication_Id = 1 and LeaveType_id = 1 and Employee_Id = 3 
Description  : Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id  
Tables Included : Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting  
Created By  : Prabakaran  
Created On  : 09-Aug-07  
Modified By  : Prabakaran  
Modified On  : 13-Aug-07  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfLeaves]  
@Employee_Id int,  
@LeaveType_Id int,
@leaveApplicationId int,
@FromDate datetime  
AS  
declare @LeaveApplicationCount as int  
DECLARE @resendLeaveDays as int
declare @YearSettingId as int
begin
	SET NOCOUNT ON;
	if(@LeaveType_Id<>-1)
		BEGIN
			select @YearSettingId = YearSettings_Id from Ta_Tbl_LeaveApplication where LeaveApplication_Id = @leaveApplicationId
		END
	else
		BEGIN
			select @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where @FromDate between FromDate and ToDate
		END
	if(@LeaveType_Id<>-1 and @leaveApplicationId<>0)  
		 begin  
			set @LeaveApplicationCount=(select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la  
			inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id   
			where ys.YearSettings_Id=@YearSettingId and la.LeaveType_Id=@LeaveType_Id and la.Employee_Id=@Employee_Id and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.status not in(''Rejected'')  and la.isdeleted=0 and la.IsBorrow=0)  
			if(@leaveApplicationId<>0)
					begin				
						SET @resendLeaveDays = (Select ISNULL(NumberOfDays,0.0) from Ta_Tbl_LeaveApplication where LeaveApplication_Id = @leaveApplicationId and LeaveType_id = @LeaveType_Id and Employee_Id = @Employee_Id)			
					end
			else
					begin
						SET @resendLeaveDays = 0
					end	
			 if(@LeaveApplicationCount > 0)  	
				  begin 
					  Select (@resendLeaveDays + ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves   
					  from TA_tbl_Yearclosure yc  
					  inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
					  inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and  la.YearSettings_Id=ys.YearSettings_Id  
					  where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0 and la.Status in (''Pending'',''Forwarded'',''Approved'',''Resend'',''Reply'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment  
				  end  
			else   
				  begin  
				  Select ((ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0)) as RemainingNoOfLeaves   
				  from TA_tbl_Yearclosure yc  
				  inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
				  where yc.employee_Id=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.YearSettings_Id=@YearSettingId  Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment  
				  end  
		 END  
	else  
		begin  
		if(@LeaveType_Id=-1 and @leaveApplicationId=0)  
		BEGIN
			 Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as ''Number of Days''  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			 where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0  		and la.Status  not in (''Rejected'')
			 and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'')   
			 and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType  
			 union  
			 Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as ''Number of Days''  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (  
			 select LeaveType_Id from Ta_Tbl_LeaveApplication la  
			 inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id  
			 where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0   
			 and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and Status not in (''Rejected'') and ys.YearSettings_Id=@YearSettingId)  
			 and ys.YearSettings_Id=@YearSettingId    
		END
	else
		BEGIN
			Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)) as ''Number of Days''  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			 where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id 
			and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
			and LeaveApplication_Id<>@leaveApplicationId   
			 --and la.Status  in (''Pending'',''Forwarded'',''Approved'') 
			and la.Status  not in (''Rejected'')
			 and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'')   
			 and la.IsBorrow=0 Group by Yc.LeaveTypeId,yc.Carry_PrevYear,yc.Current_Quota,yc.Borrow_NextYear,yc.Encashment,lt.LeaveType_Id,lt.LeaveType  
			 union  
			 Select lt.LeaveType as ''Leave Type'',(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0)) - ISNULL(yc.Encashment,0.0) as ''Number of Days''  
			 from TA_tbl_Yearclosure yc  
			 inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id  
			 inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			 where yc.employee_Id=@Employee_Id and yc.LeaveTypeId not in (  
			 select LeaveType_Id from Ta_Tbl_LeaveApplication la  
			 inner join TA_Tbl_YearSetting ys on la.YearSettings_ID=ys.YearSettings_Id  
			 where Employee_Id=@Employee_Id and Isdeleted=0 and IsBorrow=0   
			 and Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and Status not in (''Rejected'') and ys.YearSettings_Id=@YearSettingId)  
			 and ys.YearSettings_Id=@YearSettingId 
		END
	 END  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetRemainingNumberOfBorrowLeaves 5 ,52
Description		:	Get Remaining Number Of Leaves Details of Employees Based on their Employee_Id and Leave Type Id
Tables Included	:	Ta_Tbl_LeaveApplication, TA_tbl_Yearclosure and TA_Tbl_YearSetting
Created By		:	Prabakaran
Created On		:	19-Feb-08
Modified By		:	
Modified On		:	
*/
CREATE    PROCEDURE [dbo].[Proc_TA_GetRemainingNumberOfBorrowLeaves]  
@Employee_Id int,
@LeaveType_Id int
AS
declare @LeaveApplicationCount as int
declare @NumberOfLeavesCount as float
declare @BorrowLeavesCount as float
declare @RemainingNoOfBorrowLeaves as float
BEGIN
SET NOCOUNT ON;
set @LeaveApplicationCount=(
select count(la.NumberOfDays) from Ta_Tbl_LeaveApplication la
inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id  
where ys.IsActive=1 and la.LeaveType_Id=@LeaveType_Id 
and la.Employee_Id=@Employee_Id 
and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'') 
and la.status not in(''Rejected'')  and la.isdeleted=0 and la.IsBorrow=1)
set @NumberOfLeavesCount=(
Select ISNULL(sum(la.NumberOfDays),0.0) as RemainingNoOfLeaves 
from TA_tbl_Yearclosure yc
inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id
inner join Ta_Tbl_LeaveApplication la on la.LeaveType_Id =yc.LeaveTypeId  and yc.employee_Id=la.Employee_id and ys.YearSettings_Id=la.YearSettings_Id
where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id
and yc.LeaveTypeId=@LeaveType_Id and la.LeaveType_Id=@LeaveType_Id 
and ys.IsActive=1 and la.Isdeleted=0 and la.Status in (''Pending'',''Forwarded'',''Approved'') 
and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') and la.IsBorrow=1 
)
set @BorrowLeavesCount=(select (lpd.MaxDays_applicable) as RemainingNoOfBorrowLeaves
from TA_Tbl_LeavePolicyDetails lpd
inner join TA_Tbl_Emp_LeavePolicy elp
on elp.LeavePolicy_Id=lpd.Policy_Id
inner join TA_Tbl_YearSetting  ys
on ys.YearSettings_Id=elp.YearSettingId
inner join TA_Tbl_YearClosure yc
on yc.Year_SettingId=ys.YearSettings_Id and yc.Employee_Id=elp.EmployeeId and yc.LeaveTypeID=lpd.LeaveType_Id
where elp.EmployeeId=@Employee_Id and yc.LeaveTypeId=@LeaveType_Id and ys.IsActive=1 and elp.Isdeleted=0)
if(@LeaveApplicationCount > 0)
begin
set @RemainingNoOfBorrowLeaves=@BorrowLeavesCount - @NumberOfLeavesCount
end
else
begin
set @RemainingNoOfBorrowLeaves=@BorrowLeavesCount
end
select @RemainingNoOfBorrowLeaves as RemainingNoOfBorrowLeaves
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_GetPermissionSanctionDetailsForSuperAdmin  ''20'',''Rejected'',''8/1/2008'',''9/30/2008''
Description		: Get Permission Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,  
Tables Included : TA_Tbl_Permission and TA_TBL_Employee  
Created By		: Prabakaran  
Created On		: 23-Jul-07  
Modified By		: Prabakaran  
Modified On		: 24-Jul-07  
Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler 3,''All'',''03/01/2014 12:00:00 AM'',''05/31/2014 12:00:00 AM'',0,'''','''','''',''SuperAdmin'',3
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin_Angler]  
	@LevelId varchar(2000),  
	@Status varchar(250) =null,  
	@Permission_FromDate datetime =null,  
	@Permission_ToDate datetime =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int 
as  
begin
	set nocount on;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery = ''select p.permission_reason, lv.name as levelname, P.Permission_Id,P.Permission_Status, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end AS Permission_AppliedDate	
	,(REPLACE(CONVERT(VARCHAR(11), p.Permission_FromTime, ''+cast(@dateFormat as varchar(100))+''), '''' '''', ''''-'''') + 
	'''' - '''' + REPLACE(CONVERT(VARCHAR(11), p.Permission_ToTime, ''+cast(@dateFormat as varchar(100))+''), '''' '''', ''''-'''')) AS Duration,
	p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName from TA_TBL_Employee E  ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_leveldetails lv on lv.Id=EL.levelID   ''  
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.levelID ''
	set @sqlQuery = @sqlQuery + '' where  E.Isdeleted=0 and P.IsDeleted=0 ''
	--and ys.IsActive=1''
	set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc)''
	If not(@strEmployeeCodeId = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		End
	If Not (@strSwipeCardNo = '''')  
		Begin  
			  Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' ''  
		End 
	If not(@strEmployeeName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + '''''')''
			--set @sqlQuery = @sqlQuery + '' and E.Employee_FirstName like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + ''''''''
		End
	if (lower(@Status)<>''all'' and isnull(@Status,'''')<>'''' )
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status  + ''''''))''
		End
	else if(@Status=''All'')
		begin		
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected'''',''''Resend'''',''''Reply'''')) ''
		end	
	if not(cast(@Permission_FromDate as nvarchar(11))='''' or cast(@Permission_FromDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date>=CONVERT(DATETIME, '''''' + cast(@Permission_FromDate as nvarchar(11)) + '''''', 102))''
		End
	if not(cast(@Permission_ToDate as nvarchar(11))='''' or cast(@Permission_ToDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date<=CONVERT(DATETIME, '''''' + cast(@Permission_ToDate as nvarchar(11)) + '''''', 102))''
		End
	exec(@sqlQuery + '' Order by Permission_Id,Year(P.Permission_AppliedDate) desc,Month(P.Permission_AppliedDate) desc,Day(P.Permission_AppliedDate) desc'')
	drop table #LevelRights
	end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_GetPermissionSanctionDetailsForSuperAdmin  ''20'',''Rejected'',''8/1/2008'',''9/30/2008''
Description		: Get Permission Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,  
Tables Included : TA_Tbl_Permission and TA_TBL_Employee  
Created By		: Prabakaran  
Created On		: 23-Jul-07  
Modified By		: Prabakaran  
Modified On		: 24-Jul-07  
Proc_TA_GetPermissionSanctionDetailsForSuperAdmin 1,1,''Pending'',''20200101'',''20200501'',0,'''','''','''',''SuperAdmin'',1,0,0
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetailsForSuperAdmin]  
	@Employee_ID int,
	@LevelId varchar(2000),  
	@Status varchar(20) =null,  
	@Permission_FromDate VARCHAR(30) =null,  
	@Permission_ToDate VARCHAR(30) =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int,
	@EmployeeCategory int, 
	@EmployeeType int
as  
 begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
    
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),
	ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(MAX)
	set @sqlQuery=''''
	set @sqlQuery = ''select E.Employee_Code_Id as employeeid,P.Permission_Id,P.Permission_Status, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end AS Permission_AppliedDate	
	,(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '''' '''', ''''/'''') + '''' - '''' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '''' '''', ''''/'''')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName from #TempPermissionDetails E  ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=EL.levelID ''
	set @sqlQuery = @sqlQuery + '' where  E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1''
	set @sqlQuery = @sqlQuery + '' and EL.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id and EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc)''
	If not(@strEmployeeCodeId = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If Not (@strSwipeCardNo = '''')  
		Begin  
			  Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' ''  
		End 
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
		end
	If not(@strEmployeeName = '''')
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@strEmployeeName+''%'' as nvarchar(100)) + '''''')''
		End
	
	if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((P.Permission_Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
				set @sqlQuery = @sqlQuery + '' or (P.Permission_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)+''))''
			end
	end
	else 
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((P.Permission_Status IN (''''Pending''''))''
				set @sqlQuery = @sqlQuery + '' or (P.Permission_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')))''
			end
	End
		
	--if (@Status=''Pending'' or @Status=''Rejected'' or @Status=''Forwarded'' or @Status=''Rejected'' or @Status=''Approved'')
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status  + ''''''))''
	--	End
	--else if(@Status=''All'')
	--	begin				
	--		set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected''''))''
	--	end	
	if(cast(@Permission_FromDate as nvarchar(11))!='''')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date>=CONVERT(DATETIME, '''''' + cast(@Permission_FromDate as nvarchar(11)) + '''''', 102))''
		End
	if (cast(@Permission_ToDate as nvarchar(11))!='''')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date<=CONVERT(DATETIME, '''''' + cast(@Permission_ToDate as nvarchar(11)) + '''''', 102))''
		End
	exec(@sqlQuery + '' Order by Permission_Id desc'')
	print(@sqlQuery + '' Order by Permission_Id desc'')
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
END	
---------------------------------------------------------------------------
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_employeelevel where employeeid=''10861''
--Proc_TA_GetPermissionSanctionDetails  ''10864'',1,''Forwarded'',''4/1/2011'',''3/31/2012'',0,'''','''','''',''Individual Users'',1
--Proc_TA_GetPermissionSanctionDetails  ''10863'',1,''All'',''4/1/2011'',''3/31/2012'',0,'''','''','''',''ReportingTo'',1
-- =============================================
-- Author			: Prabakaran.P
-- Modified date	: 13-Feb-2012
-- Modified by		: Manikandan.R   
--	Modified By		:	Manjula.P
--	Modified On		:	21-Apr-2014
--	Descriptions	:	Adding usergroup and parentId from PRODUCT development for ANGLER Migration 
--	Proc_TA_GetPermissionSanctionDetails 5,''3'',''Forwarded'',''03/01/2014 12:00:00 AM'',''05/31/2014 12:00:00 AM'',0,'''','''',''878'',''EIT - PMs'',3           
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails_Angler]  
	@Employee_Id int,  
	@LevelId varchar(2000),  
	@Status varchar(250) =null,  
	@Permission_FromDate datetime =null,  
	@Permission_ToDate datetime =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int   
as 
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @sqlQuery as nvarchar(max)
	declare @sqlQuery1 as nvarchar(max)
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @sqlQuery=''''
	set @sqlQuery1=''''
	set @sqlQuery = ''select p.permission_reason, lv.name as levelname,e.employee_code_id,P.Permission_Id,P.Permission_Status, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end AS Permission_AppliedDate,	
	(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '''' '''', ''''/'''') + '''' - '''' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '''' '''', ''''/'''')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,''''''''))as Employee_FirstName ''
	set @sqlQuery = @sqlQuery + '' from #TempPermissionDetails E  inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id inner join TA_Tbl_EmployeeLevel ELevel on ELevel.EmployeeId=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_leveldetails lv on lv.Id=ELevel.levelID   '' 
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=ELevel.levelID ''				
	set @sqlQuery = @sqlQuery + '' where'' 
	set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1 and ''
	set @sqlQuery = @sqlQuery + '' ELevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id AND EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc) '' 
	if(@strEmployeeCodeId!='''' and @strEmployeeCodeId is not null)
		begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		end
	if(@strEmployeeName!='''' and @strEmployeeName is not null)
		begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_FirstName = '''''' + cast(@strEmployeeName as nvarchar(50)) + ''''''''
		end				
	If Not (@strSwipeCardNo = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' ''  
		End 
	if not(cast(@Permission_FromDate as nvarchar(11))='''' or cast(@Permission_FromDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date>=CONVERT(DATETIME, '''''' + cast(@Permission_FromDate as nvarchar(11)) + '''''', 102))''
		End
	if not(cast(@Permission_ToDate as nvarchar(11))='''' or cast(@Permission_ToDate as nvarchar(11))=''0'')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date<=CONVERT(DATETIME, '''''' + cast(@Permission_ToDate as nvarchar(11)) + '''''', 102))''
		End	
	if @Status=''Pending'' or @Status=''Rejected'' or @Status=''Resend'' or @Status=''Reply''
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''		
		end
	else if(@Status=''Forwarded'' or @Status=''Approved'')
		begin			
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''	
			set @sqlQuery = @sqlQuery + '' and (E.LeaveSanction = '''''' + cast(@Employee_Id as nvarchar(50)) + '''''' or E.ReportTo = '''''' + cast(@Employee_Id as nvarchar(50)) + '''''') ''			
		end
	else if(lower(@Status)=''all'')		
		begin					
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected'''',''''Resend'''',''''Reply''''))''					end		
		exec(@sqlQuery)
	drop table #LevelRights' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPermissionSanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPermissionSanctionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_employeelevel where employeeid=''10861''
--Proc_TA_GetPermissionSanctionDetails  ''10864'',1,''Forwarded'',''4/1/2011'',''3/31/2012'',0,'''','''','''',''Individual Users'',1,0,0
--Proc_TA_GetPermissionSanctionDetails  ''5'',1,''All'','''','''',0,'''','''','''',''Second Level User'',1,0,0
-- =============================================
-- Author			: Prabakaran.P
-- Modified date	: 13-Feb-2012
-- Modified by		: Manikandan.R   
-- =============================================
CREATE   PROCEDURE [dbo].[Proc_TA_GetPermissionSanctionDetails]  
	@Employee_Id int,  
	@LevelId varchar(2000),  
	@Status varchar(20) =null,  
	@Permission_FromDate varchar(30) =null,  
	@Permission_ToDate varchar(30) =null,  
	@Isdeleted bit =0,
	@strSwipeCardNo varchar(15)=null,
	@strEmployeeName varchar(100)=null,
	@strEmployeeCodeId varchar(15)=null,
	@UserGroupName varchar(250),
	@ParentID int,
	@EmployeeCategory int, 
	@EmployeeType int
as 
	begin
	SET NOCOUNT ON;
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @sqlQuery as nvarchar(max)
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,LeaveSanction int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID     
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	set @sqlQuery=''''
	set @sqlQuery = ''select e.employee_code_id as employeeid,P.Permission_Id,P.Permission_Status, 
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, P.Permission_AppliedDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, P.Permission_AppliedDate, ''+cast(@dateFormat as varchar(100))+'') end AS Permission_AppliedDate,	
	(REPLACE(CONVERT(VARCHAR(9), p.Permission_FromTime, 6), '''' '''', ''''/'''') + '''' - '''' + REPLACE(CONVERT(VARCHAR(9), p.Permission_ToTime, 6), '''' '''', ''''/'''')) AS Duration,p.Permission_FromTime,p.Permission_ToTime,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,''''''''))as Employee_FirstName ''
	set @sqlQuery = @sqlQuery + '' from #TempPermissionDetails E  inner join TA_TBL_Permission P on  E.Employee_Id=P.Employee_Id inner join TA_Tbl_EmployeeLevel ELevel on ELevel.EmployeeId=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights on #LevelRights.LevelId=ELevel.levelID ''		
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''		
	set @sqlQuery = @sqlQuery + '' where'' 
	set @sqlQuery = @sqlQuery + '' E.Isdeleted=0 and P.IsDeleted=0 and ys.IsActive=1 and ''
	set @sqlQuery = @sqlQuery + '' ELevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where EmployeeId = E.Employee_Id AND EffectiveDate <=P.Permission_AppliedDate order by EffectiveDate desc) '' 
	if(@strEmployeeCodeId!='''' and @strEmployeeCodeId is not null)
		begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast(@strEmployeeCodeId as nvarchar(50)) + ''''''''
		end
	if(@strEmployeeName!='''' and @strEmployeeName is not null)
		begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_FirstName = '''''' + cast(@strEmployeeName as nvarchar(50)) + ''''''''
		end				
	If Not (@strSwipeCardNo = '''')  
		Begin  
			Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @strSwipeCardNo + '''''' ''  
		End 
	if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
		end
	if (cast(@Permission_FromDate as nvarchar(20))!='''')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date>=CONVERT(DATETIME, '''''' + cast(@Permission_FromDate as nvarchar(20)) + '''''', 102))''
		End
	if (cast(@Permission_ToDate as nvarchar(20))!='''')
		begin
			set @sqlQuery = @sqlQuery + '' and (P.Permission_Date<=CONVERT(DATETIME, '''''' + cast(@Permission_ToDate as nvarchar(20)) + '''''', 102))''
		End	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((P.Permission_Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
				set @sqlQuery = @sqlQuery + '' or (P.Permission_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and LeaveSanction=''+CONVERT(varchar(20),@Employee_Id)+''))''
			end
	end
	else 
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (P.Permission_Status IN ('''''' + @Status + ''''''))''
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((P.Permission_Status IN (''''Pending''''))''
				set @sqlQuery = @sqlQuery + '' or (P.Permission_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')))''
			end
	End
	set @sqlQuery = @sqlQuery + ''order by P.Permission_Id desc''	
		exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpType
	drop table #EmpCategory
	drop table #TempPermissionDetails
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetOnDutyEntrySanctionForUser ''41'',''1'',''Pending'','''','''',''0'',''0'',''01/01/2019'',''31/12/2019'',0,'''',''Project%20manager'',0
exec Proc_TA_GetOnDutyEntrySanctionForUser @Employee_Id='''',@LevelId=''5'',
@Status=''Approved,Pending,Forwarded,Rejected'',@EmployeeId='''',@EmployeeName='''',@EmployeeCategory=0,@EmployeeType=0,
@ManualEntry_FromDate=''01/07/2017'',
@ManualEntry_ToDate=''08/30/2017'',@Isdeleted=0,
@EmpSwipeCard='''',@UserGroupName=''Reporting To'',@ParentID=0
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForUser]
@Employee_Id int,
@LevelId varchar(2000),
@Status varchar(100) =null,
@EmployeeId varchar(100),
@EmployeeName varchar(50),  
@EmployeeCategory int, 
@EmployeeType int,
@ManualEntry_FromDate varchar(20)=null, 
@ManualEntry_ToDate varchar(20)=null,
@Isdeleted bit =0,
@EmpSwipeCard varchar(20),
@UserGroupName varchar(250),
@ParentID int    
as
begin
	SET NOCOUNT ON;
	if(substring(@ManualEntry_FromDate,1,5)=''01/01'' and substring(@ManualEntry_ToDate,1,5)=''31/12'')
	begin		
		set @ManualEntry_ToDate=substring(@ManualEntry_ToDate,4,2)+''/''+substring(@ManualEntry_ToDate,1,2)+''/''+
		substring(@ManualEntry_ToDate,7,4)
	end
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=TODATE from TA_Tbl_YearSetting where IsActive=1
	 declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
    --Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID  
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery = ''select OD.Onduty_ID,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_EntryDate, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_FromDate,OD.Onduty_FromTime,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_ToDate, 
	 OD.Onduty_ToTime,OD.OnDuty_Status,OD.Onduty_Reason,E.Leave_Sanc_Authority,''''0'''' as SelectedRecords  from #TempPermissionDetails E ''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
		set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
		set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and OD.IsDeleted=0''
		if not(@EmployeeName='''')
		begin
			set @sqlQuery = @sqlQuery + ''and E.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		end
		if(@EmployeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery +'' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
		end
		if(@EmployeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))
		end
		if not (@EmployeeId='''')
		begin
				set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
		end		
		 If Not (@EmpSwipeCard = '''')  
		Begin  
			  Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
		--if not(@Status is null or @Status='''' or @Status=''0'' or @Status=''All'')
		--begin
		--	set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status  + ''''''))''	
		--End
		if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
		begin
			if (@Status=''Pending'' or @Status=''Rejected'')
				begin
					set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
				end
			else if(@Status=''Forwarded'' or @Status=''Approved'')
				begin
					set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))and Leave_Sanc_Authority=''+CONVERT(varchar(20),@Employee_Id)	
				end	
			else if(@Status=''All'')		
				begin
					--print ''s''
					set @sqlQuery = @sqlQuery + '' and ((OD.Onduty_Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
					set @sqlQuery = @sqlQuery + '' or (OD.Onduty_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and Leave_Sanc_Authority=''+CONVERT(varchar(20),@Employee_Id)+''))''
				end
		end
		else 
		begin
			if (@Status=''Pending'' or @Status=''Rejected'')
				begin
					set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
				end
			else if(@Status=''Forwarded'' or @Status=''Approved'')
				begin
					set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''
				end	
			else if(@Status=''All'')		
				begin
					--print ''s''
					set @sqlQuery = @sqlQuery + '' and ((OD.Onduty_Status IN (''''Pending''''))''
					set @sqlQuery = @sqlQuery + '' or (OD.Onduty_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')))''
				end
		End
		
	--	if @Status=''Pending'' or @Status=''Rejected''
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
	--	end
	--else if(@Status=''Forwarded'' or @Status=''Approved'')
	--	begin
	--		--set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
	--		set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))and E.Leave_Sanc_Authority=''+CONVERT(varchar(20),@Employee_Id)	
	--		--set @sqlQuery = @sqlQuery + '' and E.LeaveSanction = '''''' + cast(@Employee_Id as nvarchar(50)) + ''''''''			
	--	end	
	--else if(@Status=''All'')		
	--	begin
	--		set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN (''''Pending'''',''''Forwarded'''',''''Approved'''',''''Rejected''''))''
	--	end
	--else 
	--begin
	--	set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN (select value from split('''''' + @Status  + '''''','''','''')))''
	--End	
		if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END	
		If(@ManualEntry_FromDate != '''' and @ManualEntry_ToDate != '''')  
			 Begin  
			  set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
				set @sqlQuery = @sqlQuery + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102)))''
			 End  
		Else
			 Begin  
			  set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
				set @sqlQuery = @sqlQuery + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)))''
			 End  
		set @sqlQuery = @sqlQuery + '' order by OD.Onduty_ID desc ''
		exec(@sqlQuery)
		drop table #LevelRights
		drop table #EmpLevel
		drop table #EmpType
		drop table #EmpCategory
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name  : Proc_TA_GetOnDutyEntrySanctionForSuperAdmin ''1'',''Pending'',''0'','''',0,0,'''','''',0,'''',''Sanctioner'',4
Proc_TA_GetOnDutyEntrySanctionForSuperAdmin 1,1,''Forwarded'','''','''',0,0,''2020/01/01'',''2020/03/31'',0,'''',''superadmin'',1
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: R.Karthikeyan 
Created On		: 14-Mar-2016
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionForSuperAdmin]    
	@Employee_ID int,
	@LevelId varchar(2000),    
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	select @Fromdate=FromDate from TA_Tbl_YearSetting where IsActive=1
	select @SuccessiveDays=NoOfSuccessiveDaysInYear from TA_Tbl_ShiftSettings where CompanyId=@LevelId
	select @ToDate=DATEADD(d,@SuccessiveDays,TODATE) from TA_Tbl_YearSetting where IsActive=1
	--Login person is reporting to / sanctioning to some one 
    --And Reporting to / sanctioning person is another person for login employee means, its loading login person data into his login itself
    --for approval. Due to this reason deletion added here.28-Feb-2020
    Delete from #EmployeeIds where EmpAutoId=@Employee_ID 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	Create Table #TempPermissionDetails(Employee_id int,Employee_firstname varchar(50),Employee_LastName varchar(50),ReportTo int,Leave_Sanc_Authority int,Employee_code_id varchar(30),IsDeleted bit,SwipeCardNo varchar(50))
	--Insert Into #TempPermissionDetails 
	--select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	--from ta_tbl_employee where Leave_Sanc_Authority=@Employee_Id or Reporting_To=@Employee_Id
	Insert Into #TempPermissionDetails 
	select employee_id,Employee_FirstName,employee_LastName,Reporting_To,Leave_Sanc_Authority,Employee_code_id,IsDeleted,SwipeCardNo 
	from ta_tbl_employee E
	inner join TA_Tbl_EmployeeLevel el ON E.Employee_Id = el.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=el.levelID
	where Isdeleted=0 and Employee_Status=1
	
	
		DECLARE @dateFormat as int
		set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
			declare @sqlQuery as nvarchar(Max)
			set @sqlQuery=''''
			set @sqlQuery = ''select OD.Onduty_ID,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_EntryDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_EntryDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_EntryDate, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_FromDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_FromDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_FromDate,OD.Onduty_FromTime,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, OD.Onduty_ToDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, OD.Onduty_ToDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS Onduty_ToDate, 
	 OD.Onduty_ToTime,OD.OnDuty_Status,OD.Onduty_Reason,''''0'''' as SelectedRecords  from TA_TBL_Employee E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
	set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and OD.IsDeleted=0''   
	--set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and MT.IsDeleted=0  and mt.IsOnDuty=1 and ys.IsActive=1''   
	declare @sqlQuery1 as nvarchar(Max)
	set @sqlQuery1=''''
	if not(@EmployeeName='''')
	begin
		set @sqlQuery1 = @sqlQuery1 + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery1 = @sqlQuery1 + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	If Not (@EmpSwipeCard = '''')  
	Begin  
		  Set @sqlQuery1 = @sqlQuery1 + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End 
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery1 = @sqlQuery1 +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery1 = @sqlQuery1 + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='''')
	begin
			set @sqlQuery1 = @sqlQuery1 + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
	end		
	if (@UserGroupName!=''Superadmin'' and @isReportingto!=0)
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))and Leave_Sanc_Authority=''+CONVERT(varchar(20),@Employee_Id)	
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((OD.Onduty_Status IN (''''Pending'''')and ReportTo=''+CONVERT(varchar(20),@Employee_Id)+'')''
				set @sqlQuery = @sqlQuery + '' or (OD.Onduty_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')and Leave_Sanc_Authority=''+CONVERT(varchar(20),@Employee_Id)+''))''
			end
	end
	else 
	begin
		if (@Status=''Pending'' or @Status=''Rejected'')
			begin
				set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''		
			end
		else if(@Status=''Forwarded'' or @Status=''Approved'')
			begin
				set @sqlQuery = @sqlQuery + '' and (OD.Onduty_Status IN ('''''' + @Status + ''''''))''
			end	
		else if(@Status=''All'')		
			begin
				--print ''s''
				set @sqlQuery = @sqlQuery + '' and ((OD.Onduty_Status IN (''''Pending''''))''
				set @sqlQuery = @sqlQuery + '' or (OD.Onduty_Status IN (''''Forwarded'''',''''Approved'''',''''Rejected'''')))''
			end
	End
	If (@ManualEntry_FromDate != '''' and @ManualEntry_ToDate != '''')  
		 Begin  
		  set @sqlQuery1 = @sqlQuery1 + '' AND (((CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
			set @sqlQuery1 = @sqlQuery1 + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@ManualEntry_FromDate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ManualEntry_ToDate as nvarchar(50))   + '''''', 102)))''
		 End  
	Else
		 Begin  
		  set @sqlQuery1 = @sqlQuery1 + '' AND (((CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
			set @sqlQuery1 = @sqlQuery1 + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)))''
		 End  
       set @sqlQuery1 = @sqlQuery1 + '' order by OD.Onduty_ID desc ''
	exec(@sqlQuery + '' '' + @sqlQuery1) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Procedure Name  : Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin ''3'',''Approved'',''804'','''',0,0,''2013/01/01'',''2013/10/28'',0,'''',''SuperAdmin'',3
    Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin ''3'',''All'','''','''',0,0,''4/1/2014'',
    ''3/31/2015'',0,'''',''SuperAdmin'',3
Description		: Get OnDuty Time Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,    
Tables Included : TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee    
Created By		: K.Gopinath   
Created On		: 31-Jan-2014    
    */    
CREATE   PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetailsForSuperAdmin]    
	@LevelId varchar(2000),    
	@Status varchar(50) =null,  
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null,    
	@ManualEntry_ToDate varchar(20) =null,    
	@Isdeleted bit = 0 ,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int  
AS  
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Level insert in Temporary table
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	--select * from #EmpCategory
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
		declare @sqlQuery as varchar(max)
		set @sqlQuery=''''
		set @sqlQuery = ''select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,
	case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_Date, ''+cast(@dateFormat as varchar(100))+'')
	end 
 AS ManualTimeEntry_Date, 
  case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, MT.shift_date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, MT.shift_date, ''+cast(@dateFormat as varchar(100))+'')
	end 
 AS shiftDate, 
 case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_InDate, ''+cast(@dateFormat as varchar(100))+'')
	end 
 AS ManualTimeEntry_InDate,MT.ManualTimeEntry_InTime,MT.ManualTimeEntry_InPunchType,
 case when ''+cast(@dateFormat as varchar(100))+''=106 then
	REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
	else CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate, ''+cast(@dateFormat as varchar(100))+'')
	end 
 AS ManualTimeEntry_OutDate, 
 MT.ManualTimeEntry_OutTime,MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,''''0'''' as SelectedRecords  from TA_TBL_Employee E ''
	set @sqlQuery = @sqlQuery + '' inner join TA_TBL_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and MT.IsDeleted=0  and mt.IsOnDuty=1 and ys.IsActive=1''   
	if not(@EmployeeName='''')
	begin
		set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	If Not (@EmpSwipeCard = '''')  
	Begin  
	  Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End 
	if(@EmployeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@EmployeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@EmployeeId='''')
	begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
	end		
	if not(@Status is null or @Status='''' or @Status=''0'' or @Status=''All'')
	begin
	set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Status IN ('''''' + @Status  + ''''''))''
	End
	if not(cast(@ManualEntry_FromDate as nvarchar(11))='''' or cast(@ManualEntry_FromDate as nvarchar(11))=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' and (( isnull(MT.ManualTimeEntry_InDate,''''''+cast(''1990/01/01'' as nvarchar(11))+'''''') between '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) +'''''' and '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) +'''''') ''
	End
	if not(cast(@ManualEntry_ToDate as nvarchar(11))='''' or cast(@ManualEntry_ToDate as nvarchar(11))=''0'')
	begin
		set @sqlQuery = @sqlQuery + '' or ( isnull(MT.ManualTimeEntry_OutDate,''''''+cast(''1990/01/01'' as nvarchar(11))+'''''') between  '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) +'''''' and '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) +'''''')) ''
	End
	   set @sqlQuery = @sqlQuery + '' order by MT.ManualTimeEntry_Date desc ''
	exec(@sqlQuery) 
	drop table #EmpLevel
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name	:	Proc_TA_GetOnDutyEntrySanctionDetails ''3'','''','''','''','''',''2'','''',''08/01/2008'',''05/31/2009'',0
Proc_TA_GetOnDutyEntrySanctionDetails ''361'',''3'',''All'','''','''',0,0,''04/01/2014'',''03/31/2015'',0,'''',''EIT - PMs'',3
Description		:	Get OnDuty Entry Sanction Details of Employees Based on their Level_Id ,Employee_Id ,etc..,
Tables Included		:	TA_Tbl_ManualTimeEntry,Ta_tbl_leveldetails and TA_TBL_Employee
Created By		:	Gopinath.K
Created On		:	31-Jan-2014
*/
CREATE  PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionDetails]
	@Employee_Id int,
	@LevelId varchar(2000),
	@Status varchar(50) =null,
	@EmployeeId varchar(100),
	@EmployeeName varchar(50),  
	@EmployeeCategory int, 
	@EmployeeType int,
	@ManualEntry_FromDate varchar(20)=null, 
	@ManualEntry_ToDate varchar(20)=null,
	@Isdeleted bit =0,
	@EmpSwipeCard varchar(20),
	@UserGroupName varchar(250),
	@ParentID int    
as
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery = ''select MT.ManualTimeEntry_Id,ld.name,E.Employee_Code_Id,(E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''')) as Employee_FirstName,
		case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_Date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_Date, 
	  case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, MT.shift_date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, MT.shift_date, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS shiftDate, 
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_InDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_InDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_InDate,MT.ManualTimeEntry_InTime,MT.ManualTimeEntry_InPunchType,
	 case when ''+cast(@dateFormat as varchar(100))+''=106 then
		REPLACE(CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
		else CONVERT(VARCHAR, MT.ManualTimeEntry_OutDate, ''+cast(@dateFormat as varchar(100))+'')
		end 
	 AS ManualTimeEntry_OutDate, 
	 MT.ManualTimeEntry_OutTime,MT.ManualTimeEntry_Status,MT.ManualTimeEntry_Reason,E.Leave_Sanc_Authority,''''0'''' as SelectedRecords  from TA_TBL_Employee E ''
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_ManualTimeEntry MT on  E.Employee_Code_Id=MT.ManualTimeEntry_Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
			set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
			set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
			set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=MT.YearSettings_Id ''
			set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and MT.IsDeleted=0 and MT.IsOnDuty=1 and ys.IsActive=1''
			if not(@EmployeeName='''')
			begin
				set @sqlQuery = @sqlQuery + ''and E.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
			end
			if(@EmployeeCategory<>0)
			begin
				set @sqlQuery = @sqlQuery +'' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
			end
			if(@EmployeeType<>0)
			begin
				set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8))
			end
			if not (@EmployeeId='''')
			begin
				set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''
			end		
			If Not (@EmpSwipeCard = '''')  
			Begin  
			  Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			End 
			if not(@Status is null or @Status='''' or @Status=''0'' or @Status=''All'')
			begin
				set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Status IN ('''''' + @Status  + ''''''))''	
			End
			set @sqlQuery = @sqlQuery + '' and (E.Leave_Sanc_Authority = '''''' + cast(@Employee_Id as nvarchar(50)) + '''''' or E.Reporting_To= '''''' + cast(@Employee_Id as nvarchar(50)) + '''''')''	
			if not(cast(@ManualEntry_FromDate as nvarchar(11))='''' or cast(@ManualEntry_FromDate as nvarchar(11))=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Date>=CONVERT(DATETIME, '''''' + cast(@ManualEntry_FromDate as nvarchar(11)) + '''''', 102))''
			End
			if not(cast(@ManualEntry_ToDate as nvarchar(11))='''' or cast(@ManualEntry_ToDate as nvarchar(11))=''0'')
			begin
				set @sqlQuery = @sqlQuery + '' and (MT.ManualTimeEntry_Date<=CONVERT(DATETIME, '''''' + cast(@ManualEntry_ToDate as nvarchar(11)) + '''''', 102))''
			End
			if not (@EmployeeId='''')
			begin
				set @sqlQuery = @sqlQuery + '' and (E.Leave_Sanc_Authority = '''''' + cast(@Employee_Id as nvarchar(50))  + '''''')''
			End
			set @sqlQuery = @sqlQuery + '' order by MT.ManualTimeEntry_Date desc ''
			exec(@sqlQuery)
			drop table #LevelRights
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
[Proc_TA_GetOnDutyEntrySanctionCountDetails] ''65'',''Project Manager''
*/
CREATE PROCEDURE [dbo].[Proc_TA_GetOnDutyEntrySanctionCountDetails]
@Employee_Id int,
@UserGroupName varchar(250)
as
begin
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId
	Declare @Fromdate datetime
	Declare @ToDate datetime
	Declare @SuccessiveDays int
	select @Fromdate=FromDate,@ToDate=TODATE  from TA_Tbl_YearSetting where IsActive=1	 
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
	/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
	/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	DECLARE @dateFormat as int
	set @dateFormat = (select DateFormat from Func_TA_GetDateTimeFormat())
	declare @sqlQuery as nvarchar(max)
	set @sqlQuery=''''
	set @sqlQuery = ''select count(case  when OD.Onduty_Status=''''Approved'''' and E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1  end)Approved,
                            count(case  when OD.Onduty_Status=''''Forwarded'''' and E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' then 1 end)Forwarded,
                            count(case  when OD.Onduty_Status=''''Pending''''  and (E.Reporting_To='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' or E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''') then 1  end)Pending  from TA_TBL_Employee E ''
		set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_OndutyEntry OD on  E.Employee_Code_Id=OD.Onduty_EmployeeID ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID ''
		set @sqlQuery = @sqlQuery + '' inner join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id '' 
		set @sqlQuery = @sqlQuery + '' where E.Isdeleted=0 and OD.IsDeleted=0''
	if(@Employee_Id!='''')
	begin
		set @sqlQuery = @sqlQuery + '' and (E.Reporting_To='''''' +cast(@Employee_Id as nvarchar(50))   + '''''' or E.Leave_Sanc_Authority='''''' +cast(@Employee_Id as nvarchar(50))   + '''''')''
	end
	set @sqlQuery = @sqlQuery + '' AND (((CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) or (CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102) between OD.Onduty_FromDate and OD.Onduty_ToDate) )''
	set @sqlQuery = @sqlQuery + '' or (OD.Onduty_FromDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)) or (OD.Onduty_ToDate between CONVERT(DATETIME, '''''' +cast(@Fromdate as nvarchar(50))   + '''''', 102) and CONVERT(DATETIME, '''''' +cast(@ToDate as nvarchar(50))   + '''''', 102)))''
	--print(@sqlQuery)
		exec(@sqlQuery)
		drop table #LevelRights
		drop table #EmpLevel
		drop table #EmpType
		drop table #EmpCategory
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetnotificationDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetnotificationDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:        Karthikeyan.R
-- Create date: 28-11-2016
-- Description:   Get Notification Details
-- Proc_TA_GetnotificationDetails 4,''IndividualUsers''
--Proc_TA_GetnotificationDetails 3,''IndividualUsers''
--Proc_TA_GetnotificationDetails 2,''IndividualUsers''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetnotificationDetails]
      -- Add the parameters for the stored procedure here
      @employeeID as int,
      @UserGroupName as nvarchar(100)
AS
BEGIN
     SET NOCOUNT ON;
	
	Declare @local_employeeID int
	Declare @local_UserGroupName nvarchar(100)
	set @local_employeeID =@employeeID
	set @local_UserGroupName =@UserGroupName
	
	Declare @Fromdate datetime
	Declare @Todate datetime
	select @Fromdate=FromDate,@Todate=ToDate from TA_Tbl_YearSetting where IsActive=1  
	
	declare @PendingLeave as int=0
	declare @ForwardLeave as int=0
	declare @PendingPermission as int=0
	declare @ForwardPermission as int=0
	declare @PendingOnduty as int=0
	declare @ForwardOnduty as int=0
	declare @totalNotification as int=0
	declare @today datetime =getdate()
	declare @IsReportto as int=0
	declare @IsSanctionto as int=0
	declare @isReportingto as int
	declare @isIndividualuser as int
	
	--Get the Top level ID
	Create Table #TempSanctionUser(Employee_id int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	create table #EmployeeIds(EmpAutoId int)
	
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,0) as LevelId
	select @IsReportto=Count(*) from TA_Tbl_Employee where Reporting_To=@local_employeeID and Employee_Status=1
	select @IsSanctionto=Count(*) from TA_Tbl_Employee where Leave_Sanc_Authority=@local_employeeID  and Employee_Status=1
	select @isReportingto=ReportsBasedOn,@isIndividualuser=IndividualUsers from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from  
	(
		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		from TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@today as nVARCHAR(50)), 102) and EL.LevelId is not null
	and (@isIndividualuser=0 or (@isIndividualuser>0 and el.EmployeeId=CAST(@local_employeeID as nvarchar(10))))
	
	Insert Into #EmployeeIds 
	select employee_id from ta_tbl_employee where (Leave_Sanc_Authority=@local_employeeID or Reporting_To=@local_employeeID)
	and Employee_Status=1
	Insert Into #TempSanctionUser select EmpAutoId from #EmployeeIds
	delete from #TempSanctionUser where Employee_id=@local_employeeID
	--select * from #TempSanctionUser
	
	--Get Pending Leave
	Select @PendingLeave=COUNT(case when Status=''Pending'' then 1 end),
	@ForwardLeave=COUNT(case when Status=''Forwarded'' then 1 end)	
	from TA_Tbl_LeaveApplication L 
	inner join TA_Tbl_EmployeeLevel EL ON L.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=L.YearSettings_Id 
	inner join #TempSanctionUser su on su.Employee_id=L.Employee_Id  
	where L.IsDeleted=0 and ys.IsActive=1
	and (Leave_FromDate>=@Fromdate and Leave_ToDate<=@Todate)
	
	--Get Pending Permission 
	Select @PendingPermission=COUNT(case when Permission_Status=''Pending'' then 1 end) ,
	@ForwardPermission=COUNT(case when Permission_Status=''Forwarded'' then 1 end)
	from TA_Tbl_Permission P 
	inner join TA_Tbl_EmployeeLevel EL ON P.Employee_Id = EL.EmployeeId 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=P.YearSettings_Id 
	inner join #TempSanctionUser su on su.Employee_id=P.Employee_Id 
	where P.IsDeleted=0 and ys.IsActive=1
	and (Permission_Date>=@Fromdate and Permission_Date<=@Todate)
	
	--Get Pending Onduty
	select @PendingOnduty=COUNT(case when Onduty_Status=''Pending'' then M.Onduty_ID end) ,
	@ForwardOnduty=COUNT(case when Onduty_Status=''Forwarded'' then M.Onduty_ID end)	
	from ta_tbl_manualtimeentry M 
	inner join TA_Tbl_OndutyEntry OD on OD.Onduty_ID=M.Onduty_ID and OD.isDeleted=0 
	inner join TA_Tbl_Employee E on OD.Onduty_EmployeeID=E.Employee_Code_Id  
	inner join TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId 
	inner join #TempSanctionUser su on su.Employee_id=E.Employee_Id 
	inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=M.YearSettings_Id 
	where OD.Isdeleted=0 and ys.IsActive=1
	and IsOnDuty=1 and (Onduty_FromDate>=@Fromdate and Onduty_ToDate<=@Todate)
		
	set @totalNotification = (isnull(@PendingLeave,0) + isnull(@ForwardLeave,0) + isnull(@PendingPermission,0) + isnull(@ForwardPermission,0) + isnull(@PendingOnduty,0)  + isnull(@ForwardOnduty,0))
	
	select isnull(@PendingLeave,0) as ''PendingLeave'',
	isnull(@ForwardLeave,0) as ''ForwardLeave'',
	isnull(@PendingPermission,0) as ''PendingPermission'',
	isnull(@ForwardPermission,0) as ''ForwardPermission'',
	isnull(@PendingOnduty,0) as ''PendingOnduty'',
	isnull(@ForwardOnduty,0) as ''ForwardOnduty'', 
	isnull(@totalNotification,0) as ''TotalNotification'',
	0 as ''LevelID'','''' as ''FromDate'',
	'''' as ''ToDate'',isnull(@IsReportto,0) as ''IsReportingto'',
	isnull(@IsSanctionto,0) as ''IsSanctionto''
	drop table #EmpLevel
	drop table #LevelRights
	drop table #TempSanctionUser
	drop table #EmployeeIds	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetMyCalendarTeamData]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetMyCalendarTeamData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.R>
-- Create date: <11-May-2017>
-- Description:	<Description,,>
-- Proc_TA_GetMyCalendarTeamData 1,''SuperAdmin''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetMyCalendarTeamData]
	-- Add the parameters for the stored procedure here
	@EmployeeID as int,
	@UserGroupName as nvarchar(100)
AS
BEGIN
		-- SET NOCOUNT ON added to prevent extra result sets from
		-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @EmplCode as nvarchar(100)
	declare @isReportingto as int
	declare @isindividual as int
	declare @todat datetime
	declare @TotalEmployeeCount as int
	set @todat=GETDATE()
	select @isReportingto=ReportsBasedOn,@isindividual=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName
	select @EmplCode=Employee_Code_ID from TA_Tbl_Employee where Employee_Id=@EmployeeID
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #LevelRights(LevelId INT)
	create table #TempMyCalendar(id int identity(1,1), Date nvarchar(20),Details nvarchar(Max))
	create table #EmployeeIds(EmpAutoId int)
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmployeeID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmployeeID) as EmpAutoId
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,'''',0  
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,0) as LevelId 
	--select * from #EmployeeIds
	--select * from #EmpDesignation
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	SET @sqlEmpLevel=
	''INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from  (
	SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId WHERE emp.Isdeleted=0 and emp.Report_Exclude=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(getdate() as nVARCHAR(50))+'''''', 102) and EL.LevelId is not null''                
	EXECUTE(@sqlEmpLevel)
	if(@isReportingto > 0 or @isindividual>0)
		begin
			set @TotalEmployeeCount=(select COUNT(distinct(EmpAutoId)) from #EmployeeIds)
		end
	else
		begin
			set @TotalEmployeeCount=(select COUNT(distinct(Employee_Code_Id)) from #EmpLevel)
		end
	declare @SQLQuery as nvarchar(Max)
	set @SQLQuery=''''
	SET @sqlQuery = @sqlQuery + '' 
	select CONVERT(VARCHAR(10),P.Date, 126), 
	''''P - '''' + cast(SUM(CASE P.FNAttendanceCode WHEN ''''Present'''' THEN 1 Else 0 END) as nvarchar(30)) + '''' / '''' + cast(SUM( CASE P.ANAttendanceCode WHEN ''''Present'''' THEN 1 else 0 END) as nvarchar(30)) + '''','''' + 
	''''A - '''' + cast(SUM(CASE P.FNAttendanceCode WHEN ''''Absent'''' THEN 1 else 0 END) as nvarchar(30)) + '''' / '''' + cast(SUM( CASE P.ANAttendanceCode WHEN ''''Absent'''' THEN 1 else 0 END) as nvarchar(30)) + '''','''' + 
	''''L - '''' + cast(SUM(CASE WHEN P.FNAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''') THEN 1 else 0 END) as nvarchar(30)) + '''' / '''' + cast(SUM( CASE WHEN P.ANAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''') THEN 1 else 0 END)  as nvarchar(30)) + '''',''''  + 	
	''''W - '''' + cast(SUM(CASE P.FNAttendanceCode WHEN ''''Weekly Off'''' THEN 1 else 0 END) as nvarchar(30)) + '''' / '''' + cast(SUM( CASE P.ANAttendanceCode WHEN ''''Weekly Off'''' THEN 1 else 0 END) as nvarchar(30)) + '''','''' + 
	''''H - '''' + cast(SUM(CASE P.FNAttendanceCode WHEN ''''Holiday'''' THEN 1 else 0 END) as nvarchar(30)) + '''' / '''' + cast(SUM( CASE P.ANAttendanceCode WHEN ''''Holiday'''' THEN 1 else 0 END) as nvarchar(30)) + '''',''''	from ta_tbl_processeddata P 
	inner join ta_tbl_Employee E on E.Swipecardno=P.Employee_Code_ID and E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_status=1 ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id ''
    SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
	 if(@isReportingto > 0 or @isindividual>0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' Where (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	set @sqlQuery = @sqlQuery + '' and P.Date>=(select FromDate from TA_Tbl_YearSetting where IsActive=1)''
	--if(@isReportingto > 0)
 --           BEGIN
 --              set @sqlQuery = @sqlQuery + '' Where (E.Employee_ID IN (select * from #EmployeeIds)) ''  
 --           END
	--SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeIds ON #EmployeeIds.EmpAutoId=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' Group by P.Date''
	insert into #TempMyCalendar
	EXECUTE(@SQLQuery)
	--select * from #TempMyCalendar
		declare @couDate int
		select @couDate=COUNT(*) from #TempMyCalendar
		declare @i int
		set @i=1
		declare @OutputString nvarchar(Max)
		set @OutputString=''''
		while @i<=@couDate
		Begin
			DECLARE @StrValue AS NVARCHAR(Max)
			DECLARE @Date  AS NVARCHAR(25)
			select @Date= Date,@StrValue=Details from #TempMyCalendar where id=@i
			set @OutputString = @OutputString + @Date + '','' + @StrValue + ''%'' 
			set @i=@i+1
		END
		SET @OutputString = SUBSTRING(@OutputString, 0, LEN(@OutputString))
		select @OutputString + ''~'' + CAST(@TotalEmployeeCount as nvarchar(20)) as ''MyCalendarOutput''
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_getRawData]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_getRawData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Karthikeyan.R,,Proc_TA_getRawData>
-- Create date: <28-07-2015,,>
-- Proc_TA_getRawData ''2015/09/01'',''2015/09/11'',''101,'',''karthikeyan'',''SuperAdmin'',0,1,0,0,''Both''
-- Description:	<In the procedure used to get the TimeCard Entry for the Bonus Time Entry,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_getRawData]
(
@FromDate varchar(20),
@ToDate varchar(20),
@EmployeeId varchar(max),
@EmployeeName varchar(max),
@UserGroupName varchar(250),
@DesignationID int,
@employeeCategory int,
@employeeType int,
@ParentID int,
@Gender varchar(10)	
)
	-- Add the parameters for the stored procedure here
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
		if(@EmployeeId is not null and @EmployeeId <> '''')
			begin
				create table #EmployeeID(EmployeeID varchar(25))
				insert into #EmployeeID
				select * from SplitupEmployeeCode(@EmployeeId)
			end	
		if(@EmployeeName is not null and @EmployeeName <> '''')
			begin
				create table #EmployeeName(EmployeeID varchar(25))
				insert into #EmployeeName
				select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
			end	
		--create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
		create table #LevelRights(LevelId int)
		insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
		--Employee Level Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type Indexes
		/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
		/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
		--Employee Type insert in Temporary table
		insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,@DesignationID	
		insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
		insert into #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
		declare @sqlEmpLevel nvarchar(Max)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select * from #LevelRights
		set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.SwipeCardNo ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.SwipeCardNo ''
		End
	Execute(@sqlEmpLevel)
		--select * from #EmpDesignation
		--select * from #EmpCategory
		--select * from #EmpType
		--select * from #EmpLevel
		--select CAST(Emp_ID as int) from TA_Tbl_Employee
		--select * from #EmployeeID
		--select * from #EmployeeName
		--select * from Ta_Tbl_levelDetails
		declare @sqlQuery as nvarchar(max)
		set @sqlQuery=''''
		set @sqlQuery=''select RD.CLK_CARDID as ''''Employee_Code_Id'''',Emp.Employee_FirstName + '''' '''' + Emp.Employee_LastName as EmployeeName,
Ter.Terminal_Name,CONVERT(nvarchar(20),RD.CLK_DATE, ''+ convert(varchar,@dateFormat) +'') as ShiftDate,CONVERT(nvarchar(20),RD.CLK_DATE, ''+ convert(varchar,@dateFormat) +'') as PunchDate,RD.CLK_TIME as PunchTime,PY.PunchType,RD.*,ld.Name as LevelName,CAST(''''01-01-1900 '''' + RD.CLK_Time as datetime) as OrderTime, case when ReasonId=''''0'''' then ''''Processed'''' else case when ReasonId=''''1'''' then ''''Employee is not defined in timecheck'''' else case when ReasonId=''''2'''' then ''''Terminal is not created in timecheck application or this device is not used in any entrance master'''' else case when ReasonId=''''3'''' then ''''Shift is not allocated for this date'''' else ''''Punch types is not defined for this device'''' end end end end  as Process
from TA_Tbl_Clk_RawData RD left join TA_Tbl_Employee Emp on Emp.Employee_Code_Id=RD.CLK_CARDID  ''
		set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Terminal Ter on Ter.Terminal_ReaderID=RD.CLK_DEVICEID ''
		set @sqlQuery = @sqlQuery + '' left join TA_Tbl_PunchTypes PY on PY.Terminal_Id=Ter.Terminal_Id and RD.CLK_DEVICEID=Ter.Terminal_ReaderID and RD.CLK_TYPE=PY.Value ''
		if(@ParentID=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
				set @sqlQuery = @sqlQuery + '' left join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = Emp.Employee_Id''
				set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.levelID''
			end
		if(@employeeType=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EmployeeId = Emp.Employee_Id''
			end
		if(@DesignationID=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = Emp.Employee_Id''
			end
		if(@employeeCategory=0)
			begin
				set @sqlQuery = @sqlQuery + '' left join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
			end
		else
			begin
				set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = Emp.Employee_Id ''
			end
		If Not (@EmployeeId = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=#EmpLevel.SwipeCard ''
		End
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=#EmpLevel.SwipeCard ''
		End
		set @sqlQuery = @sqlQuery + '' left join Ta_tbl_leveldetails ld on  #EmpLevel.LevelId=ld.id where RD.CLK_DATE >=''''''+ @FromDate +'''''' and RD.CLK_DATE <='''''' + @ToDate +''''''''
		if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and Emp.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		set @sqlQuery = @sqlQuery +''Order by RD.CLK_DATE,OrderTime desc''
		exec(@sqlQuery)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetQuotaDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetQuotaDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Proc_TA_GetQuotaDetails 34,1
*/  
CREATE PROCEDURE [dbo].[Proc_TA_GetQuotaDetails]  
@EmpID as int,  
@LeaveTypeID as int  
AS  
BEGIN  
declare @LeaveApplicationCount as int
set @LeaveApplicationCount=(select count(*) from Ta_Tbl_LeaveApplication la
					inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=la.YearSettings_Id 
					where ys.IsActive=1 and la.LeaveType_Id=@LeaveTypeId and la.Employee_Id=@EmpID 
and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'',''LOP'') 
and la.status not in(''Rejected'')  and la.isdeleted=0 and la.IsBorrow=0)
if(@LeaveApplicationCount > 0)
begin
			 select yc.Current_Quota,lt.LeaveType,sum(isnull(la.NumberOfDays,0)) as Leave_Taken  from ta_tbl_LeaveApplication la  
			 inner join ta_tbl_leavetype lt on la.leavetype_id = lt.LeaveType_ID  
			 inner join ta_tbl_yearclosure yc on yc.Employee_Id=la.Employee_Id and yc.Year_SettingId=la.YearSettings_Id
			and yc.leavetypeid=la.leavetype_id
			 where la.employee_id=@EmpID and la.leavetype_id=@LeaveTypeID and la.Type=''Leave'' and la.Status<>''Rejected''
			and la.IsDeleted=0  and la.IsBorrow=0 and
			  la.yearsettings_ID= (select yearsettings_ID from ta_tbl_yearsetting where isactive=1)  
			group by yc.Current_Quota,lt.LeaveType
end
else 
		begin
		 select Current_Quota,ta_tbl_leavetype.LeaveType,Leave_Taken  from ta_tbl_yearclosure   
 inner join ta_tbl_leavetype on ta_tbl_yearclosure.leavetypeid = ta_tbl_leavetype.LeaveType_ID  
 where ta_tbl_yearclosure.employee_id=@EmpID and ta_tbl_yearclosure.leavetypeid=@LeaveTypeID and  
  ta_tbl_yearclosure.year_settingID= (select yearsettings_ID from ta_tbl_yearsetting where isactive=1) 
		end
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckPermanentDelete]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckPermanentDelete]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==============================================================
-- Author:		Manikandan.R
-- Create date: 11-June-2012
-- Description:	Checking Whether it is used or not in Designation
-- ==============================================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckPermanentDelete]
(
	@Grade varchar(200)
)	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	Select count(*) from ta_tbl_Title where GradeID in(@Grade) And Isdeleted=0
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckMonthClosureProcessFlag]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckMonthClosureProcessFlag]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckMonthClosureProcessFlag  
Description : check month closure process flag   
Tables Included : TA_Tbl_MonthClosure  
Created By : Kumuthini.L  
Created On : 05-Aug-2007 
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckMonthClosureProcessFlag]
 (
    @MonthClosureId int
 )
AS
BEGIN
   Select MonthClosure_Id from TA_Tbl_MonthClosure where Process = ''P'' and MonthClosure_Id = @MonthClosureId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckLeavePolicyDatesExists]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckLeavePolicyDatesExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Procedure Name : Proc_TA_CheckLeavePolicyDatesExists  60010,''2008-12-01 00:00:00.000'',''2008-12-31 00:00:00.000''
Description  :    Tables Included : TA_Tbl_LeavePolicyDetails,TA_TBL_Emp_LeavePolicy and TA_Tbl_Employee    
Created By  : Prabakaran    
Created On  : 10-Aug-07    
Modified By  :    
Modified On  :    */    
-- Proc_TA_CheckLeavePolicyDatesExists 10899,''20120408'',''20120408'',58
CREATE    PROCEDURE [dbo].[Proc_TA_CheckLeavePolicyDatesExists]    
@Employee_Id bigint,    
@FromDate datetime,
@ToDate datetime,
@LevelId int     
AS  
begin  
	SET NOCOUNT ON;
	declare @test as decimal    
	declare @Result as varchar(10)
	Declare @LevelId1 int
	declare @SuceesiveFromDate datetime
	declare @SuceesiveToDate datetime
	select @LevelId1= LevelId from ta_tbl_employeeLevel where employeeId=@Employee_Id
	while((select Id from TA_tbl_LevelDetails where id=@LevelId1) <> '''') 
		BEGIN
			if((select levelID from TA_tbl_LevelDetails where Id=@LevelId1) <> 1)
				begin
					set @LevelId1 = (select parentId from TA_tbl_LevelDetails where id=@LevelId1) 
				end
			else
				begin
					break
				end
		ENd
	set @LevelId=@LevelId1
	Declare @Successivedays int
	if exists( select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@LevelId)
		begin
			set @Successivedays=(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@LevelId)
		end
	else
		begin
			set @Successivedays=(select NoofsuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=-1)
		end
	-- select ToDate from ta_tbl_YearSetting where Isactive=1
	select @SuceesiveFromDate = ToDate from ta_tbl_YearSetting where Isactive=1
	select @SuceesiveToDate = dateadd(day,@Successivedays,ToDate) from ta_tbl_YearSetting where Isactive=1 
	if(@SuceesiveToDate < @FromDate or @SuceesiveToDate < @ToDate)
		begin
			select ''2'' as PolicyCount
		end
	else if ( (@FromDate > @SuceesiveFromDate and @FromDate <= @SuceesiveToDate) and (@ToDate > @SuceesiveFromDate and @ToDate <= @SuceesiveToDate) )
			begin	
				create table #LevelRights(LevelId int)
				insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](''SuperAdmin'',@LevelId) as LevelId
				if exists( select * from #LevelRights LR inner join ta_tbl_EmployeeLevel EL on LR.LevelId=EL.Levelid where EL.EmployeeId=@Employee_Id)
					begin
						create table #TempLeavePolicy(EmployeeId int,fromdate datetime,ToDate datetime,YearSettingsId int)
						insert into #TempLeavePolicy
						select empl.Employeeid,empl.FromDate,dateadd(day,@Successivedays,empl.ToDate) as ToDate,empl.YearSettingId from ta_tbl_emp_leavepolicy empl inner join ta_tbl_yearsetting ys on empl.YearSettingId=ys.YearSettings_Id 
						where empl.employeeId=@Employee_Id and ys.IsActive=1
						select 1 as PolicyCount
						drop table #TempLeavePolicy
					end
				else
					begin
						select ''0'' as PolicyCount
					end
			end
	else
		begin
			select count(empl.EmployeeId) as PolicyCount from ta_tbl_emp_leavepolicy empl
			inner join ta_tbl_yearsetting ys on empl.YearSettingId=ys.YearSettings_Id
			where empl.EmployeeId=@Employee_Id 
			and (@FromDate between empl.FromDate and empl.ToDate) and (@ToDate between empl.FromDate and empl.ToDate)
			and ys.IsActive=1
		end
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayBasedOnLevel]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayBasedOnLevel]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		sashma
-- Create date: 07-Jul-2011
-- Description:	checks holiday based on organization in windows service.
--Modified by Manikandan.R on 12-11-2015 11:51 AM
--Commented existing coding and added new codings. --Flexible
-- =============================================
--Proc_TA_CheckHolidayBasedOnLevel ''2019-08-02 00:00:00.000'',''2019-08-02 00:00:00.000'',''G'',5
CREATE PROCEDURE [dbo].[Proc_TA_CheckHolidayBasedOnLevel]
(
 @FromDate datetime,
 @ToDate datetime,
 @HolidayType varchar(5),
 @EmployeeAutoId bigint
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @HolidayLevelId int
	CREATE TABLE #TempHoliday(LevelIds int)
	DECLARE @EmployeeLeveld int
	insert into #TempHoliday
	Select HC.LevelId from TA_tbl_Holiday H inner join TA_Tbl_HolidayChildTable HC
	on H.Holiday_Id=HC.Holiday_Id
	where	Holiday_FromDate <= @ToDate and Holiday_ToDate >= @FromDate and 
			Holiday_Type = @HolidayType and H.IsDeleted = 0	
	select @EmployeeLeveld=EL.LevelId from TA_Tbl_EmployeeLevel EL inner join TA_Tbl_Employee E 
	on E.Employee_Id=EL.EmployeeId where E.Isdeleted=0 and E.Employee_Id=@EmployeeAutoId and EffectiveDate<=@FromDate
	IF EXISTS(SELECT * FROM #TempHoliday WHERE LevelIds=@EmployeeLeveld)
	BEGIN 
				SELECT 1 as HolidayId, '''' as HolidayDesc
	END
	Else
	Begin
			SELECT 0 as HolidayId, '''' as HolidayDesc
	End

END


' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidayForService]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidayForService]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- AUTHOR:		SASHMA
-- CREATE DATE: 07-JUL-2011
-- DESCRIPTION:	CHECKS HOLIDAY BASED ON ORGANIZATION IN WINDOWS SERVICE.  -- Nonflexible
-- =============================================
--Proc_TA_CheckHolidayForService ''2019-08-02'',''G'',93
CREATE PROCEDURE  [dbo].[Proc_TA_CheckHolidayForService]   
(
 @FROMDATE DATETIME,
 --@TODATE DATETIME,
 @HOLIDAYTYPE VARCHAR(5),
 @EMPLOYEEAUTOID BIGINT
)
AS
BEGIN
	SET NOCOUNT ON;
    DECLARE @HOLIDAYLEVELID INT
    DECLARE @employeelevelid INT
	SET @HOLIDAYLEVELID = -1
	select  @employeelevelid = EL.levelId from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 and emp.Employee_Id=@EMPLOYEEAUTOID group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@FROMDATE as nvarchar(50)), 102) and EL.LevelId is not null
	
	if not exists(SELECT hct.LevelId FROM TA_TBL_HOLIDAY 
	inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
	WHERE HOLIDAY_FROMDATE <= @FROMDATE
			AND HOLIDAY_TODATE >= @FROMDATE AND HOLIDAY_TYPE = ''G'' AND ISDELETED = 0 and hct.LevelId=@employeelevelid)
		begin

			SET @HOLIDAYLEVELID = (SELECT top 1 hct.LevelId FROM TA_TBL_HOLIDAY 
			inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
			WHERE HOLIDAY_FROMDATE <= @FROMDATE
			AND HOLIDAY_TODATE >= @FROMDATE AND HOLIDAY_TYPE = ''G'' AND ISDELETED = 0)		
		end
	else
		begin
		
			set @HOLIDAYLEVELID=@employeelevelid
		end
	IF((@HOLIDAYLEVELID <> '''') OR (@HOLIDAYLEVELID IS NOT NULL))
		BEGIN

			CREATE TABLE #LEVELRIGHTS(LEVELID INT)
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](''SUPERADMIN'',@HOLIDAYLEVELID) AS LEVELID
			DECLARE @HOLIDAYID INT
			DECLARE @HOLIDAYDesc varchar(500)

			SELECT TOP 1 @HOLIDAYID =  H.HOLIDAY_ID, @HOLIDAYDesc = Holiday_Description 
			FROM TA_TBL_EMPLOYEELEVEL EL
			INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId			
			WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID			
			AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			AND H.HOLIDAY_TODATE >= @FROMDATE)			
			AND H.HOLIDAY_TYPE = ''G'' AND H.ISDELETED = 0 
			and hct.LevelId=@HOLIDAYLEVELID

			--SET @HOLIDAYID = (SELECT TOP 1 H.HOLIDAY_ID FROM TA_TBL_EMPLOYEELEVEL EL
			--INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			--INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			--inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId
			--WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			--AND H.HOLIDAY_TODATE >= @FROMDATE) AND H.HOLIDAY_TYPE = ''G'' AND H.ISDELETED = 0 and hct.LevelId=@HOLIDAYLEVELID)


			--SET @HOLIDAYDesc = (SELECT TOP 1 H.Holiday_Description FROM TA_TBL_EMPLOYEELEVEL EL
			--INNER JOIN #LEVELRIGHTS ON (#LEVELRIGHTS.LEVELID = EL.LEVELID)
			--INNER JOIN TA_TBL_HOLIDAY H ON 1=1
			--inner join TA_Tbl_HolidayChildTable hct on h.Holiday_Id=hct.Holiday_Id and #LEVELRIGHTS.LEVELID=hct.LevelId
			--WHERE EL.EMPLOYEEID = @EMPLOYEEAUTOID AND (H.HOLIDAY_FROMDATE <= @FROMDATE 
			--AND H.HOLIDAY_TODATE >= @FROMDATE) AND H.HOLIDAY_TYPE = ''G'' AND H.ISDELETED = 0 and hct.LevelId=@HOLIDAYLEVELID)

			IF((@HOLIDAYID <> '''') OR (@HOLIDAYID IS NOT NULL))
				BEGIN
		
					SELECT @HOLIDAYID as holidayId, @HOLIDAYDesc as HolidayDesc
				END
			ELSE
				BEGIN
					SELECT 0 as holidayId, '''' as HolidayDesc
				END
			DROP TABLE #LEVELRIGHTS
		END
	ELSE
		BEGIN
			SELECT 0 as holidayId, '''' as HolidayDesc
		END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_SelectWeekday]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_SelectWeekday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--	Proc_SelectWeekday ''superadmin'',1,'''',''''
--	Modified By		:	Manjula.P
--	Modified On		:	09-Apr-2014
--	DEscriptinos	:	Adding @ParentId,@FromDate,@ToDate parameters for Searching purpose in temp weekday
CREATE   PROCEDURE [dbo].[Proc_SelectWeekday]
	@userGroupName nvarchar(50),
	@ParentId int=0,
	@FromDate varchar(20)=''01/01/1900'',
	@ToDate varchar(20)=''01/01/9999''
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	declare @SQLQuery as nvarchar(max);
	declare @LevelIds as varchar(250)
	create table #Temp
	(
	LevelId varchar(250)
	)
	insert into #Temp
	select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId  
	select @LevelIds=  COALESCE(@LevelIds + '','', '''') + LevelId FROM #Temp;
	--select * from #Temp
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)
	declare @Query nvarchar(max);
	--Added by Manjula.P on 09-Apr-2014 for levelwise and Date wise Search
	declare @WhereQuery nvarchar(500)
	declare @OrderByQuery nvarchar(max)
	set @Query='''';
	set @WhereQuery='''';
	--SET @LevelIds=@ParentId
	--********************************************************************
	set @dateFormat=(select DateFormat from Func_TA_GetDateTimeFormat())
	if(@userGroupName=''SuperAdmin'')
		begin
			if(@ParentId<=0)
			begin	
				set @Query='' SELECT T.tempWeekday_Id,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'''' '''',''''-'''') 			
				else CONVERT(VARCHAR, tempWeekday_FromDate, ''+cast(@dateFormat as varchar(100))+'') end as TempWeekday_FromDate,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, ''+cast(@dateFormat as varchar(100))+'') end 			
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id ''				
				set @WhereQuery='' where LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''','''')) ''
				set @OrderByQuery='' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted ''
			end
			else
			begin
				set @Query='' SELECT T.tempWeekday_Id,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'''' '''',''''-'''') 			
				else CONVERT(VARCHAR, tempWeekday_FromDate, ''+cast(@dateFormat as varchar(100))+'') end as TempWeekday_FromDate,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, ''+cast(@dateFormat as varchar(100))+'') end 			
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted FROM TA_Tbl_TemWeekday T
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id ''
				set @WhereQuery='' where LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''','''')) ''
				set @OrderByQuery='' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted ''
			end			
		end
	else
		begin
			if(@ParentId<=0)
			begin
				set @Query ='' SELECT T.tempWeekday_Id,case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_FromDate, ''+cast(@dateFormat as varchar(100))+'') end as TempWeekday_FromDate,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, ''+cast(@dateFormat as varchar(100))+'') end
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id ''				
				set @WhereQuery='' where IsDeleted = 0 and LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''',''''))''	
				set @OrderByQuery='' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted ''
			end
			else
			begin
				set @Query='' SELECT T.tempWeekday_Id,case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_FromDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_FromDate, ''+cast(@dateFormat as varchar(100))+'') end as TempWeekday_FromDate,
				case when ''+cast(@dateFormat as varchar(100))+''=106 then			
				REPLACE(CONVERT(VARCHAR, tempWeekday_ToDate,106),'''' '''',''''-'''') 
				else CONVERT(VARCHAR, tempWeekday_ToDate, ''+cast(@dateFormat as varchar(100))+'') end
				as TempWeekday_ToDate,ClosingTime,Reason,case when IsDeleted=1 then ''''True'''' else ''''False'''' end IsDeleted FROM TA_Tbl_TemWeekday T 
				inner join Ta_Tbl_Temporary_WeeklyOff_Levels TL on T.TempWeekday_Id=TL.TempWeekday_Id ''
				set @WhereQuery='' where IsDeleted = 0 and LevelId in (select Value from dbo.Split(''''''+cast(@LevelIds as varchar(100))+'''''','''','''')) ''	
				set @OrderByQuery='' group by T.tempWeekday_Id,TempWeekday_FromDate,TempWeekday_ToDate,ClosingTime,Reason, isDeleted ''
			end
		end
	if(isnull(@FromDate,'''')<>'''' and isnull(@ToDate,'''')<>'''')
	begin
		if(@WhereQuery!='''')
			begin
				set @WhereQuery=@WhereQuery + '' and TempWeekday_FromDate>=''''''+cast(@FromDate as nvarchar(20))+'''''' and TempWeekday_ToDate<=''''''+cast(@ToDate as nvarchar(20))+'''''' ''
			end
			else
			begin
				set @WhereQuery=@WhereQuery + '' where TempWeekday_FromDate>=''''''+cast(@FromDate as nvarchar(20))+'''''' and TempWeekday_ToDate<=''''''+cast(@ToDate as nvarchar(20))+'''''' ''
			end
	end
	SET @Query=@Query+@WhereQuery+@OrderByQuery
	--+@OrderByQuery;
	exec(@Query); 
	DROP TABLE #Temp
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_OtCalculation]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_OtCalculation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--select * from ta_tbl_leveldetails where parentid=0
-- proc_OtCalculation ''2015/01/01'',''2015/12/08'','''',0,'''',''1'',0,0,''SuperAdmin'','''',''All'','''',0,0,''Both'',''OverTime''
-- Modified by : Gopinath
-- Modified Date : 11-Jan-2014
-- Description    :     SQL Query Optimazation & Emp name filtering
-- proc_OtCalculation @fromDat=''2019-05-01 00:00:00'',@ToDat=''2019-05-06 00:00:00'',@empId=N'''',@shift=0,@EmployeeName=N'''',@LevelID=N''1'',@employeeCategory=0,@employeeType=0,@UserGroupName=N''Superadmin'',@GradeLevel=N''1'',@Status=N''All'',@EmpSwipeCard=N'''',@ParentId=0,@DesignationID=0,@Gender=N''Both'',@SanctionType=N''Overtime'',@EmpAutoId=1
CREATE PROCEDURE [dbo].[proc_OtCalculation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)     ,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@SanctionType varchar(25),
	@EmpAutoId bigint
)
AS
	BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	SET NOCOUNT ON;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Get Current date time format
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(25)             
	SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)     
	IF(@date=''dd/MM/yyyy'')
		BEGIN
			SET @dateFormat = 103
		END
	ELSE IF(@date=''MM/dd/yyyy'')
		BEGIN
			SET @dateFormat = 101
		END
	ELSE
		BEGIN
			SET @dateFormat = 106
		END   
	--End
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	--select * from #LevelRights
	CREATE TABLE #TempProcessedData
	(
		[Process_Rec_ID] bigint,
		[Employee_Code_Id] nvarchar(20),
		[Date] datetime,
		[Shift_Id] int,
		[InTime] nvarchar(25),
		[OutTime] nvarchar(25),
		[HrsWork] nvarchar(10),
		[HrsOT] nvarchar(10),
		[NormOT] nvarchar(10),
		[OffOT] nvarchar(10),
		[HolOT] nvarchar(10),
		[EarlyOut] nvarchar(10),
		[LateIn] nvarchar(10),
		[Attendance] nvarchar(20),
		[WorkHrs] nvarchar(10),
		[HrsLess] nvarchar(10),
		[HrsExtra] nvarchar(10),
		[LateInMins] float,
		[EarlyOutMins] float,
		[ExtraMins] float,
		[OtMins] float,
		[OvertimeStatus] nvarchar(50),
		[TotalDays] numeric(18, 1),
		[LeaveCode] nvarchar(20),
		[LateEntryReason] nvarchar(260),
		[EarlyOutReason] nvarchar(260),
		[ProcessFlag] bit,
		[Status] nvarchar(50),
		[FNAttendanceCode] nvarchar(15),
		[ANAttendanceCode] nvarchar(15),
		[ActHrsOT] nvarchar(10),
		[ActNormOT] nvarchar(10),
		[ActOffOT] nvarchar(10),
		[ActHolOT] nvarchar(10),
		[ActOtMins] float,
		[AvailOtMins] float,
		[ExtraTime_Id] bigint,
		
		-----
				SPEC_NormOT1	varchar(10),
				SPEC_NormOTMins1	int,
				SPEC_NormOT2	varchar(10),
				SPEC_NormOTMins2	int,
				SPEC_OffOT1		varchar(10),
				SPEC_OffOTMins1	int,
				SPEC_OffOT2		varchar(10),
				SPEC_OffOTMins2	int,
				SPEC_HOLOT1		varchar(10),
				SPEC_HOLOTMins1	int,
				SPEC_HOLOT2		varchar(10),
				SPEC_HOLOTMins2	int,			
				
				Modified_Spec_NormOTMins1 int,
				Modified_Spec_NormOTMins2 int,
				Modified_Spec_OffOTMins1 int,
				Modified_Spec_OffOTMins2 int,
				Modified_Spec_HolOTMins1 int,
				Modified_Spec_HolOTMins2 int,
				Modified_Spec_NormOTHrs1 varchar(10),
				Modified_Spec_NormOTHrs2 varchar(10),
				Modified_Spec_OffOTHrs1 varchar(10),
				Modified_Spec_OffOTHrs2 varchar(10),
				Modified_Spec_HolOTHrs1 varchar(10),
				Modified_Spec_HolOTHrs2 varchar(10)
				
	)
	--Employee Level Indexes
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]([EffectiveDate],[LevelId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]([EffectiveDate],[DesignationId],[EmployeeId] ASC)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType]([EffectiveDate],[TypeId],[EmployeeId] ASC) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory]([EffectiveDate],[CategoryId],[EmployeeId] ASC)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @ToDat,@empId,@DesignationID  
	insert into #EmpType exec [Proc_TA_EmpType] @ToDat,@empId,@employeeType 
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @ToDat,@empId,@employeeCategory     
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @ToDat,@empId      
	Declare @sqlTempProcessedData1 varchar(8000)
	--To split up the comma separated values
	if(@empId is not null and @empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	IF(@EmployeeName IS NOT NULL AND @EmployeeName <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EmployeeName,'','')
		END   
	create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
	;WITH ParentLevel AS
	(
		SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
		UNION ALL
		SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
		INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
	)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	ORDER BY lvl DESC
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@TopLevelId
	if(@isRequestCompOff is null or @isRequestCompOff='''')
		BEGIN
			select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
		END
	Declare @sqlTempProcessedData varchar(8000)    
	set @sqlTempProcessedData=
	''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@empId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		End
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_code_Id ''
		END
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0''     
	Execute(@sqlTempProcessedData)
	Declare @sqlCommonEmployee_Code_Id nvarchar(1000)
	
	
	if(@isRequestCompOff=0 or @SanctionType = ''OverTime'')
		BEGIN
			update TA_Tbl_ProcessedData set 
			OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
			set @sqlTempProcessedData=
			''insert into #TempProcessedData
			select PD.Process_Rec_ID,PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.InTime,PD.OutTime,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.OffOT,PD.HolOT,PD.EarlyOut,
			PD.LateIn,PD.Attendance,PD.WorkHrs,PD.HrsLess,PD.HrsExtra,PD.LateInMins,PD.EarlyOutMins,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.TotalDays,
			PD.LeaveCode,PD.LateEntryReason,PD.EarlyOutReason,PD.ProcessFlag,PD.Status,PD.FNAttendanceCode,PD.ANAttendanceCode,PD.ActHrsOT,PD.ActNormOT,PD.ActOffOT,PD.ActHolOT,PD.ActOtMins,case when ISNULL(ActOTMins,0)=0 then [OtMins] else ActOTMins end,0,
			PD.SPEC_NormOT1,
				PD.SPEC_NormOTMins1,
				PD.SPEC_NormOT2,
				PD.SPEC_NormOTMins2,
				PD.SPEC_OffOT1,
				PD.SPEC_OffOTMins1,
				PD.SPEC_OffOT2,
				PD.SPEC_OffOTMins2,
				PD.SPEC_HOLOT1,
				PD.SPEC_HOLOTMins1,
				PD.SPEC_HOLOT2,
				PD.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2
			from TA_Tbl_ProcessedData as PD inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id 
			Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
			where (PD.Date >= CONVERT(DATETIME,''''''+cast( @fromDat as nvarchar(50))+'''''', 102)) 
			AND (PD.Date <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102)) and (PD.OtMins <> 0 or ActOTMins <> 0)''
			Execute(@sqlTempProcessedData)
		END
	else
		BEGIN
			set @sqlTempProcessedData='' insert into #TempProcessedData 
			select OT.Process_RecID as ''''Process_Rec_ID'''',E.Employee_Code_Id,OT.Date,p.Shift_Id,P.InTime,P.OutTime,P.HrsWork,P.HrsOT,P.NormOT,P.OffOT,P.HolOT,p.EarlyOut,p.LateIn,
			p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
			p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id,
			P.SPEC_NormOT1,
			P.SPEC_NormOTMins1,
			P.SPEC_NormOT2,
			P.SPEC_NormOTMins2,
			P.SPEC_OffOT1,
			P.SPEC_OffOTMins1,
			P.SPEC_OffOT2,
			P.SPEC_OffOTMins2,
			P.SPEC_HOLOT1,
			P.SPEC_HOLOTMins1,
			P.SPEC_HOLOT2,
			P.SPEC_HOLOTMins2,
			spot.Modified_Spec_NormOTMins1,
			spot.Modified_Spec_NormOTMins2,
			spot.Modified_Spec_OffOTMins1,
			spot.Modified_Spec_OffOTMins2,
			spot.Modified_Spec_HolOTMins1,
			spot.Modified_Spec_HolOTMins2,
			spot.Modified_Spec_NormOTHrs1,
			spot.Modified_Spec_NormOTHrs2,
			spot.Modified_Spec_OffOTHrs1,
			spot.Modified_Spec_OffOTHrs2,
			spot.Modified_Spec_HolOTHrs1,
			spot.Modified_Spec_HolOTHrs2
			from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
			inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id  
			Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
			where E.Employee_Code_Id in (
			select SwipeCardNo from TA_Tbl_Employee inner join
			#EmpLevel on #EmpLevel.EmployeeId=E.Employee_Id)
			and P.[Date] between ''''''+cast( @fromDat as nvarchar(50))+'''''' and ''''''+cast(@todat as nvarchar(50))+''''''  ''
			Execute(@sqlTempProcessedData)
		END
	--select * from #TempProcessedData where OtMins <>0
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''	
	set @sqlQuery = @sqlQuery + ''select E.Employee_Code_Id,
										E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'''''''') as Employee_FirstName,
										replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],
										replace(Ta_tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,
										E.Gender,
										case	when ''+CONVERT(varchar,@dateFormat) +''=106 then REPLACE(CONVERT(VARCHAR, TPD.Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
												else CONVERT(VARCHAR, TPD.Date, ''+CONVERT(varchar,@dateFormat)+'') 
										end  as date,
										TPD.HrsWork,
										ISNULL(TPD.ActNormOT,TPD.NormOt) ActHrsOT,
										TPD.NormOt as HrsOT,
										SPEC_NormOT1,
										Modified_Spec_NormOTHrs1=ISNULL(Modified_Spec_NormOTHrs1,SPEC_NormOT1),
										SPEC_NormOT2,
										Modified_Spec_NormOTHrs2=ISNULL(Modified_Spec_NormOTHrs2,SPEC_NormOT2),
										ISNULL(TPD.ActOffOT,TPD.OffOT) ActOffOT,
										TPD.OffOT,
										SPEC_OffOT1,
										Modified_Spec_OffOTHrs1=ISNULL(Modified_Spec_OffOTHrs1,SPEC_OffOT1),
										SPEC_OffOT2,
										Modified_Spec_OffOTHrs2=ISNULL(Modified_Spec_OffOTHrs2,SPEC_OffOT2),
										ISNULL(TPD.ActHolOT,TPD.HolOT) ActHolOT,
										TPD.HolOT,									
										SPEC_HOLOT1,
										Modified_Spec_HolOTHrs1=ISNULL(Modified_Spec_HolOTHrs1,SPEC_HOLOT1),
										SPEC_HOLOT2,	
										Modified_Spec_HolOTHrs2=ISNULL(Modified_Spec_HolOTHrs2,SPEC_HOLOT2),
										ISNULL(TPD.OverTimeStatus,''''Pending'''') as OverTimeStatus,
										SPEC_NormOTMins1,
										SPEC_NormOTMins2,
										SPEC_OffOTMins1,
										SPEC_OffOTMins2,
										SPEC_HOLOTMins1,
										SPEC_HOLOTMins2,
										Modified_Spec_NormOTMins1,
										Modified_Spec_NormOTMins2,
										Modified_Spec_OffOTMins1,
										Modified_Spec_OffOTMins2,
										Modified_Spec_HolOTMins1,
										Modified_Spec_HolOTMins2,
										TPD.shift_id,
										ISNULL(ta_tbl_shift.Shift_ShortName,''''Off'''') as ShiftName, TPD.OtMins,
										CASE WHEN ISNULL(NormOt,''''00:00'''')=''''00:00'''' THEN 0 ELSE round(OtMins,0) END as ''''NormOTMins'''',
										CASE WHEN ISNULL(OffOT,''''00:00'''')=''''00:00''''	 THEN 0 ELSE round(OtMins,0) END as ''''WeekOffOTMins'''',
										CASE WHEN ISNULL(HolOT,''''00:00'''')=''''00:00''''  THEN 0 ELSE round(OtMins,0) END as ''''HolidayOTMins'''', 
										CASE WHEN ISNULL(ActNormOT,NormOT)=''''00:00'''' THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''''ActNormOTMins'''',
										CASE WHEN ISNULL(ActOffOT,OffOT)=''''00:00''''	 THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''''ActWeekOffOTMins'''',
										CASE WHEN ISNULL(ActHolOT,HolOT)=''''00:00''''	 THEN 0 ELSE ISNULL(round(ActOtMins,0),round(OtMins,0)) END as ''''ActHolidayOTMins'''',
										ISNULL(ActOtMins,OtMins) as ApprovedOTHours,
										(ISNULL(round(ActOtMins,0),round(OtMins,0)) - round(OtMins,0)) as RejectOTHours,										
										0 as SelectedRecords,
										E.SwipeCardNo,			
																	
										ISNULL(TPD.ActOtMins,TPD.OtMins) ActOtMins
	from #TempProcessedData TPD INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.SwipeCardNo''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on  #EmpType.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' where (TPD.OtMins <> 0 or TPD.ActOtMins <> 0) ''
	if(@SanctionType = ''CompOff'')
		begin
			set @sqlQuery = @sqlQuery + ''AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 ''
		end
	ELSE if(@SanctionType = ''OverTime'')
		begin
			set @sqlQuery = @sqlQuery + ''AND E.CompOff_Eligible = 0 AND E.OT_Eligible = 1 ''
		end
	if(@UserGroupName<>''SuperAdmin'')
		BEGIN
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		END
	if(@isReportingto > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	if(@shift<>0) 
		begin
			set @sqlQuery = @sqlQuery + '' And TPD.Shift_Id='' + cast (@shift as nvarchar(50))  
		end 
	set @sqlQuery = @sqlQuery + '' And E.isdeleted=0 and E.report_exclude=0 and
	((E.employee_status=1)
	or 
	(E.employee_status=0 and convert(nvarchar(11),E.InActiveDate,102)>= convert(nvarchar(11),TPD.Date,102))
	)''
	if(@Gender<>''Both'')
		begin
			set @sqlQuery = @sqlQuery + '' and E.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end   
	if not(@status='''' or @status=''All'')
		begin
			IF(@status = ''Pending'')
				BEGIN
					set @sqlQuery = @sqlQuery + '' AND (TPD.OvertimeStatus IS NULL OR TPD.OvertimeStatus = '''''' + @status + '''''')''
				END
			ELSE
				BEGIN
					set @sqlQuery = @sqlQuery + '' AND TPD.OvertimeStatus = '''''' + @status + ''''''''
				END
		end 
	set @sqlQuery = @sqlQuery + '' order by Employee_Code_Id,Date''
	print(@sqlQuery)	
	exec (@sqlQuery)	
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
	drop table #TempProcessedData
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GettingNearShiftDetailsUsingInpunch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <04-11-2016 16:44>
-- Description:	<Get the nearing shift details using in punch>
-- Proc_GettingNearShiftDetailsUsingInpunch ''2019/07/01'',''2019/07/21'','''','''',0,0,''superadmin'',0,0,0,''both'',0,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_GettingNearShiftDetailsUsingInpunch]
	-- Add the parameters for the stored procedure here
	@FROMDAT DATETIME,
	@Todate  DATETIME,
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@SHIFT INT,	
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		CompanyId int,
		AllocatedShiftStartTime varchar(10)		
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_EMPLOYEE_CODE_ID] ON [DBO].[#TEMPPROCESSEDDATA]([DATE],[EMPLOYEE_CODE_ID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @Todate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @Todate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @Todate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@Todate AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	''INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID '' 
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id ''
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0''
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	SET @SQLTEMPPROCESSEDDATA1=
	''INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	TE.EMPAUTOID,
			PD.DATE,
			PD.EMPLOYEE_CODE_ID,
			PD.INTIME,
			[dbo].[Func_TA_GetParentIds](TE.LEVELID),
			case when PD.Shift_ID=''''-1'''' then ''''Off'''' else S.SHIFT_STARTTIME end
	FROM TA_TBL_PROCESSEDDATA PD INNER JOIN #TEMPEMPLOYEE TE ON TE.EMPSWIPECARDNO=PD.EMPLOYEE_CODE_ID  	
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=PD.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (PD.DATE>= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102) and PD.DATE<= CONVERT(DATETIME,''''''+CAST( @Todate AS NVARCHAR(50))+'''''', 102)) and intime is not null and intime<>''''00:00'''' '' 
	IF(@SHIFT<>0)  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA1 = @SQLTEMPPROCESSEDDATA1 + '' AND PD.SHIFT_ID= ''+  CAST (@SHIFT AS NVARCHAR(50))
		END
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_ID VARCHAR(25),
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		DATE DATETIME,
		INTIME VARCHAR(30),
		AllocatedShiftStartTime varchar(10),
		CloseShifts varchar(max),
		CompanyId int,
		Gender varchar(10),
		ClosestShiftID int,
		EmployeeAutoID bigint
	)

	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	E.EMPLOYEE_CODE_ID,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&''''),
	REPLACE(T.TITLENAME,''''&AMP;'''',''''&''''),
	CONVERT(VARCHAR(20),PD.DATE,101),
	PD.INTIME,PD.AllocatedShiftStartTime,
	[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,1,DATE),
	CompanyId,E.Gender,
	(select top 1 ShiftID from [dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTime](CompanyId,DATE+intime,1,DATE))
	,E.Employee_ID''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     	
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId ''
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		(
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) 
		)
		AND(PD.DATE >= CONVERT(DATETIME, '''''' + CAST(@FROMDAT AS NVARCHAR(11)) + '''''', 102) and PD.DATE <= CONVERT(DATETIME, '''''' + CAST(@Todate AS NVARCHAR(11)) + '''''', 102))''
	IF(@GENDER<>''BOTH'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND E.GENDER = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' ''  
		END	
	if(@EmpAutoId>1)
		BEGIN
			set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	IF(@USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @GRADELEVEL + ''''  
		END	
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)''     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
	 --Get current date time format.
	DECLARE @dateFormat as int
	DECLARE @date as nvarchar(20)
	DECLARE @TimeFormat as nvarchar(10)
	SELECT @date=DateFormat,@TimeFormat=TimeFormat  from Func_TA_GetDateTimeFormat() --TimeFormat FROM TA_Tbl_DateandTimeFormat
      IF(@date=''dd/MM/yyyy'')
            BEGIN
                  SET @dateFormat = 103
            END
      ELSE IF(@date=''MM/dd/yyyy'')
            BEGIN
                  SET @dateFormat = 101
            END
      ELSE
            BEGIN
                  SET @dateFormat = 106
            END 
	update TM set CloseShifts=
	case	when	([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)='''') or 
					([dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE) is null)then 
					CloseShifts
			else CloseShifts+'';''+[dbo].[Func_TA_GettingCloseShiftDetailsUsingInpunchTimeData](CompanyId,DATE+intime,2,DATE)
	end from #TEMPMONTHLYATTENDANCE TM
	select
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,
		BRANCHNAME Level,
		DESIGNATION Title,
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Date, @dateFormat) end AS	Date,
		case when Intime<>''00:00'' then
					CASE	WHEN (@TIMEFORMAT)=''HH:MM'' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,InTime,0)), 114)
							ELSE SUBSTRING(InTime,13,5)+'' '' + SUBSTRING(InTime,18,2)
					END
			else '''' 
		end
		ActualShiftIn,		
		case	when AllocatedShiftStartTime!=''Off'' then 
			case	when (@TimeFormat)=''hh:mm'' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,AllocatedShiftStartTime,0)), 114)
					else	SUBSTRING(AllocatedShiftStartTime,13,5)+'' '' + SUBSTRING(AllocatedShiftStartTime,18,2)
			end
				when AllocatedShiftStartTime=''Off'' then AllocatedShiftStartTime end
		AllocatedShift,
		CloseShifts NearestShift,Gender,CompanyId,DATE as Format,ClosestShiftID ShiftID,EmployeeAutoID
	from #TEMPMONTHLYATTENDANCE order by EMPLOYEE_ID,DATE
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_GettingAutoShiftConfiguration]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GettingAutoShiftConfiguration]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<P. Velumani>
-- Create date: <13/07/2019 16:44>
-- Description:	<Get All the shift details and Employee info for configuration>
-- Proc_GettingAutoShiftConfiguration '''','''',0,0,''superadmin'',''1'',25,0,''both'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_GettingAutoShiftConfiguration]
	-- Add the parameters for the stored procedure here
	@EMPLOYEENAME VARCHAR(MAX),	
	@EMPLOYEEID VARCHAR(MAX),
	@EMPLOYEECATEGORY INT,
	@EMPLOYEETYPE INT,
	@USERGROUPNAME VARCHAR(250),
	@GRADELEVEL VARCHAR(20),
	@PARENTID INT,
	@DESIGNATIONID INT,
	@GENDER VARCHAR(10),
	@EmpAutoId bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20),LEVELID int)
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	Declare @Todate datetime
	set @Todate = getdate();
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))   
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,@PARENTID) AS LEVELID
	CREATE NONCLUSTERED INDEX [IDX_LEVELID] ON [DBO].[#EMPLEVEL]([EFFECTIVEDATE],[EMPLOYEEID],[LEVELID]) ON [PRIMARY]  	
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPDESIGNATION]([EFFECTIVEDATE],[EMPLOYEEID],[DESIGNATIONID])ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPTYPE]([EFFECTIVEDATE],[EMPLOYEEID],[TYPEID]) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_EFFECTIVE] ON [DBO].[#EMPCATEGORY]([EFFECTIVEDATE],[EMPLOYEEID],[CATEGORYID])ON [PRIMARY]  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @Todate,@EMPLOYEEID,@DESIGNATIONID
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @Todate,@EMPLOYEEID,@EMPLOYEETYPE
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @Todate,@EMPLOYEEID,@EMPLOYEECATEGORY
	--TO SPLIT UP THE COMMA SEPARATED VALUES
	IF(@EMPLOYEEID IS NOT NULL AND @EMPLOYEEID <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEEID(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEEID
			SELECT * FROM SPLITUPEMPLOYEECODE(@EMPLOYEEID)
		END	
	IF(@EMPLOYEENAME IS NOT NULL AND @EMPLOYEENAME <> '''')
		BEGIN
			CREATE TABLE #EMPLOYEENAME(EMPLOYEEID VARCHAR(25))
			INSERT INTO #EMPLOYEENAME
			SELECT [VALUE] FROM DBO.[SPLITUPEMPLOYEENAME](@EMPLOYEENAME,'','')
		END	
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@Todate AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	IF NOT (@EMPLOYEENAME = '''')  
		BEGIN  
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' INNER JOIN #EMPLOYEENAME ON #EMPLOYEENAME.EMPLOYEEID=ELEVEL.Employee_Code_Id ''
		END
	EXECUTE(@SQLEMPLEVEL)	
	SET @SQLTEMPPROCESSEDDATA=	''INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO,#EMPLEVEL.LEVELID FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID '' 
	IF NOT (@EMPLOYEEID = '''')  
		BEGIN  
			SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' INNER JOIN #EMPLOYEEID ON #EMPLOYEEID.EMPLOYEEID=TA_TBL_EMPLOYEE.Employee_Code_Id ''
		END
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0''
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(	
		AutoID int identity(1,1),
		EMPLOYEE_Code_ID VARCHAR(25),
		EMPLOYEE_ID int,
		EMPNAME VARCHAR(500),
		BRANCHNAME VARCHAR(500),
		DESIGNATION VARCHAR(250),
		--EMPLOYEE_STATUS int
	)
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT 
	E.EMPLOYEE_CODE_ID,E.Employee_Id,
	ISNULL(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,''''''''),
	REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&''''),
	REPLACE(T.TITLENAME,''''&AMP;'''',''''&'''')''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     	
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId ''
	SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 	
		(		
			(E.EMPLOYEE_STATUS=1)
			OR
			(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)<=getdate()) 
		)''
	IF(@GENDER<>''BOTH'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND E.GENDER = '''''' + CAST(@GENDER AS NVARCHAR(8)) + '''''' ''  
		END	
	if(@EmpAutoId>1)
		BEGIN
			set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
		END
	IF(@USERGROUPNAME<>''SUPERADMIN'')  
		BEGIN  
			SET @SQLQUERY = @SQLQUERY + '' AND TA_TBL_GRADE.GRADE_LEVEL>='' + @GRADELEVEL + ''''  
		END	
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME''
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)	
		DECLARE @AutoShiftSQL AS VARCHAR(MAX)    
		SET @AutoShiftSQL= ''''    	
		SET @AutoShiftSQL = @AutoShiftSQL + ''Select Distinct
		AutoID,
		EMPLOYEE_ID as id,
		EMPNAME Name,	
		EMPLOYEE_ID as EmployeeAutoID,
		EMPLOYEE_Code_ID as EMPLOYEE_Code_ID		
		from #TEMPMONTHLYATTENDANCE ''
		Create table #AutoShiftConfig (AutoID int, EMPLOYEE_ID int,EMPNAME varchar(max), EmployeeAutoID int, EmployeeCodeId varchar(40)) 
		Insert into #AutoShiftConfig exec (@AutoShiftSQL)
		select AutoID,EmployeeCodeId as id,EMPNAME as Name, EmployeeAutoID, 
		isnull(b.ShiftId1,0) as ShiftID1,isnull(b.ShiftId2,0) as ShiftID2,isnull(b.ShiftId3,0) as ShiftID3
		, isnull(b.ShiftId4,0) as ShiftID4, isnull(b.ShiftId5,0) as ShiftID5
		from #AutoShiftConfig a
		left outer join TA_Tbl_AutoShiftConfiguration b on b.EmployeeId = a.EMPLOYEE_ID
		order by AutoID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_GetRouteDetails]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_GetRouteDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_GetRouteDetails]  
AS  
BEGIN  
 SELECT [Id],Route_Name FROM TA_Tbl_RouteMaster WHERE Isdeleted=1
END 
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckDateForHoliday]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckDateForHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_CheckDateForHoliday ''06/01/2015'',''2222''
/*  
Procedure Name : Proc_TA_CheckDateForHoliday  
Description : check date fore holidays
Tables Included : TA_Tbl_Holiday  
Created By : Janakaraj.P 
Created On : 20-Aug-2007
Modified By :  Gopinath on 23Nov15 for bug no.31239
Modified On :  
*/  
--Proc_TA_CheckDateForHoliday ''07/28/2011'',''Emp103''
CREATE PROCEDURE [dbo].[Proc_TA_CheckDateForHoliday]
(
	@Date Varchar(15),
	@EmployeeCodeId nvarchar(15)
)
AS
BEGIN
	set nocount on 
	declare @EmployeeLevelId int
	set @EmployeeLevelId = (select top 1 EL.LevelId from TA_Tbl_EmployeeLevel EL
	inner join TA_Tbl_Employee E on E.Employee_Id=EL.EmployeeId
	where E.employee_Code_Id = @EmployeeCodeId order by EffectiveDate desc)
	create table #Level (LevelID int) 
	declare @EmployeeLevelIdNew int
	set @EmployeeLevelIdNew=@EmployeeLevelId  
	while((select Id from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew) <> '''')    
	BEGIN    
	  insert into #Level select id from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew    
	  select @EmployeeLevelIdNew = parentId from TA_tbl_LevelDetails where id=@EmployeeLevelIdNew
	END   
	SELECT h.Holiday_Id FROM TA_Tbl_Holiday H 
	inner join TA_Tbl_HolidayChildTable HCT on H.Holiday_Id=HCT.Holiday_Id
	INNER JOIN #Level on (#Level.LevelID = HCT.LevelID or HCT.LevelID=0)
	WHERE Holiday_FromDate <= @Date AND Holiday_ToDate >= @Date 
	AND (Holiday_Type = ''G'' or Holiday_Type = ''L'') AND IsDeleted = 0 and HCT.LevelID=@EmployeeLevelId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CMITechSelectDesignation]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CMITechSelectDesignation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <22-Jan-2020>
-- Description:	<CMITech Select Designation dropdown in grid>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CMITechSelectDesignation] 

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--Select isnull(TitleId,0) as TitleId, (isnull(TitleName,'''') + '' - '' + c.name) as TitleName, b.Grade_Level as Grade_Level
	--from ta_tbl_title a
	--inner join Ta_Tbl_levelDetails c on c.id = a.LevelID 
	--inner join TA_Tbl_Grade b on b.Grade_ID = a.GradeID
	
	Select isnull(TitleId,0) as TitleId, (isnull(TitleName,'''')) as TitleName, b.Grade_Level as Grade_Level
	from ta_tbl_title a	
	inner join TA_Tbl_Grade b on b.Grade_ID = a.GradeID
	
 
END


' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckTitle_Update]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckTitle_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*Procedure Name : Proc_TA_CheckTitle_Update    
Description : check title before update    
Tables Included : TA_Tbl_Title    
Created By : Prabakaran    
Created On : 30-Jul-07    
Modified By :    
Modified On :  */  
CREATE Procedure [dbo].[Proc_TA_CheckTitle_Update]
(	
	@TitleId int
) 
As
	DECLARE @Isdel INT
	declare @sql as nvarchar(3000)
	Declare @TitleName NVARCHAR(50)
	SET @Isdel=0
	BEGIN
		set @TitleName=(Select TitleName from TA_Tbl_Title where TitleId=@TitleId)
		set @sql = ''Select Count(TitleName)as TName from TA_Tbl_Title where TitleId<>''+cast(@TitleId as nvarchar(25))+'' And TitleName=N''''''+@TitleName+'''''' ''	
        exec(@sql)	
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearSettingExists]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearSettingExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckYearSettingExists   '''','''',''A'',35
Description : Save year settings details into table  
Tables Included : TA_Tbl_YearSetting  
Created By : Prabakaran  
Created On : 21-Nov-07  
Modified By :  Gopinath.k
Modified On :  09-Nov-16 for wrongly fetching of shift allocation from next year also while creating year in between months.
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_CheckYearSettingExists]   
@FromDate varchar(30),
@ToDate varchar(30),
@YearType char(1),
@YearSettings_Id int
as  
if( @YearType=''P'')
begin
	SELECT count(*) as YearCount FROM TA_Tbl_YearSetting as Count 
	where (FromDate between @FromDate and @ToDate) or (ToDate between @FromDate and @ToDate)
	or (@FromDate between FromDate and ToDate) or (@ToDate between FromDate and ToDate)
end
else if (@YearType=''A'')
begin
	declare @count as int  
	declare @RecordExiststing as int  
	set @count=0   
	begin
		set @RecordExiststing=(SELECT count(elp.LeavePolicy_Id) FROM ta_tbl_Emp_LeavePolicy elp inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=elp.YearSettingId where elp.isdeleted=0 and ys.YearSettings_Id=@YearSettings_Id)  
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''Leavepolicy''
	end
	begin
		set @RecordExiststing=(SELECT count(Holiday_Id) FROM ta_tbl_holiday h inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=h.YearSettings_Id where h.isdeleted=0 and ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''Holiday''
	end
	begin
		set @RecordExiststing=(SELECT count(Holiday_Id) FROM ta_tbl_holidaysettings hs inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=hs.YearSettingId where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''Holiday Settings''
	end
	/* This code commented because year closure count checked in Proc_Ta_deleteYearSetting  */
	/*
	begin
	set @RecordExiststing=(SELECT count(YearClosureId) FROM ta_tbl_yearclosure yc inner join TA_Tbl_YearSetting ys on ys.YearSettings_Id=yc.Year_SettingID where ys.YearSettings_Id=@YearSettings_Id)
	if @RecordExiststing<>0 
	set @count=@count+@RecordExiststing
	end
	*/
	begin
		declare @StartMonth as int 
		declare @EndMonth as int 
		--declare @StartYear as int 
		--declare @EndYear as int 
		--Set @StartYear=(select StartYear from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		--Set @EndYear=(select EndYear from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		Set @StartMonth=(select datepart(month,convert(varchar(20),Startyear)+''-''+convert(varchar(20),StartMonth)+''-01'')from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		Set @EndMonth=(select datepart(month,convert(varchar(20),Endyear)+''-''+convert(varchar(20),EndMonth)+''-01'')from ta_tbl_yearsetting where YearSettings_Id=@YearSettings_Id)
		set @RecordExiststing=(select count(ps.year) from ta_tbl_permanentshiftAllocation ps 
		inner join  ta_tbl_yearsetting ys on (ys.StartYear=ps.Year and ps.Month>= @StartMonth) or (ys.EndYear=ps.Year and ps.Month<= @EndMonth)
		where ys.YearSettings_Id=@YearSettings_Id )
		--set @RecordExiststing=(select count(ps.year) from ta_tbl_permanentshiftAllocation ps 
		--inner join  ta_tbl_yearsetting ys on ys.StartYear=ps.Year or ys.EndYear=ps.Year 
		--where ys.YearSettings_Id=@YearSettings_Id and ps.Month>= @StartMonth and ps.Month<= @EndMonth)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''permanentshiftAllocation''
	end
	begin
		set @RecordExiststing=(select count(ts.year) from TA_Tbl_TemporaryShiftAllocation ts inner join  ta_tbl_yearsetting ys on ys.StartYear=ts.Year or ys.EndYear=ts.Year where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''TemporaryShiftAllocation''
	end
	begin
		set @RecordExiststing=(select count(mc.MonthClosure_Id) from ta_tbl_monthclosure mc inner join  ta_tbl_yearsetting ys on ys.StartYear=mc.MonthClosure_Year or ys.EndYear=mc.MonthClosure_Year where ys.YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''Monthclosure''
	end 
	begin
		set @RecordExiststing=(SELECT count(YearSettings_Id) FROM TA_Tbl_YearSetting where IsActive=1 and YearSettings_Id=@YearSettings_Id)
		if @RecordExiststing<>0 
		set @count=@count+@RecordExiststing
		--select @RecordExiststing,''Year Setting''
	end
	if (@count>0)
	begin
		set @count=1
	end
		SELECT @count as YearCount
	end' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureExistOrNot]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosureExistOrNot]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	28-Jan-2014
Descriptions	:	Checking whether the selected year closure is exist or not based on orgid and yearsettingsid
Proc_TA_CheckYearClosureExistOrNot 6,1
*/
CREATE proc [dbo].[Proc_TA_CheckYearClosureExistOrNot]
(
@OrgLevelId int=0,
@Year_SettingID int=0
)
as
begin
declare @Count as int;
set @Count=0;
set @Count=(select COUNT(*) from TA_Tbl_YearClosure where OrgLevelId=@OrgLevelId and Year_SettingID=@Year_SettingID and isnull(YearClosed,'''')<>'''' and ISNULL(DateClosed,'''')<>'''');
select isnull(@Count,0) as count
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckYearClosureAlreadyProcessedOrNot]
	-- Add the parameters for the stored procedure here
	@yearSettingId int, @organizationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select COUNT(*) from TA_Tbl_YearClosure where Year_SettingID=@yearSettingId and OrgLevelId=@organizationId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckYearClosed]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckYearClosed]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*    
Procedure Name  :   
Description  :   
Tables Included :    
Created By  : Prabakaran.P  
Created On  : 08-Feb-08  
Modified By  :    
Modified On  :     
*/    
CREATE    PROCEDURE [dbo].[Proc_TA_CheckYearClosed]        
@EmployeeId int
AS        
BEGIN   
SELECT count(YearClosureId) as YearCount FROM TA_Tbl_YearClosure   
WHERE (YearClosed is not null and DateClosed is not null) 
and Year_SettingID =(Select YearSettings_Id from TA_Tbl_YearSetting WHERE IsActive=1)
and Employee_Id=@EmployeeId
END   
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftPatternRestore]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftPatternRestore]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name	: Proc_TA_CheckShiftPatternRestore 88 
Description	: While Restore Shift Pattern, Checking duplicate shift Pattern Name 
Tables Included : Ta_tbl_ShiftPattern
Created By 	: Prabakaran  
Created On 	: 06-FEB-08  
Modified By 	: Prabakaran.P 
Modified On 	:  27-Feb-08
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_CheckShiftPatternRestore] 
@ShiftPatternId int
as
declare @ShiftPatternCount as int
declare @PatternDays as int
declare @shiftIds as int
declare @shiftname as nvarchar(50)
declare @shiftCount as int
declare @shiftTotalCount as int
declare @incrementval as int
declare @sql as nvarchar(200)
set @sql=''''
begin
	set @ShiftPatternCount=(select count(Pattern_Name)as ShiftPatternCount from TA_Tbl_ShiftPattern
	where lower(Pattern_Name)in (select lower(Pattern_Name) from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId) and ShiftPattern_Id<>@ShiftPatternId and Isdeleted = 0)
	set @PatternDays =(select Shift_days from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId)
	set @shiftCount=0
	set @shiftTotalCount=0
	set @incrementval=1
	while(@incrementval<=@PatternDays)
		begin
			set @shiftname = ''Day'' + convert(nvarchar(50),@incrementval) + ''_Shift''
			set @sql=''select '' + @shiftname + '' as shiftId from TA_Tbl_ShiftPattern where ShiftPattern_Id='' + convert(nvarchar(50),@ShiftPatternId)
			--set @shiftIds=(select @shiftname as shiftId from TA_Tbl_ShiftPattern where ShiftPattern_Id=@ShiftPatternId)
				create table #tempshiftNew 
				(
					shiftIds int
				)  
				insert into #tempshiftNew exec(@sql) 
				set @shiftIds=(select * from #tempshiftNew)
				drop table #tempshiftNew
			set @shiftCount=(select count(Shift_Id) from TA_Tbl_Shift where Shift_Id=@shiftIds and IsDeleted=1)
			set @shiftTotalCount=@shiftTotalCount+@shiftCount
			set @incrementval=@incrementval+1
		end
set @ShiftPatternCount=@ShiftPatternCount+@shiftTotalCount
select @ShiftPatternCount as ShiftPatternCount
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckShiftName]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckShiftName]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_CheckShiftName  
Description : check shift name 
Tables Included : TA_Tbl_ShiftPattern  
Created By :  Janakaraj.P  
Created On : 19-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE PROCEDURE [dbo].[Proc_TA_CheckShiftName]  
   AS
	BEGIN
		SELECT * FROM TA_Tbl_ShiftPattern
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckRoute_Update]    Script Date: 03/25/2021 10:22:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckRoute_Update]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_CheckRoute_Update    
Description : check route before update, is already there or not  
Tables Included : TA_Tbl_RouteMaster    
Created By : Arun Vinoth    
Created On : 14-Aug-2007  
Modified By :    
Modified On :  
*/
CREATE   Procedure [dbo].[Proc_TA_CheckRoute_Update]      
( 
	@RouteId int      
)       
As      
	DECLARE @sql as nvarchar(3000)    
	DECLARE @RouteName NVARCHAR(50)      
	BEGIN      
		--Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>@RouteId And Route_Name=@RouteName AND Isdeleted=0    
		select @RouteName=Route_Name from TA_Tbl_RouteMaster where Id=@RouteId
		set @sql = ''Select Count(Route_Name)as RName from TA_Tbl_RouteMaster where Id<>''+cast(@RouteId as nvarchar(25))+'' And Route_Name=N''''''+@RouteName+'''''' AND Isdeleted=0''
		exec(@sql)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteLeaveApplication_Angler]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteLeaveApplication_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE   PROCEDURE [dbo].[Proc_TA_DeleteLeaveApplication_Angler]
(
@LeaveApplication_Id int,
@auEmpId int,
@datetimeLeaveFrom datetime,
@datetimeLeaveTo datetime,
@varSessionFrom nvarchar(50),
@varSessionTo nvarchar(50),
@varType nvarchar(1)
)
AS
begin
	SET NOCOUNT ON;
    if(@varType=''A'')
    begin
        update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
		where LeaveApplication_Id = @LeaveApplication_Id
    end
    else
    begin
		update TA_Tbl_LeaveApplication set IsDeleted = 1,Emp_Id=@auEmpId 
		where LeaveApplication_Id = @LeaveApplication_Id and Leave_FromDate = @datetimeLeaveFrom and Leave_ToDate = @datetimeLeaveTo and Leave_SessionFrom = @varSessionFrom and Leave_SessionTo = @varSessionTo
    end
	declare @intDeletedLeaveId as int
	set @intDeletedLeaveId = (select count(LeaveApplication_Id) from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id and IsDeleted=0)
	if(@intDeletedLeaveId=0)
		begin
			update TA_Tbl_LeaveApplicationMaster set IsDeleted = 1,Emp_Id=@auEmpId where LeaveApplication_Id = @LeaveApplication_Id
		end
	--update the processflag
	update Ta_Tbl_ProcessedData set processflag=0
	from Ta_Tbl_LeaveApplication t2
	inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
	inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
	t1.date between t2.Leave_FromDate and t2.Leave_ToDate
	where t2.LeaveApplication_Id=@LeaveApplication_Id
	declare @intEmployeeId as int
	set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id)
	--Update year closure
	update ta_tbl_yearclosure set Leave_Taken=
	(select isnull(sum(NumberOfDays),0.0)
	from Ta_Tbl_LeaveApplication
	inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
	where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
	and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
	and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
	and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status=''Approved''
	and TA_Tbl_YearSetting.IsActive=1 and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId)
	select @intDeletedLeaveId as LeaveCount
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmployeeChildrenDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteEmployeeChildrenDetails]  
  @EmployeeId INT  
 AS  
 DECLARE @DEL BIT  
 SET @DEL=0  
 BEGIN  
  UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child=''C'' 
  UPDATE TA_Tbl_EmpChildrenDetails SET IsDeleted=@DEL WHERE Emp_ID=@EmployeeId AND Spouse_Child=''S'' 
  DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE Emp_Id=@EmployeeId  
  DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmployeeId 
 END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	:	Proc_TA_DeleteEmpLeavePolicy_Yearclose 215,48 
Description 	:	Delete Employee Leave Policy details
Tables Included :	TA_Tbl_Emp_LeavePolicy, TA_Tbl_Emp_LeavePolicyDetails, TA_Tbl_LeavePolicy 
Created By 	:	Arun vinoth	  
Created On 	:	10 Aug 07 
Modified By 	:	Prabakaran.P
Modified On 	:	15-Feb-08
Description	:	Changes based on Year Closure logic
*/  
CREATE    PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy_Yearclose]   
@EmpID int,
@year int
AS  
BEGIN  
	SET NOCOUNT ON;  
	DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmpID and Emp_LeavePolicyId in (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy where YearSettingId=@Year and EmployeeId=@EmpID)
	DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId=@EmpID and YearSettingId=@Year
END  
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteEmpLeavePolicy]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteEmpLeavePolicy]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: Proc_TA_DeleteEmpLeavePolicy  
Description 	: Delete Employee Leave Policy details
Tables Included : TA_Tbl_Emp_LeavePolicy, TA_Tbl_Emp_LeavePolicyDetails 
Created By 		: Arun vinoth	  
Created On 		: 10 Aug 07 
Modified By 	:  Prabakaran.P
Modified On 	:  16-Feb-10
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_DeleteEmpLeavePolicy] 
	@EmpID INT
AS
declare @YearSettingID as int
BEGIN
	SET NOCOUNT ON;
	Set @YearSettingID=(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1)  
	DELETE FROM TA_Tbl_Emp_LeavePolicyDetails WHERE EmpID=@EmpID and Emp_LeavePolicyId IN (select Emp_LeavePolicyId from TA_Tbl_Emp_LeavePolicy where EmployeeId=@EmpID and YearSettingId=@YearSettingID)	
	DELETE FROM TA_Tbl_Emp_LeavePolicy WHERE EmployeeId=@EmpID and YearSettingId=@YearSettingID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CountGrade]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CountGrade]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*Procedure Name : Proc_TA_CountGrade    
Description : counting total grade   
Tables Included : ta_tbl_Title    
Created By : Arun  Vinoth
Created On : 30-Jul-07  
Modified By :  
Modified On :*/  
CREATE procedure [dbo].[Proc_TA_CountGrade]
(@Grade INT)
as
Select count(*) from ta_tbl_Title where GradeID=@Grade-- And Isdeleted=0
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompOffCalculation]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompOffCalculation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Angeswaran>
-- Create date: <27-Dec-2012>
-- Description:	<Comp off Calculation>
-- Proc_TA_CompOffCalculation ''01/Jan/2012'',''22/Jan/2013'','''',0,'''',''0,3'',0,0,''SuperAdmin'',''0'',''All'','''',0,0,''Both'',''CompOff''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CompOffCalculation]
(
	-- Add the parameters for the stored procedure here
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
    @Gender varchar(10),
    @SanctionType varchar(25)
 )   
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  --Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
--create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--select * from #LevelRights
CREATE TABLE #TempProcessedData
(
	[Employee_Code_Id] nvarchar(20),
	[Date] datetime,
	[Shift_Id] int,
	[HrsWork] nvarchar(10),
	[HrsOT] nvarchar(10),
	[NormOT] nvarchar(10),
	[WorkHrs] nvarchar(10),
	[HrsExtra] nvarchar(10),
	[ExtraMins] float,
	[OtMins] float,
	[OvertimeStatus] nvarchar(50),
	[Status] nvarchar(50),
	[HrsCompOff] nvarchar(20),
	[CompOffMins] int
)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
inner join #LevelRights on #LevelRights.LevelId=EL.levelId
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
----Employee Pay insert in Temporary table
--insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
--select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
--inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) EmpBpay
--inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
--AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
insert into #TempProcessedData
select PD.Employee_Code_Id,PD.Date,PD.Shift_Id,PD.HrsWork,PD.HrsOT,PD.NormOT,PD.WorkHrs,PD.HrsExtra,PD.ExtraMins,PD.OtMins,PD.OvertimeStatus,PD.Status,HrsCompOff,CompoffMins
from TA_Tbl_ProcessedData as PD 
inner join ta_tbl_employee e on e.SwipeCardNo=PD.Employee_Code_Id
inner join #EmpLevel el on el.employeeid=e.employee_id
where
(PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)) and compoffMins<>0
--select * from #TempProcessedData 
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + '' select * from (''
	set @sqlQuery = @sqlQuery + '' select TA_Tbl_Employee.Employee_Code_Id,convert(varchar(20),#TempProcessedData.Date,101) as date,#TempProcessedData.shift_id,''
	set @sqlQuery = @sqlQuery + '' case LP.OtHourWise when ''''0'''' then case LP.OtDayWise when ''''1'''' then ''''Day wise :(HD-'''' + isnull(LP.OtMinHrs,''''00:00'''') + '''' Hrs,FD-'''' + isnull(LP.FullDayCompOffHrs,''''00:00'''') +'''' Hrs)'''' else ''''Not Defined'''' end when ''''1'''' then ''''Hour wise : (HD-'''' + isnull(LP.OtMinHrs,''''00:00'''') + '''' Hrs,FD-'''' + isnull(LP.FullDayCompOffHrs,''''00:00'''') + '''' Hrs)'''' else ''''Not Defined'''' end as CompOffHourDayWise,''
	set @sqlQuery = @sqlQuery + '' LP.OtHourWise,LP.OtDayWise,LP.OtMinHrs,DATEPART(hh,LP.OtMinHrs) * 60 + DATEPART(MI,LP.OtMinHrs) as OTHRsMins,
	LP.FullDayCompOffHrs,DATEPART(hh,LP.FullDayCompOffHrs) * 60 + DATEPART(MI,LP.FullDayCompOffHrs) as CompOffHrMins,
	ISNULL(ta_tbl_shift.Shift_ShortName,''''Off'''') as ShiftName, isnull(ta_tbl_shift.Shift_TotalWorkingHours,''''00:00'''') as DefinedWorkingHours,#TempProcessedData.OtMins,''
	set @sqlQuery = @sqlQuery + '' #TempProcessedData.HrsWork, #TempProcessedData.NormOt as HrsOT, ta_tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''''''') as Employee_FirstName,replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],ISNULL(#TempProcessedData.OverTimeStatus,''''Pending'''') as OverTimeStatus,0 as SelectedRecords,Ta_Tbl_Employee.SwipeCardNo,replace(Ta_tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,TA_Tbl_Employee.Gender,0 as compoffDays,#TempProcessedData.HrsCompOff,#TempProcessedData.CompOffMins from #TempProcessedData INNER JOIN Ta_Tbl_Employee on #TempProcessedData.Employee_Code_Id=Ta_Tbl_Employee.SwipeCardNo''
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''	 
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on  #EmpType.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join TA_Tbl_Emp_LeavePolicy ELP on ELP.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id=ELP.LeavePolicy_Id ''
	--set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.employeeid=TA_Tbl_Employee.Employee_Id ''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeePay.EmployeeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	--set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation ON TA_Tbl_Employee.Employee_Id=TA_Tbl_EmployeeDesignation.EmployeeID''
	--set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON dbo.TA_Tbl_EmployeeDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	--set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' where #TempProcessedData.compoffMins <> 0  ''
	if(@SanctionType = ''CompOff'')
		begin
			set @sqlQuery = @sqlQuery + ''AND Ta_Tbl_Employee.CompOff_Eligible=1 ''
		end
	ELSE if(@SanctionType = ''OverTime'')
		begin
			set @sqlQuery = @sqlQuery + ''AND Ta_Tbl_Employee.OT_Eligible=1 ''
		end
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end
	if(@shift<>0) 
	begin
		set @sqlQuery = @sqlQuery + '' And #TempProcessedData.Shift_Id='' + cast (@shift as nvarchar(50))  
	end 
	set @sqlQuery = @sqlQuery + '' And ta_tbl_employee.isdeleted=0 and ta_tbl_employee.report_exclude=0 and ta_tbl_employee.employee_status=1''
	if not(@EmployeeName='''')
	begin
		--set @sqlQuery = @sqlQuery + ''and dbo.TA_Tbl_Employee.Employee_FirstName like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + ''''''''
		set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' '''' + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	If Not (@EmpSwipeCard = '''')  
	 Begin  
	  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	 End 
	if not (@empId='''')
	begin
		set @sqlQuery = @sqlQuery + '' and ta_tbl_Employee.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
	end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	 if(@Gender<>''Both'')
		begin
		   set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end	
	if not(@status='''' or @status=''All'')
	begin
	 	IF(@status = ''Pending'')
			BEGIN
				set @sqlQuery = @sqlQuery + '' AND (#TempProcessedData.OvertimeStatus IS NULL OR #TempProcessedData.OvertimeStatus = '''''' + @status + '''''')''
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + '' AND #TempProcessedData.OvertimeStatus = '''''' + @status + ''''''''
			END
    end 
	set @sqlQuery = @sqlQuery + '' ) OverTime order by OverTime.Employee_Code_Id , OverTime.Date''
create table #tempHourwise(Employee_code_Id varchar(50),date datetime,shift_Id int,CompOffHourDaywise varchar(50),OtHourWise int,
OtDayWise int,OtMinsHrs varchar(25),OTHRsMins int,FullDayCompOffHrs varchar(25),FullDayCompOffMins int,ShiftName varchar(50),
DefinedworkingHours varchar(20),otMins int,HrsWork varchar(50),HrsOT varchar(20),
Employee_FirstName varchar(100),LevelName varchar(50),OverTimeStatus varchar(20),
SelectedRecords int,SwipeCardNo varchar(50),TitleName varchar(25),Gender varchar(10),compOffDays1 float,HrsCompOff varchar(50),CompOffMins int)
insert into #tempHourwise
exec (@sqlQuery)
--select * from #tempHourwise
update #tempHourwise set compOffDays1= case when CompOffMins >= FullDayCompOffMins then 1 when CompOffMins >= OTHRsMins then 0.5 else 0 end 
where  OtDayWise=1 and OverTimeStatus=''Approved''
--select * from #tempHourwise
update #tempHourwise set compOffDays1= A.compOffDays from 
(select sum(compOffDays1) as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtDayWise=1 and OverTimeStatus=''Approved'' 
group by Employee_code_Id,shift_Id) as A
inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
--update #tempHourwise set compOffDays1= A.compOffDays from 
--(select (SUM(CompOffMins)/FullDayCompOffMins) + case  when ((SUM(CompOffMins)%FullDayCompOffMins)/OTHRsMins) >= 1 then 0.5 else 0 end as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtHourWise=1 and OverTimeStatus=''Approved'' group by
--Employee_code_Id,OTHRsMins,shift_Id,FullDayCompOffMins) as A 
--inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
update #tempHourwise set compOffDays1= A.compOffDays from 
(select (cast((SUM(CompOffMins)/OTHRsMins) as float)/2) as compOffDays,Employee_code_Id,shift_Id from #tempHourwise where OtHourWise=1 and OverTimeStatus=''Approved'' group by
Employee_code_Id,OTHRsMins,shift_Id,FullDayCompOffMins) as A 
inner join #tempHourwise on #tempHourwise.Employee_code_Id=A.Employee_code_Id and #tempHourwise.shift_Id=A.shift_Id
select * from #tempHourwise
--insert into #tempDaywise
--select * from #tempHourwise  where OtDayWise=1
--delete from #tempHourwise where OtDayWise=1
--insert into #tempNOHourDaywise
--select * from #tempHourwise  where OTHRsMins=''''
--insert into #tempFinalCompOff
--select * from #tempNOHourDaywise
--	union all
--select COUNT(Employee_code_Id) as compOffDays,Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender from #tempDaywise group by
--Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender having otMins >= OTHRsMins
--	union all
--select SUM(otMins)/OTHRsMins as compOffDays,Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender from #tempHourwise where CompOffHourDaywise <> ''''
--group by
--Employee_code_Id ,date,shift_Id,CompOffHourDaywise,OtHourWise,OtDayWise,OtMinsHrs,OTHRsMins,ShiftName,
--DefinedworkingHours,otMins,NormalOTMins,WeeklyoffOTMins,HolidayOTMins ,HrsWork ,HrsOT ,
--OffOT ,HolOT ,Employee_FirstName ,LevelName ,OverTimeStatus ,
--SelectedRecords ,SwipeCardNo,TitleName ,Gender
--update #tempFinalCompOff set compOffDays1=0 where CompOffHourDaywise = ''''
--select * from #tempFinalCompOff
--Remove the temporary tables here 
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
--drop table #EmpPay
drop table #LevelRights
drop table #TempProcessedData
drop table #tempHourwise
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListingByEmpId]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationListingByEmpId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  Karthikeyan.R
-- Create date: 08-Feb-2017
-- Description: <Description,,>  
-- Proc_TA_CompensationListing null,null,''01/01/1900'',''01/01/1900'',''Superadmin'',0
 -- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CompensationListingByEmpId]  
@Employee_Id int,
@GradeLevel varchar(20),
@fromdate datetime = ''01/01/1900'', 
@ToDate datetime = ''01/01/1900'',
@UserGroupName varchar(250),
@ParentId int
AS  
BEGIN
	SET NOCOUNT ON;  
	Declare @sqlQuery nvarchar(Max)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	declare @ELTodate as datetime
	if(@ToDate=''01/01/1900'')
	begin
		set @ELTodate=getdate()
	end
	else
	begin
		set @ELTodate=@ToDate
	end
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	 SET @sqlEmpLevel=
      ''INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
      from  (
      SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
      from TA_Tbl_EmployeeLevel el
      INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
      INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId ''
      set @sqlEmpLevel= @sqlEmpLevel +'' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
      INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ELTodate as nVARCHAR(50))+'''''', 102) and EL.LevelId is not null''      
	EXECUTE(@sqlEmpLevel)
	set @sqlQuery=''''  
	set @sqlQuery=''select OT.ExtraTime_Id ''''Compensation_Id'''',E.Employee_Code_Id as ''''Employee_ID'''',E.Employee_FirstName + '''' ''''+ isnull(E.Employee_LastName,'''''''') as Employee_FirstName ,
	case when ''+CONVERT(varchar,@dateFormat)+'' =106 then
		REPLACE(CONVERT(VARCHAR, OT.ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
	else CONVERT(VARCHAR, OT.ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') end as ApplicationDate,
	case when ''+CONVERT(varchar,@dateFormat)+'' =106 then
		REPLACE(CONVERT(VARCHAR, OT.Date,''+CONVERT(varchar,@dateFormat) + ''),'''' '''',''''-'''') 
	else CONVERT(VARCHAR, OT.Date, ''+CONVERT(varchar,@dateFormat)+'') end as FromDate,'''''''' Type,OT.Reason,OT.OverTimeStatus ''''Status'''',case	when OT.InTime<>''''00:00'''' then	case	when (''''''+CONVERT(varchar,@TimeFormat)+ '''''') =''''hh:mm'''' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.InTime,0)), 114)
															else	SUBSTRING(OT.InTime,13,5)+'''' '''' + SUBSTRING(OT.InTime,18,2) 
													end 
						else ''''''''
				end	InTime
	,
	case	when OT.OutTime<>''''00:00'''' then	case	when (''''''+CONVERT(varchar,@TimeFormat)+ '''''') =''''hh:mm'''' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.OutTime,0)), 114)
															else SUBSTRING(OT.OutTime,13,5)+'''' '''' + SUBSTRING(OT.OutTime,18,2)
													end 
						else ''''''''
				end	OutTime,OT.HrsExtra ''''WorkedHours'''',OT.DaysWorked ''''DayWorked'''',OT.OverTimeStatus ''''Comp_Status'''',Ta_Tbl_levelDetails.name as LevelName
	from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on OT.Employee_Id=E.Employee_Id 
	INNER JOIN TA_Tbl_EmployeeDesignation ON E.Employee_Id = TA_Tbl_EmployeeDesignation.EmployeeId 
	INNER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
	INNER JOIN TA_Tbl_Title ON TA_Tbl_Title.TitleId=TA_Tbl_EmployeeDesignation.DesignationId 
	INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId where OT.isRequest=1 and OT.isDelete=0 and E.Employee_Id = '''''' + cast(@Employee_Id as nvarchar(100))  + '''''' AND TA_Tbl_Grade.Grade_Level >='' + cast(@GradeLevel as nvarchar(100))  
	If not(@fromdate = ''01/01/1900'' and @ToDate = ''01/01/1900'')
		begin
			set @sqlQuery= @sqlQuery + '' and OT.Date>=CONVERT(DATETIME,''''''+cast(@fromdate as nvarchar(50))+'''''',102) ''  
			set @sqlQuery= @sqlQuery + '' and OT.Date<=CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''',102) ''  
		end
	set @sqlQuery= @sqlQuery + ''  order by OT.ExtraTime_Id desc''
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CompensationListing]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CompensationListing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================  
-- Author:  Karthikeyan.R
-- Create date: 08-Feb-2017
-- Description: <Description,,>  
-- Proc_TA_CompensationListing null,null,''01/01/1900'',''01/01/1900'',''Management'',0,3
-- select * from TA_Tbl_OverTimeStatus
 -- =============================================  
CREATE PROCEDURE [dbo].[Proc_TA_CompensationListing]  
 -- Add the parameters for the stored procedure here  
 @EmployeeFirstName nvarchar(MAX),  
 @EmployeeId nvarchar(MAX),  
 @fromdate nvarchar(40),  
 @ToDate nvarchar(40),
 @UserGroupName nvarchar(250),
 @ParentID int,
 @EmpAutoID int
AS  
BEGIN
	SET NOCOUNT ON;  
	Declare @sqlQuery nvarchar(Max)  
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId	
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(10)
	Select @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	Select @TimeFormat=TimeFormat from Func_TA_GetDateTimeFormat()
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	declare @ELTodate as datetime
	if(@ToDate=''01/01/1900'')
	begin
		set @ELTodate=getdate()
	end
	else
	begin
		set @ELTodate=@ToDate
	end
	DECLARE @sqlEmpLevel nVARCHAR(4000) 
	 SET @sqlEmpLevel=
      ''INSERT INTO #EmpLevel SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
      from  (
      SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
      from TA_Tbl_EmployeeLevel el
      INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
      INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId ''
      set @sqlEmpLevel= @sqlEmpLevel +'' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
      INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
      INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
      AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ELTodate as nVARCHAR(50))+'''''', 102) and EL.LevelId is not null''      
	EXECUTE(@sqlEmpLevel)
	--select * from #LevelRights
	--select * from #EmpLevel
	set @sqlQuery=''''  
	set @sqlQuery=''select  OT.ExtraTime_Id ''''Compensation_Id'''',E.Employee_Code_Id as ''''Employee_ID'''',E.Employee_FirstName + '''' ''''+ isnull(E.Employee_LastName,'''''''') as Employee_FirstName ,
	case when ''+CONVERT(varchar,@dateFormat)+'' =106 then
		REPLACE(CONVERT(VARCHAR, OT.ApplicationDate,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
	else CONVERT(VARCHAR, OT.ApplicationDate, ''+CONVERT(varchar,@dateFormat)+'') end as ApplicationDate,
	case when ''+CONVERT(varchar,@dateFormat)+'' =106 then
		REPLACE(CONVERT(VARCHAR, OT.Date,''+CONVERT(varchar,@dateFormat) + ''),'''' '''',''''-'''') 
	else CONVERT(VARCHAR, OT.Date, ''+CONVERT(varchar,@dateFormat)+'') end as FromDate,'''''''' Type,OT.Reason,OT.OverTimeStatus ''''Status'''',
	case	when OT.InTime<>''''00:00'''' then	case	when (''''''+CONVERT(varchar,@TimeFormat)+ '''''') =''''hh:mm'''' then 
	CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.InTime,0)), 114)
															else SUBSTRING(OT.InTime,13,5)+'''' '''' + SUBSTRING(OT.InTime,18,2)
													end 
						else ''''''''
				end	InTime
	,
	case	when OT.OutTime<>''''00:00'''' then	case	when (''''''+CONVERT(varchar,@TimeFormat)+ '''''') =''''hh:mm'''' then CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OT.OutTime,0)), 114)
															else	SUBSTRING(OT.OutTime,13,5)+'''' '''' + SUBSTRING(OT.OutTime,18,2) 
													end 
						else ''''''''
				end	OutTime
,OT.HrsExtra ''''WorkedHours'''',OT.DaysWorked ''''DayWorked'''',OT.OverTimeStatus ''''Comp_Status'''',Ta_Tbl_levelDetails.name as LevelName
	from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on OT.Employee_Id=E.Employee_Id  ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId where OT.isRequest=1 and OT.isDelete=0 ''
	if(@EmployeeFirstName<>'''')  
		Begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName +'''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeFirstName+''%'' as nvarchar(100)) + '''''')''
		End
	if(@EmployeeId<> '''')  
		Begin
			set @sqlQuery = @sqlQuery + '' and e.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(50)) + ''''''''
		End
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and e.Employee_ID IN (select * from #EmployeeIds) ''  
            END
	If not(@fromdate = ''01/01/1900'' and @ToDate = ''01/01/1900'')
		begin
			set @sqlQuery= @sqlQuery + '' and OT.Date>=CONVERT(DATETIME,''''''+cast(@fromdate as nvarchar(50))+'''''',102) ''  
			set @sqlQuery= @sqlQuery + '' and OT.Date<=CONVERT(DATETIME,''''''+cast(@ToDate as nvarchar(50))+'''''',102) ''  
		end
	set @sqlQuery= @sqlQuery + '' order by OT.ExtraTime_Id desc''
	--print @sqlQuery
	exec(@sqlQuery)
	drop table #LevelRights
	drop table #EmpLevel
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearsetting]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearsetting]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name 	: Proc_TA_DeleteYearsetting  50
Description 	: Save year settings details into table  
Tables Included : TA_Tbl_YearSetting  
Created By 	: Prabakaran  
Created On 	: 22-Nov-07  
Modified By 	:  
Modified On 	:  
*/  
CREATE   PROCEDURE [dbo].[Proc_TA_DeleteYearsetting]   
@YearSettingId  int
as  
--declare @RecordExiststing as int  
--set @RecordExiststing=(select count(*) From TA_Tbl_Yearsetting ys where ys.IsActive=0 
--and (Year(Getdate()) not between ys.StartYear and ys.EndYear) and ys.StartYear > Year(Getdate()) and ys.EndYear > Year(Getdate()) 
--and ys.YearSettings_Id=@YearSettingId)
--select @RecordExiststing
--if(@RecordExiststing>0)
begin
delete from ta_tbl_yearclosure where Year_SettingID=@YearSettingId
--end
--if(@RecordExiststing>0)
--begin
delete from TA_Tbl_Yearsetting where YearSettings_Id=@YearSettingId
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteYearClosuredetails]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteYearClosuredetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteYearClosuredetails] 
(
@YearsettingId int,
@EmployeeId int
)
as
DELETE FROM TA_TBL_YEARCLOSURE WHERE YEAR_SETTINGID=@YearsettingId AND EMPLOYEE_ID=@EmployeeId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteTitle]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteTitle]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteTitle]
		@Type CHAR(1),
		@TitleId INT,
		@TitleIds NVARCHAR(50)
	AS
	DECLARE @DEL VARCHAR
	SET @DEL=1
	DECLARE @Query NVARCHAR(2000)
	SET @Query=''''
IF (@Type=''I'')
	BEGIN
		UPDATE TA_Tbl_Title SET IsDeleted=@DEL WHERE TitleId=@TitleId
	END
ELSE IF (@Type=''C'')
	BEGIN
		SET @Query = ''UPDATE TA_Tbl_Title SET IsDeleted='' + @DEL + '' WHERE TitleId IN  ('' + @TitleIds + '')''
		EXEC (@Query)
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftRoaster]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftRoaster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftRoaster]  
(@ShiftRoasterId int)
AS
	BEGIN
		Delete from TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Id=@ShiftRoasterId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftPattern]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/* 
Created by	: 	Abul
Description	:	To delete a particular shift pattern using its pattern id  
Modified by	:	P.Prabakaran
Modified on	:	05-Feb-08
*/
CREATE      Proc [dbo].[Proc_TA_DeleteShiftPattern]
@ShiftPattern_Id int,
@Type CHAR(1),
@ShiftPattern_Ids varchar(1000)
As
DECLARE @DEL VARCHAR
SET @DEL=1
DECLARE @Query NVARCHAR(2000)
SET @Query=''''
	IF (@Type=''I'')
	-- I refers Individual record updation
		BEGIN
			update TA_Tbl_ShiftPattern set Isdeleted=@DEL where ShiftPattern_Id = @ShiftPattern_Id
		END
	ELSE IF (@Type=''M'')
	-- M refers Multilple records updation
		BEGIN
			SET @Query = ''UPDATE TA_Tbl_ShiftPattern SET IsDeleted='' + @DEL + '' WHERE ShiftPattern_Id IN  ('' + @ShiftPattern_Ids + '')''
			EXEC (@Query)
		END
	ELSE IF (@Type=''P'')
	--P refers Permanently delete the record
		BEGIN
			Delete from TA_Tbl_ShiftPattern where ShiftPattern_Id = @ShiftPattern_Id
		END
	--select * from ta_tbl_shiftPattern
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: Proc_TA_DeleteShiftHoliday_YrSettings  59
Description 	: Check for data available during delete of new year settings in shift and holiday if the data is not yet processed.
Tables Included : TA_Tbl_YearSetting  
Created By 	: Gopinath  
*/   
CREATE PROCEDURE [dbo].[Proc_TA_DeleteShiftHoliday_YrSettings]
	@YearSettingId  int
as  
begin
	SET NOCOUNT ON;
	Declare @StartMonth as int
	Declare @EndMonth as int
	declare @StartYear as int
	Declare @EndYear as int
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @RowCount as bigint
	Select @StartYear = Year(Fromdate), @EndYear = Year(Todate), @StartMonth = Month(Fromdate),@EndMonth = Month(Todate),
	@StartDate = Fromdate, @EndDate = Todate from ta_tbl_yearsetting where YearSettings_ID = @YearSettingId
	Set @RowCount = (select Count(*) from ta_tbl_processeddata where Date between @StartDate and @EndDate)
	--select @StartYear,@EndYear,@StartMonth,@EndMonth,@StartDate,@EndDate,@RowCount
	if(@RowCount = 0)
	BEGIN
		DELETE ta_tbl_permanentshiftAllocation where ((year=@StartYear and month>=@StartMonth) or (year=@EndYear and month<=@EndMonth)) 
		DELETE ta_tbl_holidaysettings where YearSettingID = @YearSettingId
		Delete TA_Tbl_HolidayChildTable where holiday_id in 
	   (Select Holiday_ID from ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate)
		DELETE ta_tbl_holiday where Holiday_FromDate between @StartDate and @EndDate and  Holiday_ToDate between @StartDate and @EndDate
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeleteMonthCloseDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeleteMonthCloseDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_DeleteMonthCloseDetails]
(
	@MonthCloseID INT
)
AS
BEGIN
	UPDATE TA_Tbl_MonthClosure SET Isdeleted=0 WHERE MonthClosure_Id=@MonthCloseID
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Approvaldatacount]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Approvaldatacount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Gopinath.k, 19Jun15
-- Description:	To fetch data apprval count data for dashboard.
-- Proc_Approvaldatacount '''','''',0,0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Approvaldatacount]
	@FROMDATE datetime,
	@TODATE datetime,
	@ShiftID int,
	@ParentID int
AS
BEGIN
	SET NOCOUNT ON;
	Declare @FromdateString varchar(20)
	Declare @Union varchar(max)
	set @Union='' Union All ''
	Declare @Approveddata varchar(max)
		if @FROMDATE=''''
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,GETDATE()))+''-''+CONVERT(varchar(20),DATEPART(month,getdate()))+''-''+
			case when len(CONVERT(varchar(20),DATEPART(D,GETDATE())))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,GETDATE()))
			else CONVERT(varchar(20),DATEPART(D,GETDATE())) end
		end	
	else
		begin
			set @FromdateString=CONVERT(varchar(20),DATEPART(YEAR,@FROMDATE))+''-''+CONVERT(varchar(20),DATEPART(month,@fromdate))+''-''+
			case when len(CONVERT(varchar(20),DATEPART(D,@fromdate)))=1 then ''0''+CONVERT(varchar(20),DATEPART(D,@fromdate))
			else CONVERT(varchar(20),DATEPART(D,@fromdate)) end
		end
	create table #LevelRights(LevelId int)
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](''SuperAdmin'',@ParentID) as LevelId
		Declare @sqlEmpLevel nvarchar(4000)	
	set @sqlEmpLevel=
		''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
		 select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
		 inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
		 inner join #LevelRights on #LevelRights.LevelId=el.LevelId
		 where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
		 inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
		 inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
		 AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@TODATE as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	execute(@sqlEmpLevel)	
	-- OnDuty Data
	set @Approveddata =''SELECT DISTINCT ''''Approved OnDuty'''' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],1 AS HYPER, ''''OnDuty'''' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= ''''''+convert(varchar(max),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  <= ''''''+convert(varchar(max),@TODATE)+'''''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' '' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Forwarded OnDuty'''' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],2 AS HYPER, ''''OnDuty'''' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= ''''''+convert(varchar(max),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  <= ''''''+convert(varchar(max),@TODATE)+'''''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''''Forward'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Pending OnDuty'''' AS TOPIC,COUNT(M.ManualTimeEntry_InDate) [COUNT],3 AS HYPER, ''''OnDuty'''' AS REPORTNAME FROM Ta_Tbl_ManualTimeEntry M
	Inner join TA_Tbl_Employee E on E.SwipeCardNo=M.ManualTimeEntry_Employee_Id 
	Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
	Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
	WHERE (M.ManualTimeEntry_InDate >= ''''''+convert(varchar(max),@FromdateString)+'''''') AND (M.ManualTimeEntry_OutDate  <= ''''''+convert(varchar(max),@FromdateString)+'''''') AND M.IsOnDuty=1 
	and M.ManualTimeEntry_Status =''''Pending'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
-- Permission Data
	set @Approveddata =''SELECT DISTINCT ''''Approved Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],4 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' '' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Forwarded Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],5 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Forward'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Pending Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],6 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Pending'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
-- Leave Data
	set @Approveddata =''SELECT DISTINCT ''''Approved Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],4 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Approved'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' '' 
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Forwarded Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],5 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Forward'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Pending Permission'''' AS TOPIC, COUNT(P.Permission_Date) [COUNT],6 AS HYPER, ''''Permission'''' AS REPORTNAME FROM TA_Tbl_Permission P
Inner join TA_Tbl_Employee E on E.Employee_Id=P.Employee_Id
Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
WHERE (P.Permission_Date >=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.Permission_Date <=''''''+convert(varchar(max),@FromdateString)+'''''') AND ISNULL(P.IsDeleted,0)=0 and
P.Permission_Status !=''''Pending'''' AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+''SELECT DISTINCT ''''Approved Leave'''' AS TOPIC, COUNT(P.DATE) [COUNT],3 AS HYPER, ''''Leave'''' AS REPORTNAME FROM TA_TBL_PROCESSEDDATA P
			Inner join TA_Tbl_Employee E on E.SwipeCardNo=P.Employee_Code_Id 
			Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id
			Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id
			WHERE (P.DATE>=''''''+convert(varchar(max),@FromdateString)+'''''') AND (P.DATE<=''''''+convert(varchar(max),@FromdateString)+'''''') AND (ANATTENDANCECODE not in(''''PRESENT'''',''''Absent'''',''''Weekly Off'''',''''RH'''') AND FNAttendanceCode not in(''''Present'''',''''Absent'''',''''Weekly Off'''',''''RH''''))
			AND E.Report_Exclude=0 and E.Isdeleted=0 and E.Employee_Status=1 and E.Employee_Code_Id<>''''18000000'''' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'' ''
	set @Approveddata=@Approveddata+@Union
	set @Approveddata=@Approveddata+'' ''
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Pro_Update_RouteMaster_BYId]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Pro_Update_RouteMaster_BYId]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Pro_Update_RouteMaster_BYId  
Description : update route master by ID 
Tables Included : TA_Tbl_RouteMaster  
Created By : Arun Vinoth  
Created On : 14-Aug-2007
Modified By :  
Modified On :  
*/  
CREATE Procedure [dbo].[Pro_Update_RouteMaster_BYId] (@routeId int) As
 Update TA_Tbl_RouteMaster set IsMapped=''1'' where [id]=@routeId
' 
END
GO
/****** Object:  StoredProcedure [dbo].[ImportOvertTimeData]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ImportOvertTimeData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-June-2019 12:58 PM>
-- Description:	<Import OverTime data>
/*
ImportOvertTimeData
''<dsOverTime>  
  <dtOvertime>
    <Sl.no>3</Sl.no>
    <Employee_Code_Id>22028636</Employee_Code_Id>
    <Employee_FirstName>Ishmila Bahadoor</Employee_FirstName>
    <LevelName>Human Resources-Plastics</LevelName>
    <date>7/1/2019</date>
    <HrsOT>1:52</HrsOT>
    <ActHrsOT>2:00</ActHrsOT>
    <OffOT>0:00</OffOT>
    <ActOffOT>0:00</ActOffOT>
    <HolOT>0:00</HolOT>
    <ActHolOT>0:00</ActHolOT>
    <SPEC_NormOT1>0:00</SPEC_NormOT1>
    <Modified_Spec_NormOTHrs1>0:00</Modified_Spec_NormOTHrs1>
    <SPEC_NormOT2>0:00</SPEC_NormOT2>
    <Modified_Spec_NormOTHrs2>0:00</Modified_Spec_NormOTHrs2>
    <SPEC_OffOT1>0:00</SPEC_OffOT1>
    <Modified_Spec_OffOTHrs1>0:00</Modified_Spec_OffOTHrs1>
    <SPEC_OffOT2>0:00</SPEC_OffOT2>
    <Modified_Spec_OffOTHrs2>0:00</Modified_Spec_OffOTHrs2>
    <SPEC_HOLOT1>0:00</SPEC_HOLOT1>
    <Modified_Spec_HolOTHrs1>0:00</Modified_Spec_HolOTHrs1>
    <SPEC_HOLOT2>0:00</SPEC_HOLOT2>
    <Modified_Spec_HolOTHrs2>0:00</Modified_Spec_HolOTHrs2>
    <OverTimeStatus>Pending</OverTimeStatus>
  </dtOvertime>  
</dsOverTime>'',1,''superadmin''
*/
-- =============================================
CREATE PROCEDURE [dbo].[ImportOvertTimeData]
	@OverTimeData XML = NULL,
	@EmpAutoID bigInt,
	@UserGroup VARCHAR(max)
AS
BEGIN
	Declare @OverTimeData1 XML = @OverTimeData
	Declare	@EmpAutoID1 bigInt=@EmpAutoID
	Declare @UserGroup1 VARCHAR(max)=@UserGroup
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)
	BEGIN TRY
		BEGIN TRAN ImportOverTimeData
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @OverTimeData1	
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@UserGroup1,0) AS LEVELID			
			DECLARE @SQLEMPLEVEL			NVARCHAR(4000)			
			SET @SQLEMPLEVEL=
			''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
			SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''
			EXECUTE(@SQLEMPLEVEL)			
			INSERT INTO Proc_ImportOvertime
			SELECT Tbl.*, case	when isnull(tbl.Employee_Code_Id,'''')='''' then 1 
								when isnull(e.Employee_Code_Id,'''')='''' then 2
								when E.CompOff_Eligible=1 then 3
								when (isnull(HrsOT,'''')='''' or 
								isnull(ActHrsOT,'''')='''' or 
								isnull(OffOT,'''')='''' or 
								isnull(ActOffOT,'''')='''' or 
								isnull(HolOT,'''')='''' or 
								isnull(ActHolOT,'''')='''' or 
								isnull(SPEC_NormOT1,'''')='''' or 
								isnull(Modified_Spec_NormOTHrs1,'''')='''' or 
								isnull(SPEC_NormOT2,'''')='''' or 
								isnull(Modified_Spec_NormOTHrs2,'''')='''' or 
								isnull(SPEC_OffOT1,'''')='''' or 
								isnull(Modified_Spec_OffOTHrs1,'''')='''' or 
								isnull(SPEC_OffOT2,'''')='''' or 
								isnull(Modified_Spec_OffOTHrs2,'''')='''' or 
								isnull(SPEC_HOLOT1,'''')='''' or 
								isnull(Modified_Spec_HolOTHrs1,'''')='''' or 
								isnull(SPEC_HOLOT2,'''')='''' or 
								isnull(Modified_Spec_HolOTHrs2,'''')='''') then 4
								when (CHARINDEX('':'',HrsOT)=0 or 
								CHARINDEX('':'',ActHrsOT)=0 or 
								CHARINDEX('':'',OffOT)=0 or 
								CHARINDEX('':'',ActOffOT)=0 or 
								CHARINDEX('':'',HolOT)=0 or 
								CHARINDEX('':'',ActHolOT)=0 or 
								CHARINDEX('':'',SPEC_NormOT1)=0 or 
								CHARINDEX('':'',Modified_Spec_NormOTHrs1)=0 or 
								CHARINDEX('':'',SPEC_NormOT2)=0 or 
								CHARINDEX('':'',Modified_Spec_NormOTHrs2)=0 or 
								CHARINDEX('':'',SPEC_OffOT1)=0 or 
								CHARINDEX('':'',Modified_Spec_OffOTHrs1)=0 or 
								CHARINDEX('':'',SPEC_OffOT2)=0 or 
								CHARINDEX('':'',Modified_Spec_OffOTHrs2)=0 or 
								CHARINDEX('':'',SPEC_HOLOT1)=0 or 
								CHARINDEX('':'',Modified_Spec_HolOTHrs1)=0 or 
								CHARINDEX('':'',SPEC_HOLOT2)=0 or 
								CHARINDEX('':'',Modified_Spec_HolOTHrs2)=0) then 5
								when (CONVERT(DATETIME,ActHrsOT)>CONVERT(DATETIME,HrsOT)	or
									  CONVERT(DATETIME,ActOffOT)>CONVERT(DATETIME,OffOT) or
									  CONVERT(DATETIME,ActHolOT)>CONVERT(DATETIME,HolOT) or 
									  CONVERT(DATETIME,Modified_Spec_NormOTHrs1)>CONVERT(DATETIME,SPEC_NormOT1) or 
									  CONVERT(DATETIME,Modified_Spec_NormOTHrs2)>CONVERT(DATETIME,SPEC_NormOT2) or 
									  CONVERT(DATETIME,Modified_Spec_OffOTHrs1)>CONVERT(DATETIME,SPEC_OffOT1) or 
									  CONVERT(DATETIME,Modified_Spec_OffOTHrs2)>CONVERT(DATETIME,SPEC_OffOT2) or 
									  CONVERT(DATETIME,Modified_Spec_HolOTHrs1)>CONVERT(DATETIME,SPEC_HOLOT1) or 
									  CONVERT(DATETIME,Modified_Spec_HolOTHrs2)>CONVERT(DATETIME,SPEC_HOLOT2)) then 6
							end			
			FROM OPENXML (@XMLParams, ''/dsOverTime/dtOvertime'', 2) WITH 
			(
				[Sl.no] VARCHAR(20), 
				Employee_Code_Id VARCHAR(20), 
				Employee_FirstName VARCHAR(max), 
				LevelName VARCHAR(max), 
				date VARCHAR(20), 
				HrsOT VARCHAR(20), 
				ActHrsOT VARCHAR(20), 
				OffOT VARCHAR(20), 
				ActOffOT VARCHAR(20), 
				HolOT VARCHAR(20), 
				ActHolOT VARCHAR(20), 
				SPEC_NormOT1 VARCHAR(20), 
				Modified_Spec_NormOTHrs1 VARCHAR(20), 
				SPEC_NormOT2 VARCHAR(20), 
				Modified_Spec_NormOTHrs2 VARCHAR(20), 
				SPEC_OffOT1 VARCHAR(20), 
				Modified_Spec_OffOTHrs1 VARCHAR(20), 
				SPEC_OffOT2 VARCHAR(20), 
				Modified_Spec_OffOTHrs2 VARCHAR(20), 
				SPEC_HOLOT1 VARCHAR(20), 
				Modified_Spec_HolOTHrs1 VARCHAR(20), 
				SPEC_HOLOT2 VARCHAR(20), 
				Modified_Spec_HolOTHrs2 VARCHAR(20), 
				OverTimeStatus VARCHAR(20)
			) Tbl			
			LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employee_Code_Id
			AND E.IsDeleted = 0 AND E.Employee_Status = 1
			EXEC SP_XML_RemoveDocument @XMLParams
			IF NOT EXISTS(SELECT Employee_Code_Id FROM Proc_ImportOvertime)
			BEGIN
				SET @ErrMsg = ''There is no record in the file;<br />''
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
			END
			--select * from Proc_ImportOvertime
			IF NOT EXISTS(select Employee_Code_Id from Proc_ImportOvertime where Error!=0)
			BEGIN
				Insert into @ErrorMsg
				select [Sl.no], Employee_Code_Id,'''',0,date from Proc_ImportOvertime where error=0
				IF EXISTS(SELECT t.Employee_Code_Id FROM Proc_ImportOvertime t INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (isnull(EL.EMPLOYEEID,'''')=''''))
				BEGIN
					set @alertMsg=''Employee is not available or you are not having an previlege to import overtime data for this employee;<br />''				
					UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
															Else @alertMsg
													END,
					flag=0 FROM @ErrorMsg EM
					INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid				
					INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
					LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (isnull(EL.EMPLOYEEID,'''')='''')
				END
				IF NOT EXISTS(SELECT top 1 [Employee_Id] FROM @ErrorMsg WHERE flag=0)
				BEGIN						
					create table #tempEmployeeid(autoid int identity(1,1),Employee_Code_Id varchar(50))
					insert into #tempEmployeeid
					select distinct Employee_Code_Id from Proc_ImportOvertime where ISNULL(Employee_Code_Id, '''') != ''''
					Declare @count int
					Declare @start int
					set @start=1
					select @count=count(Employee_Code_Id) from #tempEmployeeid 
					while @start<=@count
					begin
							Declare @filterEmpid varchar(50)
							select @filterEmpid=Employee_Code_Id from #tempEmployeeid where autoid=@start
							Declare @Error int
							set @Error=0
							IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (TOT.Employee_Code_Id=@filterEmpid and @Error=0) and OtMins=0 AND tot.HrsOT!=''00:00'' AND TOT.HrsOT!=''0:00'')
							BEGIN
								SET @alertMsg=''Normal day - Overtime hours is not calculated by system for this date, but mentioned in excel sheet;<br />''				
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		ELSE @alertMsg
																END,
								flag=0 
								--select * 
								FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (t.Employee_Code_Id=@filterEmpid and @Error=0) and OtMins=0 AND t.HrsOT!=''00:00'' AND t.HrsOT!=''0:00''
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_NormOTMins1=0 AND TOT.SPEC_NormOT1!=''00:00'' AND TOT.SPEC_NormOT1!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg=''Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />''			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)				
								WHERE (pd.SPEC_NormOTMins1=0 AND t.SPEC_NormOT1!=''00:00'' AND t.SPEC_NormOT1!=''0:00'')and  t.Employee_Code_Id=@filterEmpid								
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_NormOTMins2=0 AND TOT.SPEC_NormOT2!=''00:00'' AND TOT.SPEC_NormOT2!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg=''Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />''	
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)				
								WHERE (pd.SPEC_NormOTMins2=0 AND t.SPEC_NormOT2!=''00:00'' AND t.SPEC_NormOT2!=''0:00'') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_OffOTMins1=0 AND TOT.SPEC_OffOT1!=''00:00'' AND TOT.SPEC_OffOT1!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)
							BEGIN
								SET @alertMsg=''Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />''			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_OffOTMins1=0 AND t.SPEC_OffOT1!=''00:00'' AND t.SPEC_OffOT1!=''0:00'') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_OffOTMins2=0 AND TOT.SPEC_OffOT2!=''00:00'' AND TOT.SPEC_OffOT2!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)							
							BEGIN
								SET @alertMsg=''Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />''			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_OffOTMins2=0 AND t.SPEC_OffOT2!=''00:00'' AND t.SPEC_OffOT2!=''0:00'') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_HOLOTMins1=0 AND TOT.SPEC_HOLOT1!=''00:00'' AND TOT.SPEC_HOLOT1!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)
							--WHERE ((ISNULL(PD.SPEC_HOLOT1,'''')='''' OR PD.SPEC_HOLOT1=''00:00'') AND TOT.SPEC_HOLOT1!=''00:00'' AND TOT.SPEC_HOLOT1!=''0:00'')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
							BEGIN
								SET @alertMsg=''Special Overtime hours 1 is not calculated by system for this date, but mentioned in excel sheet;<br />''			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_HOLOTMins1=0 AND t.SPEC_HOLOT1!=''00:00'' AND t.SPEC_HOLOT1!=''0:00'') and  t.Employee_Code_Id=@filterEmpid
							END
							ELSE IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
							INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
							WHERE (pd.SPEC_HOLOTMins2=0 AND TOT.SPEC_HOLOT2!=''00:00'' AND TOT.SPEC_HOLOT2!=''0:00'') and  TOT.Employee_Code_Id=@filterEmpid)
							--WHERE ((ISNULL(PD.SPEC_HOLOT2,'''')='''' OR PD.SPEC_HOLOT2=''00:00'') AND TOT.SPEC_HOLOT2!=''00:00'' AND TOT.SPEC_HOLOT2!=''0:00'')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
							BEGIN
								SET @alertMsg=''Special Overtime hours 2 is not calculated by system for this date, but mentioned in excel sheet;<br />''			
								UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																END,
								flag=0 FROM @ErrorMsg EM
								INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
								INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
								WHERE (pd.SPEC_HOLOTMins2=0 AND t.SPEC_HOLOT2!=''00:00'' AND t.SPEC_HOLOT2!=''0:00'') and  t.Employee_Code_Id=@filterEmpid
							END									
							ELSE if(@UserGroup1!=''Superadmin'')
							BEGIN
								IF EXISTS(SELECT TOT.Employee_Code_Id FROM TA_Tbl_ProcessedData PD 
								INNER JOIN Proc_ImportOvertime TOT ON (PD.Employee_Code_Id=TOT.Employee_Code_Id AND PD.Date=TOT.date)
								WHERE (PD.OvertimeStatus=''Approved'')and  TOT.Employee_Code_Id=@filterEmpid and @Error=0)
								BEGIN
									SET @alertMsg=''Approved Overtime hours can''''t be modified;<br />''
									UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
																		Else @alertMsg
																	END,
									flag=0 FROM @ErrorMsg EM
									INNER JOIN Proc_ImportOvertime t on EM.RecordID=t.autoid	
									INNER JOIN TA_Tbl_ProcessedData PD ON (PD.Employee_Code_Id=T.Employee_Code_Id AND PD.Date=T.date)
									WHERE (PD.OvertimeStatus=''Approved'') and  t.Employee_Code_Id=@filterEmpid
									and ISNULL(t.Employee_Code_Id, '''') != ''''
									set @Error=1
								END
							END
							set @start=@start+1
						end				
				end
			END
			ELSE
			BEGIN				
				insert into @ErrorMsg 
				select [Sl.no], Employee_Code_Id,
				case when error=1 then ''Employee ID is missing''
					 when error=2 then ''Employee is not available in Timecheck''
					 when error=3 then ''Overtime is not eligible''
					 when error=4 then ''Overtime is not specified in this row''
					 when error=5 then ''Time format is not correct''
					 when error=6 then ''Modified hours should not be greater than actual hours''
				end,0,date from Proc_ImportOvertime where error!=0
			END
			IF NOT EXISTS(SELECT top 1 [Employee_Id] FROM @ErrorMsg WHERE flag=0)
			BEGIN
				UPDATE TA_Tbl_ProcessedData SET 
				--select 
				ActHrsOT=''00:00'',
				ActNormOT=CASE WHEN LEN(tot.HrsOT)<5 THEN RIGHT(''00'' + tot.HrsOT,5) else tot.HrsOT end,
				ActNormOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HrsOT)))*60+
							  SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.HrsOT))),
				ActOffOT=CASE WHEN LEN(tot.OffOT)<5 THEN RIGHT(''00'' + tot.OffOT,5) else tot.OffOT end,				
				ActOffOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.OffOT)))*60+
							 SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.OffOT))+1,LEN(CONVERT(VARCHAR(20),tot.OffOT))),
				ActHolOT=CASE WHEN LEN(tot.HolOT)<5 THEN RIGHT(''00'' + tot.HolOT,5) else tot.HolOT end,
				ActHolOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HolOT)))*60+
							 SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HolOT))+1,LEN(CONVERT(VARCHAR(20),tot.HolOT))),
				NormOT=CASE WHEN LEN(tot.ActHrsOT)<5 THEN RIGHT(''00'' + tot.ActHrsOT,5) else tot.ActHrsOT end,
				OffOT=CASE WHEN LEN(tot.ActOffOT)<5 THEN RIGHT(''00'' + tot.ActOffOT,5) else tot.ActOffOT end,
				HolOT=CASE WHEN LEN(tot.ActHolOT)<5 THEN RIGHT(''00'' + tot.ActHolOT,5) else tot.ActHolOT end,
				OtMins=SUBSTRING(CONVERT(VARCHAR(20),tot.ActHrsOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActHrsOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHrsOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActHrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActHrsOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActOffOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActOffOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActOffOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActOffOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActOffOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHolOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActHolOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.ActHolOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.ActHolOT))+1,LEN(CONVERT(VARCHAR(20),tot.ActHolOT))),
				ActOTMins=SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HrsOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HrsOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HrsOT))+1,LEN(CONVERT(VARCHAR(20),tot.HrsOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.OffOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.OffOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.OffOT))+1,LEN(CONVERT(VARCHAR(20),tot.OffOT)))+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HolOT)))*60+
					   SUBSTRING(CONVERT(VARCHAR(20),tot.HolOT),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.HolOT))+1,LEN(CONVERT(VARCHAR(20),tot.HolOT)))
				FROM TA_Tbl_ProcessedData pd
				inner join Proc_ImportOvertime tot on (pd.Employee_code_id=tot.Employee_Code_Id and pd.Date=tot.date)
				-- Data is available
				UPDATE Ta_tbl_specialOvertimeDetails SET
				Modified_Spec_NormOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))),
				Modified_Spec_NormOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))),
				Modified_Spec_OffOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))),
				Modified_Spec_OffOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))),
				Modified_Spec_HolOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))),
				Modified_Spec_HolOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))),
				Modified_Spec_NormOTHrs1	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs1)<5 THEN RIGHT(''00'' + tot.Modified_Spec_NormOTHrs1,5) else tot.Modified_Spec_NormOTHrs1 end,
				Modified_Spec_NormOTHrs2	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_NormOTHrs2,5) else tot.Modified_Spec_NormOTHrs2 end,
				Modified_Spec_OffOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs1)<5 THEN RIGHT(''00'' +tot.Modified_Spec_OffOTHrs1,5) else tot.Modified_Spec_OffOTHrs1 end,
				Modified_Spec_OffOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_OffOTHrs2,5) else tot.Modified_Spec_OffOTHrs2 end,
				Modified_Spec_HolOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs1)<5 THEN RIGHT(''00'' +tot.Modified_Spec_HolOTHrs1,5) else tot.Modified_Spec_HolOTHrs1 end,
				Modified_Spec_HolOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_HolOTHrs2,5) else tot.Modified_Spec_HolOTHrs2 end,
				Modified_By=@EmpAutoID1,
				Modified_Date=GETDATE()
				FROM Ta_tbl_specialOvertimeDetails sot
				inner join Proc_ImportOvertime tot on (sot.Employee_code_id=tot.Employee_Code_Id and sot.Date=tot.date)				
				-- Data is not available
				INSERT INTO Ta_tbl_specialOvertimeDetails
				(Employee_code_id,Date,Modified_Spec_NormOTMins1,Modified_Spec_NormOTMins2,Modified_Spec_OffOTMins1,Modified_Spec_OffOTMins2,
				Modified_Spec_HolOTMins1,Modified_Spec_HolOTMins2,Modified_Spec_NormOTHrs1,
				Modified_Spec_NormOTHrs2,Modified_Spec_OffOTHrs1,Modified_Spec_OffOTHrs2,Modified_Spec_HolOTHrs1,Modified_Spec_HolOTHrs2,
				Inserted_By,Inserted_Date)
				select 	
				tot.Employee_Code_Id,
				tot.date,
				Modified_Spec_NormOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs1))),
				Modified_Spec_NormOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_NormOTHrs2))),
				Modified_Spec_OffOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs1))),
				Modified_Spec_OffOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_OffOTHrs2))),
				Modified_Spec_HolOTMins1	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs1))),
				Modified_Spec_HolOTMins2	=SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),0,CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2)))*60+
											 SUBSTRING(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2),CHARINDEX('':'',CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))+1,LEN(CONVERT(VARCHAR(20),tot.Modified_Spec_HolOTHrs2))),
				Modified_Spec_NormOTHrs1	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs1)<5 THEN RIGHT(''00'' + tot.Modified_Spec_NormOTHrs1,5) else tot.Modified_Spec_NormOTHrs1 end,
				Modified_Spec_NormOTHrs2	=CASE WHEN LEN(tot.Modified_Spec_NormOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_NormOTHrs2,5) else tot.Modified_Spec_NormOTHrs2 end,
				Modified_Spec_OffOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs1)<5 THEN RIGHT(''00'' +tot.Modified_Spec_OffOTHrs1,5) else tot.Modified_Spec_OffOTHrs1 end,
				Modified_Spec_OffOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_OffOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_OffOTHrs2,5) else tot.Modified_Spec_OffOTHrs2 end,
				Modified_Spec_HolOTHrs1		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs1)<5 THEN RIGHT(''00'' +tot.Modified_Spec_HolOTHrs1,5) else tot.Modified_Spec_HolOTHrs1 end,
				Modified_Spec_HolOTHrs2		=CASE WHEN LEN(tot.Modified_Spec_HolOTHrs2)<5 THEN RIGHT(''00'' +tot.Modified_Spec_HolOTHrs2,5) else tot.Modified_Spec_HolOTHrs2 end,
				@EmpAutoID1,GETDATE()
				FROM Proc_ImportOvertime tot
				LEFT OUTER JOIN Ta_tbl_specialOvertimeDetails sot on (sot.Employee_code_id=tot.Employee_Code_Id and sot.Date=tot.date)
				WHERE sot.Employee_code_id IS NULL
			END
			ELSE 
			BEGIN
				SELECT	RecordID,
						Employee_Id, 
						Error_Msg,
						date
				FROM @ErrorMsg where flag=0
			END
			delete from Proc_ImportOvertime
		COMMIT TRAN ImportOverTimeData
			SELECT ''Msg:DataImportedSuccessfully'' [Message]
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportOverTimeData
		RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
	END CATCH
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[GetPreviousLeaveApplicationDaysValues]    Script Date: 03/25/2021 10:22:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetPreviousLeaveApplicationDaysValues]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <09-Apr-2019>
-- Description:	<Get the previously availe leave total count value details>
-- [GetPreviousLeaveApplicationDaysValues] 4
-- =============================================
CREATE PROCEDURE [dbo].[GetPreviousLeaveApplicationDaysValues]
	@LeaveAppID bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @YearSettingId INT
	SELECT @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where IsActive=1
	Declare @EarnedLeave decimal(18,1)
	Declare @LOP decimal(18,1)
	Declare @LeaveBal decimal(18,1)
	Declare @WaiveOff decimal(18,1)
	CREATE TABLE #Temp(Employee_id bigint,EarnedLeave decimal(18,1),LOP decimal(18,1),LeaveBal decimal(18,1),WaiveOff decimal(18,1))
	Declare @Employee_id bigint
	select @Employee_id=Employee_Id from TA_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveAppID
	Insert into #Temp(Employee_id)values(@Employee_id)
	--select * from #Temp
	update T set LeaveBal=a.NumberOfDays from #Temp T inner join
	(
		select	yc.Employee_id,NumberOfDays=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))
		from TA_tbl_Yearclosure yc  
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
		inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
		left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
		and la.Status  not in (''Rejected'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'')
		and la.LeaveApplication_Id<@LeaveAppID  
		and la.IsBorrow=0 group by yc.Employee_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
	)as a on a.Employee_Id=T.Employee_id
	update T set EarnedLeave=b.ELNumberOfDays,LOP=b.LOPNumberOfDays,WaiveOff=b.WONumberOfDays from #Temp T inner join
	(
		select ELNumberOfDays=sum(ELNumberOfDays),WONumberOfDays=sum(WONumberOfDays),LOPNumberOfDays=sum(LOPNumberOfDays),Employee_Id from
		( 
			select  ELNumberOfDays=case when lt.LeaveType=''EL'' and la.Type!=''LOP'' then la.NumberOfDays else 0 end,
					WONumberOfDays=case when lt.LeaveType=''WO'' then la.NumberOfDays else 0 end,
					LOPNumberOfDays=case when la.Type=''LOP'' then la.NumberOfDays else 0 end,
					Employee_Id from TA_Tbl_LeaveApplication la
			inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
			where la.Status  not in (''Rejected'') and la.IsDeleted=0
			and la.LeaveApplication_Id<@LeaveAppID
		)as a group by Employee_Id
	)as b on b.Employee_Id=T.Employee_id
	select	@EarnedLeave=EarnedLeave,@LOP=LOP,@LeaveBal=LeaveBal,@WaiveOff=WaiveOff from #Temp
	Declare @ConcernName varchar(500)
	--select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id
	select top 1 @ConcernName=name from Ta_Tbl_levelDetails where description in(select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id)
	select	LeaveTaken=(isnull(@EarnedLeave,0)+isnull(@LOP,0)+isnull(@WaiveOff,0)),
			EarnedLeave=isnull(@EarnedLeave,0),
			LOP=isnull(@LOP,0),
			LeaveBal=isnull(@LeaveBal,0),
			WaiveOff=isnull(@WaiveOff,0),
			ConcernName=isnull(@ConcernName,'''')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeOTSanction]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeOTSanction]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_EmployeeOTSanction  
Description : To get the OT Employee with Approval Status
Tables Included : TA_Tbl_Employee,TA_Tbl_ProcessedData,TA_Tbl_EmployeeLevel,Ta_Tbl_levelDetails,TA_Tbl_EmployeeCategory
				  TA_Tbl_Category,TA_Tbl_EmployeeType,TA_Tbl_EmployeePay,TA_Tbl_Type,TA_Tbl_EmployeeDesignation,TA_Tbl_Title
				  TA_Tbl_Grade,ta_tbl_shift
Created By : Sasireka  
Created On : 08-Jan-2009 
Modified By :  Karthikeyan.R
Modified On :  14-Mar-2017
*/  
-- [Proc_TA_EmployeeOTSanction] 1,''2019/05/01'',''2019/05/01'','''','''',''0'','''','''',''SuperAdmin'',''1'',''All'','''',0,''compoff''
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeOTSanction]
(
	@Employee_ID int,
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@EmployeeName varchar(50),
	@LevelID varchar(8000),
	@employeeCategory int, 
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),
	@Status varchar(50),
    @EmpSwipeCard varchar(20),
    @ParentId int,
    @SanctionType varchar(25)   
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and EL.LevelId is not null
	--select * from #EmpLevel
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102) and ED.DesignationId is not null
	--select * from #EmpDesignation
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)  and EType.TypeId is not null
	--select * from #EmpType
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
	declare @GetLevelID as int
	declare @TopLevelId as int
	set @GetLevelID=(select top 1 LevelId from #EmpLevel)
	DECLARE @childID INT 
		;WITH ParentLevel AS
		(
			SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails WHERE id = @GetLevelID
			UNION ALL
			SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
			INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
		)
	SELECT TOP 1 @TopLevelId=id
	FROM ParentLevel r
	--inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
	ORDER BY lvl DESC
	--select @TopLevelId
	--update TA_Tbl_ShiftSettings set isRequestingforCompOff=1
	declare @isRequestCompOff nvarchar(10)
	select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=@TopLevelId
	if(@isRequestCompOff is null or @isRequestCompOff='''')
	BEGIN
		select @isRequestCompOff=isRequestingforCompOff from TA_Tbl_ShiftSettings where CompanyId=-1
	END
	CREATE TABLE #TempProcessedData
			(
				[Process_Rec_ID] bigint,
				[Employee_Code_Id] nvarchar(20),
				[Date] datetime,
				[Shift_Id] int,
				[InTime] nvarchar(25),
				[OutTime] nvarchar(25),
				[HrsWork] nvarchar(10),
				[HrsOT] nvarchar(10),
				[NormOT] nvarchar(10),
				[OffOT] nvarchar(10),
				[HolOT] nvarchar(10),
				[EarlyOut] nvarchar(10),
				[LateIn] nvarchar(10),
				[Attendance] nvarchar(20),
				[WorkHrs] nvarchar(10),
				[HrsLess] nvarchar(10),
				[HrsExtra] nvarchar(10),
				[LateInMins] float,
				[EarlyOutMins] float,
				[ExtraMins] float,
				[OtMins] float,
				[OvertimeStatus] nvarchar(50),
				[TotalDays] numeric(18, 1),
				[LeaveCode] nvarchar(20),
				[LateEntryReason] nvarchar(260),
				[EarlyOutReason] nvarchar(260),
				[ProcessFlag] bit,
				[Status] nvarchar(50),
				[FNAttendanceCode] nvarchar(15),
				[ANAttendanceCode] nvarchar(15),
				[ActHrsOT] nvarchar(10),
				[ActNormOT] nvarchar(10),
				[ActOffOT] nvarchar(10),
				[ActHolOT] nvarchar(10),
				[ActOtMins] float,
				[AvailOtMins] float,
				[ExtraTime_Id] bigint,
				
				-----
				SPEC_NormOT1	varchar(10),
				SPEC_NormOTMins1	int,
				SPEC_NormOT2	varchar(10),
				SPEC_NormOTMins2	int,
				SPEC_OffOT1		varchar(10),
				SPEC_OffOTMins1	int,
				SPEC_OffOT2		varchar(10),
				SPEC_OffOTMins2	int,
				SPEC_HOLOT1		varchar(10),
				SPEC_HOLOTMins1	int,
				SPEC_HOLOT2		varchar(10),
				SPEC_HOLOTMins2	int,			
				
				Modified_Spec_NormOTMins1 int,
				Modified_Spec_NormOTMins2 int,
				Modified_Spec_OffOTMins1 int,
				Modified_Spec_OffOTMins2 int,
				Modified_Spec_HolOTMins1 int,
				Modified_Spec_HolOTMins2 int,
				Modified_Spec_NormOTHrs1 varchar(10),
				Modified_Spec_NormOTHrs2 varchar(10),
				Modified_Spec_OffOTHrs1 varchar(10),
				Modified_Spec_OffOTHrs2 varchar(10),
				Modified_Spec_HolOTHrs1 varchar(10),
				Modified_Spec_HolOTHrs2 varchar(10)
		  )
		if(@isRequestCompOff=0 or @SanctionType = ''OverTime'')
			BEGIN
				update TA_Tbl_ProcessedData set 
				OvertimeStatus=OT.OvertimeStatus from TA_Tbl_OverTimeStatus OT inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id where OT.isDelete=0 and OT.isRequest=1
			  
				insert into #TempProcessedData 
				select [Process_Rec_ID],PD.[Employee_Code_Id],pd.[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],
				[EarlyOut],[LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],
				[OvertimeStatus],[TotalDays],[LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[ActHrsOT],[ActNormOT],[ActOffOT],[ActHolOT],[ActOtMins],case when ISNULL(ActOTMins,0)=0 then [OtMins] else ActOTMins end,0,
				PD.SPEC_NormOT1,
				PD.SPEC_NormOTMins1,
				PD.SPEC_NormOT2,
				PD.SPEC_NormOTMins2,
				PD.SPEC_OffOT1,
				PD.SPEC_OffOTMins1,
				PD.SPEC_OffOT2,
				PD.SPEC_OffOTMins2,
				PD.SPEC_HOLOT1,
				PD.SPEC_HOLOTMins1,
				PD.SPEC_HOLOT2,
				PD.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2
				from TA_Tbl_ProcessedData PD
				inner join TA_Tbl_Employee e on PD.Employee_Code_Id=e.SwipeCardNo
				inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
				Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
				where (OtMins <> 0 or ActOTMins <> 0)  and 
				pd.[Date] between @fromDat and @ToDat 
			END
		Else
			BEGIN
				insert into #TempProcessedData 
				select OT.Process_RecID as ''Process_Rec_ID'',E.Employee_Code_Id,OT.Date,p.Shift_Id,
				P.InTime,P.OutTime,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,OT.HrsExtra,
				p.EarlyOut,p.LateIn,p.Attendance,p.WorkHrs,p.HrsLess,p.HrsExtra,p.LateInMins,p.EarlyOutMins,
				p.ExtraMins,p.OtMins,OT.OverTimeStatus,p.TotalDays,p.LeaveCode,p.LateEntryReason,p.EarlyOutReason,
				p.ProcessFlag,p.Status,p.FNAttendanceCode,p.ANAttendanceCode,p.ActHrsOT,p.ActNormOT,p.ActOffOT,p.ActHolOT,
				p.ActOtMins,OT.ExtraMins,OT.ExtraTime_Id,
				P.SPEC_NormOT1,
				P.SPEC_NormOTMins1,
				P.SPEC_NormOT2,
				P.SPEC_NormOTMins2,
				P.SPEC_OffOT1,
				P.SPEC_OffOTMins1,
				P.SPEC_OffOT2,
				P.SPEC_OffOTMins2,
				P.SPEC_HOLOT1,
				P.SPEC_HOLOTMins1,
				P.SPEC_HOLOT2,
				P.SPEC_HOLOTMins2,
				spot.Modified_Spec_NormOTMins1,
				spot.Modified_Spec_NormOTMins2,
				spot.Modified_Spec_OffOTMins1,
				spot.Modified_Spec_OffOTMins2,
				spot.Modified_Spec_HolOTMins1,
				spot.Modified_Spec_HolOTMins2,
				spot.Modified_Spec_NormOTHrs1,
				spot.Modified_Spec_NormOTHrs2,
				spot.Modified_Spec_OffOTHrs1,
				spot.Modified_Spec_OffOTHrs2,
				spot.Modified_Spec_HolOTHrs1,
				spot.Modified_Spec_HolOTHrs2				
				from TA_Tbl_OverTimeStatus OT 
				inner join TA_Tbl_Employee E on E.Employee_Id=OT.Employee_Id 
				inner join TA_Tbl_ProcessedData P on OT.Date=P.Date and E.Employee_Code_Id=P.Employee_Code_Id  
				inner join #EmpLevel on #EmpLevel.EmployeeId=e.Employee_Id
				Left outer join Ta_tbl_specialOvertimeDetails spot on P.Employee_Code_Id=spot.Employee_code_id	
				where P.[Date] between @fromDat and @ToDat and OT.isDelete=0 and OT.isRequest=1
			END	
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''	
	set @sqlQuery = @sqlQuery + ''select 
	E.Employee_Code_Id,
	E.Employee_FirstName + space(1) + isnull(E.employee_lastname,'''''''') as Employee_FirstName,
	replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''')  AS [Level Name],
	convert(varchar(20),TPD.Date,101) as date,
	TPD.NormOt as HrsOT,
	ISNULL(TPD.ActNormOT,TPD.NormOt) ActHrsOT,
	TPD.OffOT,
	ISNULL(TPD.ActOffOT,TPD.OffOT) ActOffOT,
	TPD.HolOT,
	ISNULL(TPD.ActHolOT,TPD.HolOT) ActHolOT,
	SPEC_NormOT1,
	Modified_Spec_NormOTHrs1=ISNULL(Modified_Spec_NormOTHrs1,SPEC_NormOT1),
	SPEC_NormOT2,
	Modified_Spec_NormOTHrs2=ISNULL(Modified_Spec_NormOTHrs2,SPEC_NormOT2),
	SPEC_OffOT1,
	Modified_Spec_OffOTHrs1=ISNULL(Modified_Spec_OffOTHrs1,SPEC_OffOT1),
	SPEC_OffOT2,
	Modified_Spec_OffOTHrs2=ISNULL(Modified_Spec_OffOTHrs2,SPEC_OffOT2),
	SPEC_HOLOT1,
	Modified_Spec_HolOTHrs1=ISNULL(Modified_Spec_HolOTHrs1,SPEC_HOLOT1),
	SPEC_HOLOT2,	
	Modified_Spec_HolOTHrs2=ISNULL(Modified_Spec_HolOTHrs2,SPEC_HOLOT2),
	ISNULL(TPD.OverTimeStatus,''''Pending'''') as OverTimeStatus, 	
	E.Employee_Id,TPD.OTMins,
	''''0'''' as SelectedRecords,
	ISNULL(TPD.ActOtMins,TPD.OtMins) ActOtMins,''+@isRequestCompOff +'' as isRequestCompOff,TPD.ExtraTime_Id,	
	TPD.Process_Rec_ID,
	TPD.shift_id,
	TPD.HrsWork 
	from #TempProcessedData TPD 
	INNER JOIN Ta_Tbl_Employee E on TPD.Employee_Code_Id=E.SwipeCardNo''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''	 
	set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN ta_tbl_shift ON TPD.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' where TPD.AvailOtMins <> 0 ''
	if(@SanctionType = ''OverTime'')
		begin
			set @sqlQuery = @sqlQuery + '' AND E.OT_Eligible = 1 AND E.CompOff_Eligible = 0 ''
		end
	ELSE IF(@SanctionType = ''compoff'')
		BEGIN
			set @sqlQuery = @sqlQuery + '' AND E.CompOff_Eligible = 1 AND E.OT_Eligible = 0 ''
		END	
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end
	set @sqlQuery = @sqlQuery + '' And E.isdeleted=0 and E.report_exclude=0 and E.employee_status=1''
	if not(@EmployeeName='''')
	begin
			set @sqlQuery = @sqlQuery + '' and (E.Employee_FirstName + '''' '''' + isnull(E.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if(@employeeCategory<>0)
	begin
		set @sqlQuery = @sqlQuery +'' and #EmpCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8))
	end
	if(@employeeType<>0)
	begin
		set @sqlQuery = @sqlQuery + '' and #EmpType.TypeId = '' + cast(@employeeType as nvarchar(8))
	end
	if not (@empId='''')
	begin
			set @sqlQuery = @sqlQuery + '' and E.Employee_Code_Id = '''''' + cast (@empId as nvarchar(50)) + '''''' ''
	end
	If Not (@EmpSwipeCard = '''')
    Begin  
		  Set @sqlQuery = @sqlQuery + '' And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End
	if not(@status='''' or @status=''All'')
	begin
	 	IF(@status = ''Pending'')
			BEGIN
				set @sqlQuery = @sqlQuery + '' AND (TPD.OvertimeStatus IS NULL OR TPD.OvertimeStatus = '''''' + @status + '''''')''
			END
		ELSE
			BEGIN
		        set @sqlQuery = @sqlQuery + '' AND TPD.OvertimeStatus = '''''' + @status + ''''''''
			END
	end 
	set @sqlQuery = @sqlQuery + '' order by Employee_Code_Id , Date''
	exec (@sqlQuery)
	drop table #TempProcessedData
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForUpdate]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForUpdate]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Proc_TA_EmployeeDetailsForUpdate ''A'' , '''' , '''',''1,2,3,47,113,132,133,134,136,135'',''2''
CREATE      PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForUpdate]
@type CHAR(1)='''',
@EmployeeName NVARCHAR(50)='''',
@UserGroupName NVARCHAR(250),
@UserLevels nvarchar(2000),
@GradeLevel nvarchar(20),
@ParentId int 
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
--selecting Employee for Grid
declare @Query as varchar(7000)
IF @type=''A''
BEGIN
	IF(@UserGroupName=''SuperAdmin'')
			BEGIN
					set @Query= ''SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''''''') as Employee_FirstName, E.Employee_Status, T.TitleName,E.SwipeCardNo,E.Isdeleted	''
					set @Query= @Query +'' FROM TA_Tbl_Employee E''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
                    set @Query= @Query +'' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid''
					set @Query= @Query +'' WHERE E.Employee_Firstname<>''''Administrator'''' AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id)  ''
					set @Query= @Query +'' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)''
					--set @Query= @Query +'' and TA_Tbl_EmployeeLevel.Levelid in ('' + @UserLevels + '')''
			END
	ELSE
			BEGIN
					set @Query= ''SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''''''') as Employee_FirstName,E.Employee_Status,T.TitleName,E.SwipeCardNo,E.Isdeleted''
					set @Query= @Query +'' FROM TA_Tbl_Employee E''			
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''
					set @Query =@Query +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
					set @Query= @Query +'' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid''
					set @Query= @Query +'' WHERE E.IsDeleted=0 and Employee_Firstname<>''''Administrator'''' AND EDesig.EffectiveDate=(Select Max(EffectiveDate) from TA_Tbl_EmployeeDesignation where EmployeeId=E.Employee_Id)  ''
					set @Query= @Query +'' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)''
					--set @Query= @Query +'' and TA_Tbl_EmployeeLevel.Levelid in ('' + @UserLevels + '')''
					set @Query= @Query +'' and TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
			END
exec(@Query)
--selecting employee using search option
END
ELSE IF @type=''N''
BEGIN
	IF(@UserGroupName=''SuperAdmin'')
			BEGIN
					set @Query= ''SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''''''') as Employee_FirstName,E.Employee_Status,T.TitleName''
					set @Query= @Query +'' FROM TA_Tbl_Employee E''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
					set @Query= @Query +'' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid''
					set @Query= @Query +'' WHERE Employee_FirstName LIKE '''''' + @EmployeeName +''+%''''  and Employee_Firstname<>''''Administrator'''' ''
					set @Query= @Query +'' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)''
					--set @Query= @Query +'' and TA_Tbl_EmployeeLevel.Levelid in ('' + @UserLevels + '')''
			END
	ELSE
			BEGIN
					set @Query= ''SELECT E.Employee_Id,E.Employee_Code_Id,E.Employee_FirstName + space(1) + ISNULL( E.Employee_LastName,'''''''') as Employee_FirstName,E.Employee_Status,T.TitleName''
					set @Query= @Query +'' FROM TA_Tbl_Employee E''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id''
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId''
					set @Query =@Query +'' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId ''					
					set @Query= @Query +'' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''					
					set @Query= @Query +'' INNER JOIN #LevelRights ON #LevelRights.LevelId = TA_Tbl_EmployeeLevel.Levelid''
					set @Query= @Query +'' WHERE E.IsDeleted=0 AND Employee_FirstName LIKE '''''' + @EmployeeName + ''+%''''  and Employee_Firstname<>''''Administrator'''' ''
					set @Query= @Query +'' and TA_Tbl_EmployeeLevel.EffectiveDate = (select top 1 EffectiveDate from TA_Tbl_EmployeeLevel where  EmployeeId = E.Employee_Id AND EffectiveDate <=CONVERT(DATETIME,getdate(), 102) order by EffectiveDate desc)''
					--set @Query= @Query +'' and TA_Tbl_EmployeeLevel.Levelid in ('' + @UserLevels + '')''
					set @Query= @Query +'' and TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
			END
			drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForSearch]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForSearch]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
exec Proc_TA_EmployeeDetailsForSearch @EmployeeName=N'''',@empId=N'''',@UserGroupName=N''SuperAdmin'',
@UserLevel=''10'',@GradeLevel=N''0'',@SwipeOpt=''Select'',@EmpSwipeCard='''',@ParentId=0,@LoginEmployeeAutoId=1,@ApplnMode=1,@Filter= 10
,@EmployeeCategory=0,@employeetype=1,@Gender=''Both'',@EmpAutoID=1,@ScheduleID=0,@FilterUserGroup=0,@LeavePolicy=0,@Reportingto=0,@ApprovalAuthority=0,@EmailAvail=0
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForSearch]    
(    
	@EmployeeName			NVARCHAR(MAX)='''',
	@empId					NVARCHAR(MAX)='''',
	@UserGroupName			NVARCHAR(250),
	@UserLevel				VARCHAR(8000),
	@GradeLevel				NVARCHAR(20) ,
	@SwipeOpt				VARCHAR(25),
	@EmpSwipeCard			VARCHAR(20),
	@ParentId				INT,
	@LoginEmployeeAutoId	INT,
	@ApplnMode				BIT,
	@Filter					INT,
	@EmployeeCategory		INT,
	@EmployeeType			INT,
	@Gender					VARCHAR(10),
	@EmpAutoID int,
	@ScheduleID int		=	null,	
	@FilterUserGroup int,  
	@LeavePolicy int,  
    @Reportingto int,  
    @ApprovalAuthority int, 
    @EmailAvail int 
)    
AS
BEGIN 
	--insert into TestingEmployee values
	--(
	--	@EmployeeName,
	--	@empId		,
	--	@UserGroupName,
	--	@UserLevel	,
	--	@GradeLevel	,
	--	@SwipeOpt	,
	--	@EmpSwipeCard,
	--	@ParentId	,
	--	@LoginEmployeeAutoId	,
	--	@ApplnMode				,
	--	@Filter					,
	--	@EmployeeCategory		,
	--	@EmployeeType			,
	--	@Gender					,
	--	@EmpAutoID ,
	--	@ScheduleID ,
	--	@FilterUserGroup ,
	--	@LeavePolicy ,
	--	@Reportingto ,
	--	@ApprovalAuthority ,
	--	@EmailAvail 
	--)
	SET NOCOUNT ON;
	DECLARE @IndividualUserStatus int
	DECLARE @sql AS VARCHAR(8000) 	
	DECLARE @EmpId_Numeric table (EmployeeCodeId VARCHAR(15))
	CREATE table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) AS LevelId
	CREATE table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	CREATE table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	CREATE table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	CREATE table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id VARCHAR(50),SwipeCard VARCHAR(50))
	declare @isReportingto as int
	
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!=''Superadmin'' and @isReportingto=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
    CREATE table #EmployeeID(EmployeeID VARCHAR(25))
    CREATE table #EmployeeName(EmployeeID VARCHAR(25))
    
	if(@empId is not null and @empId <> '''')
		begin			
			insert into #EmployeeID
			select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin			
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from 
	(
		select max(el.EffectiveDate) AS EffectiveDate,el.EmployeeId from TA_Tbl_EmployeeLevel el  
		inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id   
		INNER JOIN #LevelRights LR ON LR.LevelId=el.LevelId
		Left outer JOIN #EmployeeID TEmpID ON TEmpID.EmployeeID=Employee_Code_Id 
		Left Outer JOIN #EmployeeName TEmpName ON TEmpName.EmployeeID=Employee_Code_Id
		left outer join TA_Tbl_Emp_LeavePolicyDetails LP on emp.Employee_Id=LP.EmpID
		Where 1=1
		and
		(
			(@Filter=0) or 
			(@Filter=1 and OT_Eligible=1 and CompOff_Eligible=0) or 
			(@Filter=2 and OT_Eligible=0 and CompOff_Eligible=1) or
			(@Filter=3 and OT_Eligible=1 and CompOff_Eligible=1) or
			(@Filter=4 and LP.Policy_Id is null)  or
			(@Filter=5 and Employee_Status=0) or
			(@Filter=6 and Hostel=1) or
			(@Filter=7 and Report_Exclude=1) or
			(@Filter=8 and (UserGroup_Id is null or UserGroup_Id='''')) or
			(@Filter=9 and OT_Eligible=0 and CompOff_Eligible=0) or
			(@Filter=10 and Employee_Status=1)			
		)
		and(@Gender=''Both'' or Gender=@Gender)
		and(@isReportingto=0 or (Employee_ID IN (select * from #EmployeeIds)))
		and(ISNULL(@empId,'''')='''' or (Employee_Code_Id IN (select EmployeeID from #EmployeeID)))
		and(ISNULL(@EmployeeName,'''')='''' or (Employee_Code_Id IN (select * from #EmployeeName)))
		group by el.EmployeeId
	) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from 
	(
		select max(ed.EffectiveDate) AS EffectiveDate,ed.EmployeeId AS EmployeeId from TA_Tbl_EmployeeDesignation ed
		inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		group by ed.EmployeeId
	) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	and ED.DesignationId is not null
	
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(ec.EffectiveDate) AS EffectiveDate,ec.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeCategory ec
		inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeCategory,0)=0 or ec.CategoryId=@EmployeeCategory)
		group by ec.EmployeeId,Employee_Code_Id,emp.SwipeCardNo 
	) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
	(
		select max(et.EffectiveDate) AS EffectiveDate,et.EmployeeId AS EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
		inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
		INNER JOIN #EmpLevel EL ON emp.Employee_Id=EL.EmployeeId 
		where (isnull(@EmployeeType,0)=0 or et.TypeId=@EmployeeType)
		group by et.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	and EType.TypeId is not null
	
	insert into @EmpId_Numeric 
	select Employee_code_Id  AS EmpId from TA_Tbl_Employee 
	INNER JOIN #EmpLevel EL ON TA_Tbl_Employee.Employee_Id=EL.EmployeeId 
	where TA_Tbl_Employee.Employee_Firstname<>''Administrator'' and PatIndex(''%[^0-9]%'',Employee_code_Id) = 0 order by EmpId ASc
	
	select @IndividualUserStatus=IndividualUsers from TA_Tbl_Usergroup where groupName=@UserGroupName and isDeleted=0
	IF(@ApplnMode = 0)
		BEGIN
			DECLARE @Deleted int	
			IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[UpdateTrigTA_Tbl_Employee]''))
			begin
				DISABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
				SET @Deleted=1
			end			
			UPDATE TA_Tbl_Employee SET
			Isdeleted = 1,
			Employee_Status = 0,
			InActiveDate = DATEADD(D, 1, DateOfJoining)
			WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> ''18000000'') AND
			Employee_Code_Id <> ''18000000'' AND ISNULL(InActive_Status, 0) = 0
			if @Deleted=1
				begin
					ENABLE TRIGGER UpdateTrigTA_Tbl_Employee ON TA_Tbl_Employee
				end
		END
		

	Create table #Temp_TA_Tbl_EmailScheduled_Employees(Employee_id int,ScheduleId int)
	Insert into #Temp_TA_Tbl_EmailScheduled_Employees
	select Employee_id,ScheduleId from TA_Tbl_EmailScheduled_Employees where ScheduleId=@ScheduleID
	SELECT	E.Employee_Id,
			E.Employee_Code_Id,
			E.Employee_FirstName + '' ''+ isnull(E.Employee_LastName,'''')AS Employee_FirstName,
			case when E.Employee_Status=1 then ''Active'' else ''InActive'' end Employee_Status,
			case when E.IsDeleted=1 then ''True'' else ''False'' end Isdeleted,
			T.TitleName,
			case when isnull(ESE.Employee_id,0)=0 then 0 else 1 end emailScheduler_flag,
			E.EmailId,
			E.Mobile_number,
			E.SwipeCardNo,
			E.Contact_Address,
			groupName, 
			E.Father_name,
			E.Mother_name,
			E.DateofBirth,
			E.DateofBirth_Record,
			E.Blood_Group,
			E.Permanent_Address,
			E.Phone_Number,
			E.Mobile_Number,
			E.Gender,
			E.Marital_status,
			E.Personal_mailid,
			E.Passport_No,
			E.Passport_expirydate,
			E.Visa_No,
			E.Visa_expirydate,
			E.Vehicle_No,
			E.Anniversary_Date,
			E.DateOfJoining,
			Reporting_To=ER.Employee_Code_Id + '' - ''+ ER.Employee_FirstName + '' ''+ isnull(ER.Employee_LastName,''''),
			Leave_Sanc_Authority=ES.Employee_Code_Id + '' - ''+es.Employee_FirstName + '' ''+ isnull(es.Employee_LastName,''''),
			CompOff_Eligible=case when E.CompOff_Eligible=1 then ''Yes'' else ''No'' end,
			OT_Eligible=case when E.OT_Eligible=1 then ''Yes'' else ''No'' end,
			Report_Exclude=case when E.Report_Exclude=1 then ''Yes'' else ''No'' end,
			E.InActiveDate,
			E.CustomField1,
			E.CustomField2,
			E.CustomField3,
			E.CustomField4,
			E.CustomField5,
			[Imported]=case when E.IsImported=1 then ''Yes'' else ''No'' end,
			MobileClockIn=case when E.MobileClockInOUt=1 then ''Yes'' else ''No'' end,
			DepartmentName=ld.name,
			C.CategoryName,
			Typ.TypeName,
			E.Time_Stamp as CreatedDate
			FROM TA_Tbl_Employee E
			inner JOIN #EmpDesignation EDesig ON EDesig.EmployeeID= E.Employee_Id
			inner JOIN #EmpLevel ON E.Employee_Id = #EmpLevel.EmployeeId
			inner JOIN TA_Tbl_Title T ON T.TitleId=EDesig.DesignationId
			INNER JOIN TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId
			Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId
			inner join Ta_Tbl_levelDetails ld on #LevelRights.LevelId=ld.id
			left outer join #EmpType on #EmpType.employeeid=e.Employee_Id
			inner join TA_Tbl_Type typ on typ.TypeId=#EmpType.TypeId
			left outer join #Temp_TA_Tbl_EmailScheduled_Employees ESE on ESE.Employee_id=e.Employee_Id
			left outer join #EmpCategory on #EmpCategory.employeeid=e.Employee_Id
			inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
			left outer join ta_tbl_usergroup ug on E.UserGroup_Id=ug.groupId
			left outer join TA_Tbl_Employee er on e.Reporting_To=er.Employee_Id
			left outer join TA_Tbl_Employee es on e.Leave_Sanc_Authority=es.Employee_Id
			WHERE E.Employee_FirstName<>''Administrator'' and (ESE.ScheduleId is null or ESE.ScheduleId = @ScheduleID)
			and(@SwipeOpt=''Not Exists'' or e.swipecardno is not null and e.swipecardno!='''')
			and(@UserGroupName=''Superadmin'' or TA_Tbl_Grade.Grade_Level>=@GradeLevel)
			and(ISNULL(@FilterUserGroup,0)=0 or E.UserGroup_Id= @FilterUserGroup)
			and(ISNULL(@Reportingto,0)=0 or E.Reporting_To=@Reportingto)
			and(ISNULL(@ApprovalAuthority,0)=0 or E.Leave_Sanc_Authority=@ApprovalAuthority)
			and(ISNULL(@EmailAvail,0)=0 or (@EmailAvail=1 and E.EmailId is not null and E.EmailId<>'''') or (@EmailAvail=2 and (E.EmailId is null or E.EmailId='''' )))
			and(isnull(@IndividualUserStatus,0)=0 or E.Employee_Id =@IndividualUserStatus)
			ORDER BY E.Employee_Id	
	drop table #EmpLevel      
	drop table #LevelRights
	drop table #EmpDesignation	 
	drop table #EmployeeID
	drop table #EmployeeName
	drop table #EmpCategory
	drop table #EmpType
	drop table #Temp_TA_Tbl_EmailScheduled_Employees
	drop table #EmployeeIds
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[proc_TA_EarlyExit]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[proc_TA_EarlyExit]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- proc_TA_EarlyExit ''01/Jan/2017'',''30/jun/2017'','''',0,'''',''0'',''0'',''0'',''SuperAdmin'',0,'''',0,0,''Both'',1,''''
-- Modified by : Gopinath
-- Modified Date : 19-Dec-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
CREATE  PROCEDURE [dbo].[proc_TA_EarlyExit]  
(  
	 @fromDat datetime,  
	 @ToDat datetime,  
	 @empId varchar(100),  
	 @shift int,  
	 @EmployeeName varchar(50),  
	 @LevelID varchar(8000),
	 @EmployeeCategory int,	   
	 @EmployeeType int,
	 @UserGroupName varchar(250),
	 @GradeLevel varchar(20),
	 @EmpSwipeCard varchar(20),
	 @ParentId int,
	 @DesignationID int,
	 @Gender varchar(10),
	 @ExportType int,
	 @MINExceptionHOURS AS VARCHAR(6),
	 @EmpAutoID int
)  
AS  
BEGIN  
	SET NOCOUNT ON;
	Declare @local_fromDat datetime
	Declare @local_ToDat datetime
	Declare @local_empId varchar(100)
	Declare @local_shift int
	Declare @local_EmployeeName varchar(50)
	Declare @local_LevelID varchar(8000)
	Declare @local_EmployeeCategory int
	Declare @local_EmployeeType int
	Declare @local_UserGroupName varchar(250)
	Declare @local_GradeLevel varchar(20)
	Declare @local_EmpSwipeCard varchar(20)
	Declare @local_ParentId int
	Declare @local_DesignationID int
	Declare @local_Gender varchar(10)
	Declare @local_ExportType int
	Declare @local_MINExceptionHOURS AS VARCHAR(6)
	Declare @local_EmpAutoID int
	
	Set @local_fromDat=@fromDat
	Set @local_ToDat=@ToDat
	Set @local_empId=@empId
	Set @local_shift=@shift
	Set @local_EmployeeName=@EmployeeName
	Set @local_LevelID=@LevelID
	Set @local_EmployeeCategory=@EmployeeCategory
	Set @local_EmployeeType=@EmployeeType
	Set @local_UserGroupName=@UserGroupName
	Set @local_EmpSwipeCard=@EmpSwipeCard
	Set @local_ParentId=@ParentId
	Set @local_DesignationID=@DesignationID
	Set @local_Gender=@Gender
	Set @local_ExportType=@ExportType
	Set @local_MINExceptionHOURS=@MINExceptionHOURS
	Set @local_EmpAutoID=@EmpAutoID
	Set @local_GradeLevel=@GradeLevel
	 
	Declare @RowCountEmployeeID int
	Declare @RowCountEmployeeName int
	Declare @RowCountSwipeCardNo int
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@local_UserGroupName,@local_ParentId) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@local_UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@local_EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@local_EmpAutoID) as EmpAutoId
	DECLARE @TOTALExceptionMIN AS INT  
	SET @TOTALExceptionMIN = SUBSTRING(@local_MINExceptionHOURS,0,CHARINDEX('':'',@local_MINExceptionHOURS))*60 + SUBSTRING(@local_MINExceptionHOURS,CHARINDEX('':'',@local_MINExceptionHOURS)+1,2)
	create table #TempProcessedData
	(
		EmpAutoId bigint,
		Date datetime,
		Employee_Code_Id varchar(50),
		InTime nvarchar(30),
		OutTime nvarchar(30),
		Shift_Id int,
		EarlyOut nvarchar(20),
		EarlyOutReason nvarchar(Max),
		EarlyOutMins float,
		Process_Rec_ID bigint,
		Shift_EndTime nvarchar(20)
	)
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData] 
	(
		[Employee_Code_Id] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @local_ToDat,@local_empId,@local_DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @local_ToDat,@local_empId,@local_EmployeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @local_ToDat,@local_empId,@local_EmployeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @local_ToDat,@local_empId
	if(@local_EmployeeName is not null and @local_EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@local_EmployeeName,'','')
		end
	if(@local_empId is not null and @local_empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@local_empId)
		end	
    create table #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo varchar(20))
	Declare @sqlTempProcessedData varchar(8000)
	set @sqlTempProcessedData= ''insert into #TempEmployee select Employee_ID,SwipeCardNo from TA_Tbl_Employee
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	If Not (@local_empId = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@local_EmployeeName = '''')  
		Begin  
			SET @sqlTempProcessedData = @sqlTempProcessedData + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlTempProcessedData = @sqlTempProcessedData + '' where SwipeCardNo is not null and dbo.TA_Tbl_Employee.IsDeleted = ''''0''''  and dbo.TA_Tbl_Employee.report_exclude=0 ''
	if(@local_Gender<>''Both'')
		begin
			set @sqlTempProcessedData = @sqlTempProcessedData + '' and TA_Tbl_Employee.Gender = '''''' + cast(@local_Gender as nvarchar(8)) + '''''' ''
		end	
	if(@isReportingto > 0)
            BEGIN
               set @sqlTempProcessedData = @sqlTempProcessedData + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	Execute(@sqlTempProcessedData)
	Declare @sqlTempProcessedData1 varchar(max)
	set @sqlTempProcessedData1= ''insert into #TempProcessedData
	select	#TempEmployee.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Shift_Id,
			PD.EarlyOut,
			PD.EarlyOutReason,
			PD.EarlyOutMins,
			PD.Process_Rec_ID,
			PD.Shift_EndTime
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployee on #TempEmployee.EmpSwipeCardNo=PD.Employee_Code_Id
    where (PD.Date >= CONVERT(DATETIME,''''''+cast( @local_fromDat as nvarchar(50))+'''''', 102))  
	AND (PD.Date <= CONVERT(DATETIME,''''''+cast(@local_ToDat as nvarchar(50))+'''''', 102)) 
	AND PD.EarlyOut <> ''''0'''' and PD.EarlyOut <> ''''00:00:00'''' and PD.EarlyOut <> ''''00:00''''
	and PD.EarlyOut is not null AND EarlyOutMins > 0 AND OutTime is not null AND OutTime <>'''''''' AND OutTime <> ''''0'''' AND OutTime <> ''''00:00'''' and processflag=1 ''
	if(@local_shift<>0)  
		begin  
			Set @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' and PD.shift_id= ''+  cast (@local_shift as nvarchar(50))
		end
	IF (@local_MINExceptionHOURS<>'''')  
		BEGIN  
			SET @sqlTempProcessedData1 = @sqlTempProcessedData1 + '' AND PD.EarlyOutMins >= '' + CAST(@TOTALExceptionMIN AS NVARCHAR(8))
		END
	Execute(@sqlTempProcessedData1)
	DECLARE @dateFormat as int
	DECLARE @TimeFormat as nvarchar(25)
	Select @dateFormat=dateformat,@TimeFormat=timeformat from Func_TA_GetDateTimeFormat()
	declare @sqlQuery as varchar(max)  
	set @sqlQuery = ''''   
	
	
	
	set @sqlQuery = @sqlQuery + '' select	dbo.TA_Tbl_Employee.Employee_Code_Id,
											(dbo.TA_Tbl_Employee.Employee_FirstName + space(1) + isnull(dbo.TA_Tbl_Employee.employee_lastname,'''''''')) as Employee_FirstName,
											replace(Ta_tbl_LevelDetails.Name,''''&amp;'''',''''&'''') as LevelName, 
											replace(Ta_tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName,											
											
											case when ''+cast(@dateFormat as varchar(100))+''=106 then
											REPLACE(CONVERT(VARCHAR, #TempProcessedData.Date,''+cast(@dateFormat as varchar(100))+''),''+'''''' ''''''+'',''+''''''-''''''+'') 
											else CONVERT(VARCHAR, #TempProcessedData.Date, ''+cast(@dateFormat as varchar(100))+'') end as date,
											ta_tbl_shift.shift_shortName,
											#TempProcessedData.Shift_EndTime as shiftOut ,
											CASE	WHEN (''''''+convert(varchar(10),@TIMEFORMAT)+'''''')=''''HH:MM'''' THEN CONVERT(VARCHAR(8),DATEADD(MINUTE,0,CONVERT(DATETIME,OutTime,0)), 114) 
													ELSE OutTime
											END OutTime,
											#TempProcessedData.EarlyOut,											
											#TempProcessedData.EarlyOutReason as Reason,
											#TempProcessedData.Process_Rec_ID,
											#EmpLevel.LevelId,											 
											#TempProcessedData.shift_id,''  
	set @sqlQuery = @sqlQuery + ''	TA_Tbl_Employee.Gender,
									EarlyOutMins,
									#TempProcessedData.Date as format FROM  #TempProcessedData INNER JOIN dbo.TA_Tbl_Employee ON #TempProcessedData.EmpAutoId = dbo.TA_Tbl_Employee.Employee_ID ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID''
	set @sqlQuery = @sqlQuery + '' INNER JOIN ta_tbl_shift ON #TempProcessedData.shift_id = dbo.ta_tbl_shift.shift_id ''  
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.employeeid = TA_Tbl_Employee.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.employeeid = TA_Tbl_Employee.Employee_Id ''
	if(@RowCountEmployeeID >0)
		begin
			Set @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		end
	if(@RowCountSwipeCardNo >0)
		begin
			Set @sqlQuery = @sqlQuery + '' INNER JOIN #SwipeCardNo on #SwipeCardNo.SwipeCardNo=TA_Tbl_Employee.SwipeCardNo ''
		end	
	set @sqlQuery = @sqlQuery + '' where 
	((dbo.TA_Tbl_Employee.employee_status=1)
	or
	(dbo.TA_Tbl_Employee.employee_status=0 and convert(nvarchar(11),dbo.TA_Tbl_Employee.InActiveDate,102)>=convert(nvarchar(11),#TempProcessedData.Date,102))
	) ''
	if(@local_UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @local_GradeLevel  
		end
	set  @sqlQuery = @sqlQuery + ''  order by #TempProcessedData.Employee_Code_Id,#TempProcessedData.Date''  
	 if(@local_ExportType=1)
		begin
			Exec(@sqlQuery)   
		end
	else
	begin
		Create table #TempEarlyExit
		(
			Employee_Code_Id nvarchar(30),
			[Employee_FirstName] nvarchar(100),
			LevelName nvarchar(100),
			designation nvarchar(100),
			Date nvarchar(20),
			shift_shortName nvarchar(4),
			shiftOut nvarchar(20),
			OutTime nvarchar(20),
			EarlyOut nvarchar(20),
			Reason nvarchar(max),
			Peocess_Rec_ID int,
			Levelid int,
			shift_id int,
			Gender nvarchar(10),
			EarlyOutMins decimal(18,2),
			format datetime
		)
		insert into #TempEarlyExit exec (@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempLevelName 
		select distinct LevelName from #TempEarlyExit
		insert into #TempDate 
		select distinct CAST(format as datetime),Date from #TempEarlyExit order by format
		declare @couLevel int
		set @couLevel=(select COUNT(*) from #TempLevelName)
		declare @couDate int
		set @couDate=(select COUNT(*) from #TempDate)
		declare @i int
		set @i=1
		declare @j int
		set @j=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''''
		while @i<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@i)
			set @SQLString1 = @SQLString1 + @Levelstr + ''@''
			while @j<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #TempEarlyExit where LevelName=@Levelstr and Date=(select date from #TempDate where ID=@j))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@j) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
				end
				set @j=@j+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + ''#''
			set @j=1
			set @i=@i+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
		drop table #TempDate
		drop table #TempLevelName
		drop table #TempEarlyExit
	end
  	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory    
    drop table #LevelRights
    drop table #TempProcessedData
    drop table #TempEmployee
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employees_ForShiftReAllocation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employees_ForShiftReAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Proc_Ta_Employees_ForShiftReAllocation ''04/01/2011'',''04/30/2011'','''',18,'''',''SuperAdmin'',323,1
--drop procedure Proc_Ta_Employees_ForShiftReAllocation
CREATE PROCEDURE [dbo].[Proc_Ta_Employees_ForShiftReAllocation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''''''') as EmployeeName ''
	set @sqlQuery = @sqlQuery + '' from ta_tbl_Employee ''
    set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)''
	if not(@EmployeeName='''')
	begin
		set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if not (@empId='''')
	begin
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_Employee.Employee_code_id= '''''' + @empId + '''''' )''
	end
	set @sqlQuery = @sqlQuery + ''  order by ta_tbl_Employee.Employee_FirstName ''
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,''0'' as SelectedRecords from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	--insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat))
	--update A set A.PreviousDayShift = B.CurrentShiftId
	--from #TempShiftIdForShiftReAllocation A inner join #TempShiftIdForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--update A set A.NextDayShift = B.CurrentShiftId
	--from #TempShiftIdForShiftReAllocation A inner join #TempShiftIdForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation] ''03/31/2018'',62,''SuperAdmin'',0,1,''7,1''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Emp_ShiftAlloc_YearCreation]
(
	@ToDat datetime,
	@InsertedYearSettingsID int,
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int,
    @WeekOff VARCHAR(25)
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,TopParentLevelId int,EffectiveDate datetime,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
--insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
--select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
--inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
--where emp.Isdeleted=0 group by EmployeeId) ELevel
--inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,[dbo].[Func_TA_GetParentIds](EL.LEVELID),ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Shift_Id int)
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,
	dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,
	ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''''''') as EmployeeName,Ta_Tbl_Shift.Shift_Id ''
	set @sqlQuery = @sqlQuery + '' from ta_tbl_Employee ''
    set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_Shift on #EmpLevel.TopParentLevelId = Ta_Tbl_Shift.Level_id''
	set @sqlQuery = @sqlQuery + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1 and Ta_Tbl_Shift.DefaultShift=1)''
	set @sqlQuery = @sqlQuery + ''  order by ta_tbl_Employee.Employee_FirstName ''
	exec(@sqlQuery)
	Declare @StartMonth as int
	Declare @EndMonth as int
	declare @StartYear as int
	Declare @EndYear as int
	Declare @StartDate as Date 
	Declare @EndDate as Date 
	Declare @MonthCount as int
	Declare @MonthName as varchar(10)
 SET @StartYear = (select Year(Fromdate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndYear = (select Year(Todate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 	
 SET @StartMonth = (select Month(Fromdate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndMonth = (select Month(Todate) from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @StartDate = (select Fromdate from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @EndDate = (select Todate from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID) 
 SET @MonthCount = (SELECT DATEDIFF(MONTH, FromDate, ToDate)+1 from ta_tbl_yearsetting where YearSettings_ID = @InsertedYearSettingsID)
 Delete ta_tbl_permanentshiftAllocation where ((year=@StartYear and month>=@StartMonth) or (year=@EndYear and month<=@EndMonth)) 
 IF (@StartDate <= @EndDate)
	BEGIN
		Declare @Month int 
		Declare @Year int 
		Declare @InsertedMonth int
		Declare @MonthStartDate nvarchar(50)
		SET @Month= @StartMonth
		SET @Year= @StartYear
		SET @InsertedMonth=1
		While (@MonthCount>=@InsertedMonth)
			BEGIN
				SET @MonthName= (Select CONVERT(varchar(3),DateName( month , DateAdd( month , @Month , -1 ))))	
				Declare @date29 int				
				if(@year%4=0)
				begin
					set @date29=29					
				end
				else
				begin
					set @date29=28					
				end
				Declare @DynamicQuery varchar(max)
				set @DynamicQuery=''''
				set @DynamicQuery=@DynamicQuery+'' insert into TA_Tbl_PermanentShiftAllocation 
				 SELECT E.EmployeeAutoID ''+'',''+  convert(varchar(4),@Year) + '','' +  convert(varchar(4),@Month)+'',
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''01-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''02-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''03-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''04-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''05-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''06-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''07-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''08-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''09-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''10-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''11-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''12-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''13-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''14-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''15-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''16-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''17-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''18-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''19-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''20-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''21-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''22-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''23-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''24-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''25-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''26-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''27-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),
					(CASE WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''28-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END)''
				if(@MonthName=''Feb'')
					begin
						set @DynamicQuery=@DynamicQuery+'',
						(CASE WHEN ((''''''+ convert(varchar(4),@MonthName) +''''''=''''Feb'''') AND (DATEADD(D, -1, (''''01-Mar-'' + CONVERT(varchar(6),@Year)+'''''')) = 29)) THEN 
								(
									CASE	WHEN ''''''+convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' +  CAST(DATEPART(DW, ''''''+CONVERT(varchar(6),@date29)+''-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 
											ELSE E.Shift_Id 
									END
								) 
								ELSE 0 
						END),0,0''
					end
				else if(@MonthName NOT IN (''Apr'', ''Jun'', ''Sep'', ''Nov''))
					begin
						set @DynamicQuery=@DynamicQuery+'',
						CASE WHEN ''''''+ convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''29-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END,						
						CASE WHEN ''''''+ convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''30-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END,
						CASE WHEN ''''''+ convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''31-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END''
					 end
				else
					begin	
						set @DynamicQuery=@DynamicQuery+'',	
						(CASE WHEN ''''''+ convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''29-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),									
						(CASE WHEN ''''''+ convert(varchar(15),@WeekOff) +'''''' LIKE ''''%'''' + CAST(DATEPART(DW, ''''30-'' + convert(varchar(4),@MonthName) + ''-'' + CONVERT(varchar(6),@Year)+'''''') AS VARCHAR(8)) + ''''%'''' THEN -1 ELSE E.Shift_Id END),0''
					end
				set @MonthStartDate=  convert(varchar(5),@Year)+''-''+ convert(varchar(5),@Month)+''-01 00:00:00.000''
				set @DynamicQuery=@DynamicQuery + '',''+convert(varchar(5),@LoggedInEmployeeId)+'',''''''+ convert(varchar(50),Getdate()) +'''''',''''''+ convert(varchar(50),@MonthStartDate) +'''''' From #TempEmployee E''
				Execute (@DynamicQuery)
				SET @Month = (@Month+1)
				IF (@Month=13)
					BEGIN
						SET @Month = 1
						SET @Year = @StartYear+1
					END
				SET @InsertedMonth = @InsertedMonth+1
			END	
				SET @StartDate = DateAdd(Day, 365, @StartDate) 
	END
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DetailAttendanceforExportTally]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DetailAttendanceforExportTally]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_DetailAttendanceforExportTally ''2017/04/01'',''2017/04/30'','''','''',''0,1'',''SuperAdmin'',''0'','''',9,0,''Both'',0,0,1
-- exec Proc_TA_RptDetailAttendanceDynamicNew @fromDat=''2014-07-01 00:00:00'',@ToDat=''2014-07-31 00:00:00'',@empId=N'''',
--@EmployeeName=N'''',@LevelID=N''0'',@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpSwipeCard=N'''',@ParentId=0,@DesignationId=0,@Gender=N''Both'',0,0
CREATE PROCEDURE [dbo].[Proc_TA_DetailAttendanceforExportTally]   
(  
	@fromDat datetime,  
	@ToDat datetime,  
	@empId varchar(max),   
	@EmployeeName varchar(max),
	@LevelID varchar(8000),  
	@UserGroupName varchar(250),  
	@GradeLevel varchar(20)  ,  
	@EmpSwipeCard varchar(20),  
	@ParentId int,  
	@DesignationID int,  
	@Gender varchar(10),
	@EmployeeCategory int,
	@EmployeeType int,
	@EmpAutoID int
)  
AS  
BEGIN  
	set nocount on
	create table #TempDetailedAttendance  
	(     
		[Employee Name] nvarchar(200),[Employee Id] varchar(50),SwipeCardNo varchar(50),
		Gender varchar(20),	Present numeric(8,1),Absent numeric(8,1),
		[Total Late Days] numeric(8,1),[Total Late Hours] numeric(8,1),
		[Total Early Exit Days] numeric(18,1),[Total Early Exit Hours] float default(0),
		[Total OT Days] numeric(8,1),
		[Total OT Hours] numeric(8,1),[Norm OT Hrs] numeric(8,1),[WeekOff OT Hrs] numeric(8,1),  
		[Holiday OT Hrs] numeric(8,1),Others numeric(8,1),
		EmployeeCategory int,EmpCategory nvarchar(200),
		EmployeeType int,WeeklyOff numeric(8,1),Holiday numeric(8,1),Leave Numeric(8,1),LOP numeric(8,1)
	)
	create table #TempDetailedAttendanceFinal  
	(     
		[Employee Name] nvarchar(200),[Employee Id] varchar(50),
		Gender varchar(20),Present numeric(8,1),Absent numeric(8,1),
		[Total Late Days] numeric(8,1),[Total Late Hours] numeric(8,1),
		EarlyOutInMins float default(0),EarlyOutDays numeric(18,1),
		[Total OT Days] numeric(8,1),[Total OT Hours] numeric(8,1),
		[Norm OT Hrs] numeric(8,1),[WeekOff OT Hrs] numeric(8,1),
		[Holiday OT Hrs] numeric(8,1),Others numeric(8,1)
	)
	create table #tempemployee (EmployeeCodeId  varchar(50),SwipeCardNo  varchar(50), EmployeeName nvarchar(200) ,Gender varchar(20))   
	create table #tempLeavetype (slno int identity(1,1),Leavetype nvarchar(10) )  
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50)) 
	create table #EmpGrade(Grade_Id int)  
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	create table #EmpAttendanceDetails(EmployeeID  varchar(50),Present numeric(8,1),Absent numeric(8,1),TotalLateDays numeric(8,1),TotalLateHours numeric(8,1),TotalOTDays numeric(8,1),TotalOTHours numeric(8,1),NormalOTHrs numeric(8,1),WeekOffOTHrs numeric
	(8,1),HolidayOTHours numeric(8,1),EarlyOutInMins float,TotalEarlyOutDays numeric(8,1),EmployeeCategory int,EmpCategory nvarchar(200),EmployeeType int,WeeklyOff numeric(8,1),Holiday numeric(8,1),Leave Numeric(8,1),LOP numeric(8,1))
	create table #LevelRights(LevelId int)
	create table #TempProcessedData(EmpAutoId bigint,Date datetime,Employee_Code_Id varchar(20),InTime nvarchar(25),OutTime nvarchar(25),Attendance nvarchar(20),fnattendanceCode nvarchar(20),anattendanceCode nvarchar(20),Shift_Id int,TotalDays numeric(18,
	1),LateInMins float,OtMins float,NormOT nvarchar(10),OffOT nvarchar(10),HolOT nvarchar(10),EarlyOutMins float)	
	create table #TempEmployeeForProcessedData(EmpAutoId bigint,EmpSwipeCardNo varchar(20))  
	CREATE NONCLUSTERED INDEX [IDX_Employee_Code_Id] ON [dbo].[#TempProcessedData]   
	(  
		[Employee_Code_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Grade] ON [dbo].[#EmpGrade]   
	(  
		[Grade_Id] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel]   
	(  
		[EffectiveDate],[EmployeeId],[LevelId] ASC  
	) ON [PRIMARY]  
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation]   
	(  
		[EffectiveDate],[EmployeeId], [DesignationId] ASC  
	)ON [PRIMARY]  
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	insert into #tempLeavetype SELECT Top 5 substring(LeaveType,1,3)  FROM ta_tbl_leavetype
	insert into #EmpGrade select distinct Grade_Id from  TA_Tbl_Grade where Grade_Level>=@GradeLevel  	
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	--To split up the comma separated values
	if(@empId is not null and @empId <> '''')
		begin
			create table #EmployeeID(EmployeeID varchar(25))
			insert into #EmployeeID select * from SplitupEmployeeCode(@empId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	Declare @sqlEmpLevel nvarchar(4000)
	set @sqlEmpLevel=
	''insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from (
	select max(el.EffectiveDate) as EffectiveDate,el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	inner join #LevelRights on #LevelRights.LevelId=el.LevelId
	where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102) and EL.LevelId is not null''	
	If Not (@empId = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=ELevel.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlEmpLevel = @sqlEmpLevel + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=ELevel.Employee_Code_Id ''
		End
	Execute(@sqlEmpLevel)	
			declare @LevelId1 as int
			declare @GetLevelID as int
			declare @LeaveName as nvarchar(200)
            set @GetLevelID=(select top 1 LevelId from #EmpLevel)
            DECLARE @childID INT 
             ;WITH ParentLevel AS
            (
                  SELECT *, 1 AS Lvl FROM Ta_Tbl_levelDetails 
                  WHERE id = @GetLevelID
                  UNION ALL
                  SELECT rh.*, Lvl+1 AS Lvl FROM Ta_Tbl_levelDetails rh
                  INNER JOIN ParentLevel rc ON rh.id = rc.ParentId
            )
            SELECT TOP 1 @LevelId1=id
            FROM ParentLevel r
            --inner JOIN Ta_Tbl_levelDetails p ON p.id = r.ParentId
            ORDER BY lvl DESC
	select @LeaveName=name from Ta_Tbl_levelDetails where id=@LevelId1
	Declare @sqlCommonSwipeCardNo nvarchar(1000)
	set @sqlCommonSwipeCardNo=
	''insert into #TempEmployeeForProcessedData 
	select Employee_ID,SwipeCardNo from TA_Tbl_Employee  
	inner join #EmpLevel on #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id ''
	If Not (@empId = '''')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' Inner join #EmployeeID on #EmployeeID.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=TA_Tbl_Employee.Employee_Code_Id ''
		End
	SET @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' where SwipeCardNo is not null and TA_Tbl_Employee.Isdeleted=0 AND TA_Tbl_Employee.report_exclude = 0 ''
	if(@Gender<>''Both'')  
		begin  
			set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' and TA_Tbl_Employee.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''  
		end   
	if(@isReportingto > 0)
            BEGIN
               set @sqlCommonSwipeCardNo = @sqlCommonSwipeCardNo + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	execute(@sqlCommonSwipeCardNo)	
	Declare @sqlTempProcessedData1 varchar(8000)
	set @sqlTempProcessedData1=  
	''insert into #TempProcessedData 
	select	#TempEmployeeForProcessedData.EmpAutoId,
			PD.Date,
			PD.Employee_Code_Id,
			PD.InTime,
			PD.OutTime,
			PD.Attendance,
			PD.fnattendanceCode,
			PD.anattendanceCode,
			PD.Shift_Id,
			PD.TotalDays,
			PD.LateInMins,
			PD.OtMins,
			PD.NormOT,
			PD.OffOT,
			PD.HolOT,
			PD.EarlyOutMins
	from TA_Tbl_ProcessedData PD
	inner join #TempEmployeeForProcessedData on #TempEmployeeForProcessedData.EmpSwipeCardNo=PD.Employee_Code_Id  
	inner join TA_Tbl_Employee E on E.SwipeCardNo=#TempEmployeeForProcessedData.EmpSwipeCardNo  
	where (PD.date >= CONVERT(DATETIME,''''''+cast( @fromDat as nvarchar(50))+'''''', 102))  
	AND (PD.date <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102)) and    
	((E.Employee_Status=0 and E.InActiveDate>=PD.date)  
	or  
	(E.Employee_Status=1)  
	)''  
	execute(@sqlTempProcessedData1)
	declare @SqlQuery as varchar(8000)  
	set @SqlQuery=''''  
	set @SqlQuery = ''insert into #tempemployee (EmployeeCodeId,SwipeCardNo,EmployeeName,Gender) select ta_tbl_employee.employee_code_id as [Employee Id],ta_tbl_employee.SwipeCardNo,isnull(Employee_FirstName,'''''''') + SPACE(1) + isnull(Employee_LastName,'''''''') AS [Employee Name],TA_Tbl_Employee.Gender''  
	set @SqlQuery = @SqlQuery + ''	from ta_tbl_employee inner join #TempProcessedData on #TempProcessedData.EmpAutoId = ta_tbl_employee.Employee_ID''  
	set @SqlQuery = @SqlQuery + ''	Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''  
	set @SqlQuery = @SqlQuery + ''	Inner join #EmpDesignation on #EmpDesignation.employeeid=TA_Tbl_Employee.Employee_Id ''  
	set @SqlQuery = @SqlQuery + ''	inner join TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	set @sqlQuery = @sqlQuery + ''	inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = TA_Tbl_Title.GradeId ''
	set @sqlQuery = @sqlQuery + ''	WHERE 
									(TA_Tbl_Employee.Employee_Status = 1  
										or   
									(TA_Tbl_Employee.Employee_Status = 0 and  convert(varchar(11), TA_Tbl_Employee.InActiveDate,102) >=   
									convert(varchar(11),#TempProcessedData.Date,102))) '' 	
	if(@UserGroupName<>''SuperAdmin'')  
		begin  
			set @SqlQuery=@SqlQuery+'' AND TA_Tbl_Grade.Grade_Level >='''''' + cast(@GradeLevel as nvarchar(8)) + '''''' ''
		end  
	exec(@SqlQuery)  
	insert into #TempDetailedAttendance([Employee Id],SwipeCardNo,[Employee Name],Gender) select distinct EmployeeCodeId,SwipeCardNo,EmployeeName,Gender from #tempemployee  
	declare @SqlPresent varchar(8000)  
	set @SqlPresent = '' insert into #EmpAttendanceDetails select Employee_code_Id, ''  
	set @SqlPresent = @SqlPresent + '' ''''Present'''' = sum( CASE FNAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Present'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''	
	--set @SqlPresent = @SqlPresent + '' ''''Present'''' = 
	--									sum(
	--											CASE FNAttendanceCode 
	--												WHEN ''''Present'''' THEN	Case TotalDays	When ''''1.0'''' Then ''''0.5'''' 
	--																						Else TotalDays 
	--																		END 
	--												When ''''|'''' Then TotalDays 
	--												When ''''Weekly Off'''' then totalDays 
	--												else 0 
	--											END
	--										) + 
	--									sum( 
	--											CASE	ANAttendanceCode 
	--													WHEN ''''Present'''' THEN	Case TotalDays	When ''''1.0'''' Then ''''0.5'''' 
	--																							Else TotalDays 
	--																			END  
	--													else 0 
	--											END
	--										)''  
	--set @SqlPresent = @SqlPresent + '' + sum( CASE FNAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Comp Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)+ sum( CASE FNAttendanceCode WHEN ''''BL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''BL'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END),''
	set @SqlPresent = @SqlPresent + '' ''''Absent'''' = sum( CASE FNAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Absent'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''  
	set @SqlPresent = @SqlPresent + '' ''''Total Late Days'''' =  count(CASE lateinmins WHEN lateinmins THEN  lateinmins END) - count(CASE lateinmins WHEN 0 THEN  lateinmins END) - count(CASE lateinmins WHEN null THEN  lateinmins END)   , ''  
	set @SqlPresent = @SqlPresent + '' ''''Total Late Hours'''' =  sum(CASE lateinmins WHEN lateinmins THEN  lateinmins END), ''  
	set @SqlPresent = @SqlPresent + '' ''''Total OT Days'''' =  count(CASE otmins WHEN otmins THEN  otmins END) - count(CASE otmins WHEN 0 THEN  lateinmins END) - count(CASE otmins WHEN null THEN  lateinmins END)   , ''  
	set @SqlPresent = @SqlPresent + '' ''''Total Ot Hours'''' =  sum(CASE otmins WHEN otmins THEN  otmins END)/60, ''  
	set @SqlPresent = @SqlPresent + '' ''''Norm OT Hrs''''=sum(CASE ISNULL(NormOt,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''WeekOff OT Hrs''''=sum(CASE ISNULL(OffOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''''Holiday OT Hrs''''=sum(CASE ISNULL(HolOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OtMins END),''  
	set @SqlPresent = @SqlPresent + '' ''''Total EarlyOut Hours'''' =  sum(CASE EarlyOutmins WHEN EarlyOutmins THEN  EarlyOutmins END), ''  
	set @SqlPresent = @SqlPresent + '' ''''Total EarlyOut Days'''' =  count(CASE EarlyOutmins WHEN EarlyOutmins THEN  EarlyOutmins END) - count(CASE EarlyOutmins WHEN 0 THEN  EarlyOutmins END) - count(CASE EarlyOutmins WHEN null THEN  EarlyOutmins END),C.CategoryId,C.CategoryName,T.TypeId ,''
	set @SqlPresent = @SqlPresent + '' ''''WeeklyOff'''' = sum( CASE FNAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Weekly Off'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''  
	set @SqlPresent = @SqlPresent + '' ''''Holiday'''' = sum( CASE FNAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''Holiday'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''	
	set @SqlPresent = @SqlPresent + '' ''''Leave'''' = SUM(CASE WHEN FNAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''',''''LOP'''') THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + 
	SUM( CASE WHEN ANAttendanceCode not in(''''Absent'''',''''Present'''',''''Holiday'''',''''Weekly Off'''') THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END),''	
	set @SqlPresent = @SqlPresent + '' ''''LOP'''' = sum( CASE FNAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END) + sum( CASE ANAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END  else 0 END)''		
	set @SqlPresent = @SqlPresent + '' from #TempProcessedData  ''  
	set @SqlPresent = @SqlPresent + '' inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=#TempProcessedData.EmpAutoId 
	inner join TA_Tbl_Category C on C.CategoryId=EC.CategoryId
	inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=#TempProcessedData.EmpAutoId  
	inner join TA_Tbl_Type T on T.TypeId=ET.TypeId   ''  
	set @SqlPresent = @SqlPresent + '' where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance) ''  
	set @SqlPresent = @SqlPresent + '' group by Employee_Code_ID,C.CategoryId,C.CategoryName,T.TypeId ''  
	exec (@SqlPresent)  
	--Updates the Present,Absent,OT,Late details in the temporary table.  
	update #TempDetailedAttendance set Present = #EmpAttendanceDetails.Present,Absent = #EmpAttendanceDetails.Absent,  
	[Total Late Days] = #EmpAttendanceDetails.TotalLateDays,[Total Late Hours] = #EmpAttendanceDetails.TotalLateHours,  
	[Total OT Days] = #EmpAttendanceDetails.TotalOTDays,[Total OT Hours] = #EmpAttendanceDetails.TotalOTHours,  
	[Norm OT Hrs] = #EmpAttendanceDetails.NormalOTHrs,[WeekOff OT Hrs] = #EmpAttendanceDetails.WeekOffOTHrs,  
	[Holiday OT Hrs] = #EmpAttendanceDetails.HolidayOTHours,
	[Total Early Exit Hours]=#EmpAttendanceDetails.EarlyOutInMins,
	[Total Early Exit Days]= #EmpAttendanceDetails.TotalEarlyOutDays,
	EmployeeCategory=#EmpAttendanceDetails.EmployeeCategory,
	EmpCategory=#EmpAttendanceDetails.EmpCategory,
	EmployeeType=#EmpAttendanceDetails.EmployeeType,
	WeeklyOff=#EmpAttendanceDetails.WeeklyOff,
	Holiday=#EmpAttendanceDetails.Holiday,
	Leave=#EmpAttendanceDetails.Leave,
	LOP=#EmpAttendanceDetails.LOP
	 from #EmpAttendanceDetails inner join #TempDetailedAttendance   
	on #EmpAttendanceDetails.EmployeeID=#TempDetailedAttendance.SwipeCardNo  
	--Inserts the Others details in the temporary table  
	--declare @SqlOthers varchar(4000)  
	--create table #Others(SwipeCardNo  varchar(50),Others numeric(8,1))  
	----inserts the Others in the temporary table.  
	--set @SqlOthers = ''Insert into #Others select Employee_Code_Id ,''''Others'''' = sum( CASE FNAttendanceCode WHEN ''''RH'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE FNAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)''  
	--set @SqlOthers = @SqlOthers + '' + sum( CASE ANAttendanceCode WHEN ''''RH'''' THEN Case TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''LOP'''' THEN Case TotalDays
	--When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END) + sum( CASE ANAttendanceCode WHEN ''''ESI'''' THEN Case TotalDays When ''''1.0'''' Then ''''0.5'''' Else TotalDays END else 0 END)''  
	--set @SqlOthers = @SqlOthers + '' from #TempProcessedData where Employee_Code_Id in(select SwipeCardNo from #TempDetailedAttendance) ''  
	--set @SqlOthers = @SqlOthers + '' group by Employee_Code_ID''  
	--exec(@SqlOthers)  
	--Create table #tempLeaveTypeforOthers(SNO int identity(1,1),Leavetype varchar(10) )  
	--insert into #tempLeaveTypeforOthers select LeaveType from Ta_Tbl_LeaveType where LeaveType not in(select LeaveType from #tempLeavetype)  
	--declare @LTOthersCount int  
	--set @LTOthersCount=1  
	--while(@LTOthersCount<=(select count(*) from #tempLeaveTypeforOthers))  
	--	BEGIN  
	--		declare @LeaveTypeForOthers varchar(10)  
	--		set @LeaveTypeForOthers =(select LeaveType from #tempLeaveTypeforOthers where SNO=@LTOthersCount)  
	--		declare @SqlUpdateOthers varchar(3000)  
	--		set @SqlUpdateOthers = ''Update #Others set Others = Others + ''  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + ''A.TotalDays from ''   
	--		set @SqlUpdateOthers =@SqlUpdateOthers + '' (select Employee_Code_Id,(sum( CASE PD.FNAttendanceCode WHEN ''''''+ @LeaveTypeForOthers + '''''' THEN CASE PD.TotalDays When ''''1.0'''' Then ''''0.5'''' when null then 0 Else PD.TotalDays END else 0 END)''  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + '' + sum( CASE PD.ANAttendanceCode WHEN ''''''+ @LeaveTypeForOthers + '''''' THEN CASE PD.TotalDays when null then 0 When ''''1.0'''' Then ''''0.5'''' When ''''0.5'''' Then ''''0.5'''' Else PD.TotalDays END else 0 END)) as TotalDays''
	--		set @SqlUpdateOthers = @SqlUpdateOthers + '' from #TempProcessedData PD ''  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + '' group by PD.Employee_Code_Id) A''  
	--		set @SqlUpdateOthers = @SqlUpdateOthers + '' inner join #Others OthersTemp on OthersTemp.SwipeCardNo=A.Employee_Code_Id''  
	--		set @LTOthersCount=@LTOthersCount+1  
	--		exec(@SqlUpdateOthers)  
	--	END  
	--Updates the Others column in the temporary table  
	--update #TempDetailedAttendance set Others=#Others.Others from #Others inner join #TempDetailedAttendance on #Others.SwipeCardNo=#TempDetailedAttendance.SwipeCardNo  
	--Adding the Leave type column in the #TempDetailedAttendance table.  
	--declare @LeaveTypeCount int  
	--set @LeaveTypeCount=1  
	--while(@LeaveTypeCount<=5)  
	--	BEGIN  
	--		declare @LeaveType varchar(10)  
	--		set @LeaveType=(select Leavetype from #tempLeavetype where slno=@LeaveTypeCount)  
	--		declare @AlterQuery varchar(100)  
	--		set @AlterQuery=''Alter table #TempDetailedAttendance add ['' + @LeaveType + ''] numeric(18,1)''  
	--		exec(@AlterQuery)  
	--		declare @UpdateQuery varchar(4000)  
	--		set @UpdateQuery = ''update #TempDetailedAttendance  set [''+ @LeaveType +'']''  
	--		set @UpdateQuery = @UpdateQuery + ''=A.TotalDays from''  
	--		set @UpdateQuery = @UpdateQuery +'' (select Employee_Code_ID,(sum(CASE PD.FNAttendanceCode WHEN '''''' + @LeaveType + '''''' THEN CASE PD.TotalDays When ''''0.5'''' Then ''''0.5'''' when ''''1.0'''' Then ''''0.5'''' when null then 0 Else PD.TotalDays END else 0 END) ''  
	--		set @UpdateQuery = @UpdateQuery + '' + sum(CASE PD.ANAttendanceCode WHEN '''''' + @LeaveType + '''''' THEN CASE PD.TotalDays When ''''0.5'''' Then ''''0.5'''' When ''''1.0'''' Then ''''0.5'''' when null then 0 Else PD.TotalDays END else 0 END)) as TotalDays ''  
	--		set @UpdateQuery = @UpdateQuery + '' from #TempProcessedData PD''  
	--		set @UpdateQuery = @UpdateQuery + '' inner join #TempDetailedAttendance TDA on TDA.SwipeCardNo=PD.Employee_code_ID''  
	--		set @UpdateQuery = @UpdateQuery + '' group by PD.Employee_Code_ID) A''  
	--		set @UpdateQuery = @UpdateQuery + '' inner join #TempDetailedAttendance TempAttendance on TempAttendance.SwipeCardNo=A.Employee_code_ID''  
	--		exec(@UpdateQuery)  
	--		set @LeaveTypeCount=@LeaveTypeCount+1  
	--END  
	set @SqlPresent=''''
	set @SqlPresent='' select *,''''''+cast(isnull(@LeaveName,'''') as nvarchar(100))+'''''' as LevelName from #TempDetailedAttendance where 1=1  ''
	if(isnull(@EmployeeCategory,0)>0)
		begin
			set @SqlPresent = @SqlPresent + '' and EmployeeCategory =''''''+cast(@EmployeeCategory as varchar(50))+'''''' '' 
		end
	if(isnull(@EmployeeType,0)>0)
		begin
			set @SqlPresent = @SqlPresent + '' and  EmployeeType=''''''+cast(@EmployeeType as varchar(50))+'''''' '' 
		end
	exec (@SqlPresent)
	drop table #tempemployee  
	drop table #tempLeavetype  
	drop table #EmpLevel  
	drop table #EmpDesignation  
	drop table #EmpGrade  
	drop table #EmpAttendanceDetails  
	--drop table #Others  
	--drop table #tempLeaveTypeforOthers  
	drop table #TempDetailedAttendance  
	drop table #LevelRights  
	drop table #TempProcessedData  
	drop table #TempEmployeeForProcessedData  
	drop table #TempDetailedAttendanceFinal  
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_BulkImportPrevLeaveBalance]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_BulkImportPrevLeaveBalance]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <28-01-2019 04.42 PM>
-- Description:	<Import Previous year Leave values into employee leave type table>
--select * from ImportFromExcel
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_BulkImportPrevLeaveBalance]
AS
BEGIN
	SET NOCOUNT on;	
	Declare @YearSetID int
	Declare @Count int
	Declare @Start int
	set @Start=1
	--select * from TA_Tbl_Emp_LeaveTypeDetails
	select @YearSetID=YearSettings_Id from TA_Tbl_YearSetting where IsActive=1
	select @Count=COUNT(*) from ImportFromExcel	
	--select * from ImportFromExcel
	While @Count>=@Start
	BEGIN		
		Declare @EmpAutoID bigint
		Declare @Employeeid	varchar(50)
		Declare @LeaveType1	decimal(18,1)
		Declare @LeaveType2	decimal(18,1)
		Declare @LeaveType3	decimal(18,1)
		Declare @LeaveType4	decimal(18,1)
		Declare @LeaveType5	decimal(18,1)
		Declare @LeaveType6	decimal(18,1)
		Declare @LeaveType7	decimal(18,1)
		Declare @LeaveType8	decimal(18,1)
		Declare @LeaveType9	decimal(18,1)
		Declare @LeaveType10 decimal(18,1)
		Declare @LeaveType11 decimal(18,1)
		Declare @LeaveType12 decimal(18,1)
		Declare @LeaveType13 decimal(18,1)
		Declare @LeaveType14 decimal(18,1)
		Declare @LeaveType15 decimal(18,1)
		
		set @Employeeid=''''
		set @LeaveType1=0 
		set @LeaveType2=0 
		set @LeaveType3=0 
		set @LeaveType4=0 
		set @LeaveType5=0 
		set @LeaveType6=0 
		set @LeaveType7=0
		set @LeaveType8=0 
		set @LeaveType9=0
		set @LeaveType10=0 
		set @LeaveType11=0 
		set @LeaveType12=0
		set @LeaveType13=0
		set @LeaveType14=0 
		set @LeaveType15=0
		
		select 
		@Employeeid=Employeeid,
		@LeaveType1=LeaveType1,
		@LeaveType2=LeaveType2,
		@LeaveType3=LeaveType3, 
		@LeaveType4=LeaveType4,
		@LeaveType5=LeaveType5,
		@LeaveType6=LeaveType6,
		@LeaveType7=LeaveType7,
		@LeaveType8=LeaveType8,
		@LeaveType9=LeaveType9,
		@LeaveType10=LeaveType10, 
		@LeaveType11=LeaveType11,
		@LeaveType12=LeaveType12,
		@LeaveType13=LeaveType13,
		@LeaveType14=LeaveType14,
		@LeaveType15=LeaveType15			
		from ImportFromExcel where [Sl.No]=@Start
		
		select @EmpAutoID=Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@Employeeid and Isdeleted=0
		Declare @i int
		set @i=1
		if(@EmpAutoID is not null and @EmpAutoID<>'''')
		begin
			Declare @LeaveTypeID int
			--1
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=1 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType1,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END
			end
			---2
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=2 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType2,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---3
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=3 order by LeaveType_Id			
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType3,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---4
			set @LeaveTypeID=0							
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=4 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType4,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---5
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=5 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType5,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---6
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=6 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType6,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---7
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=7 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType7,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---8
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=8 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType8,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---9
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=9 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType9,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---10
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=10 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType10,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---11
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=11 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType11,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---12
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=12 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType12,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---13
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=13 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType13,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---14
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=14 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType14,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
			---15
			set @LeaveTypeID=0				
			select @LeaveTypeID=LeaveType_Id from TA_Tbl_LeaveType where LeaveType_Id=15 order by LeaveType_Id
			if(isnull(@LeaveTypeID,'''')!='''')
			begin
				IF EXISTS(SELECT * FROM TA_Tbl_YearClosure where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID)
				BEGIN
					update TA_Tbl_YearClosure set Carry_PrevYear=isnull(@LeaveType15,0) where Employee_Id=@EmpAutoID and Year_SettingID=@YearSetID and LeaveTypeId=@LeaveTypeID
				END	
			end
		end
		set @Start=@Start+1 
	END
	delete from ImportFromExcel
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoShiftConfiguration_Import]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoShiftConfiguration_Import]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani>
-- Create date: <13/07/2019>
-- Description:	<Import Auto Shift Configuration>
-- =============================================
/* 
Proc_TA_AutoShiftConfiguration_Import
''<Dst_ShiftAlloc>
<Tbl_ShiftAlloc>
<EmployeeId>S1164</EmployeeId>
<Employee_Name>velu</Employee_Name>
<ShiftId1>G1</ShiftId1>
<ShiftId2>G2</ShiftId2>
<ShiftId3>F1</ShiftId3>   
<ShiftId4>F2</ShiftId4>
<ShiftId5>F3</ShiftId5>
</Tbl_ShiftAlloc>
</Dst_ShiftAlloc>'', 1,''Superadmin''
*/
CREATE PROCEDURE [dbo].[Proc_TA_AutoShiftConfiguration_Import]
	-- Add the parameters for the stored procedure here
@ShiftData XML = NULL,
@EmpId bigInt,
@UserGroup VARCHAR(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
  	Declare @local_LeaveData XML = @ShiftData
	Declare	@local_EmpAutoID bigInt=@EmpId	
	Declare @local_UserGroup VARCHAR(max)=@UserGroup
	SET NOCOUNT ON;
	DECLARE @XMLParams INT	
	DECLARE @ErrMsg VARCHAR(MAX)
	Declare @ErrIds VARCHAR(MAX)
	Declare @SQLQuery varchar(max)
	declare @ValidEmpId varchar(40)
	DECLARE @ISREPORTINGTO AS INT
	DECLARE @ISINDIVIDUAL AS INT
	CREATE TABLE #EMPLOYEEIDS(EMPAUTOID INT)
	DECLARE @ErrorMsg TABLE
	(
		RecordID int,
		Employee_Id VARCHAR(100), 
		Error_Msg VARCHAR(MAX),
		flag bit default(1),
		date datetime
	)	
	BEGIN TRY
		BEGIN TRAN ImportAutoShift
			EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @ShiftData
			SELECT @ISREPORTINGTO=REPORTSBASEDON,@ISINDIVIDUAL=INDIVIDUALUSERS FROM TA_TBL_USERGROUP WHERE GROUPNAME=@local_UserGroup
			INSERT INTO  #EMPLOYEEIDS SELECT * FROM [DBO].[FN_TA_GETMAPPEDEMPLOYEES_REPORTINGTO](@local_EmpAutoID) AS EMPAUTOID  
			DECLARE @alertMsg VARCHAR(MAX)
			SET @alertMsg=''''
			CREATE TABLE #EMPLEVEL
			(
				EMPLOYEEID INT,
				LEVELID INT,
				EFFECTIVEDATE DATETIME,
				EMPLOYEE_CODE_ID VARCHAR(50),
				SWIPECARD VARCHAR(50)
			)
			CREATE TABLE #LEVELRIGHTS(LEVELID INT)			
			INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@local_UserGroup,0) AS LEVELID
			DECLARE @SQLEMPLEVEL			NVARCHAR(4000)			
			SET @SQLEMPLEVEL=
			''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM 
			(
				SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
				INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
				INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
				WHERE  SWIPECARDNO IS NOT NULL AND EMP.ISDELETED=0 ''
			SET @SQLEMPLEVEL = @SQLEMPLEVEL +'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
			) ELEVEL
			INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
			INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
			AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(dbo.DateOnly(getdate()) AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''

			

			IF(@ISREPORTINGTO > 0)
			BEGIN
			SET @SQLEMPLEVEL = @SQLEMPLEVEL + '' AND (EMP.EMPLOYEE_ID IN (SELECT * FROM #EMPLOYEEIDS)) ''  
			END

			EXECUTE(@SQLEMPLEVEL)
						
			create table #TempShiftData
			(	
				autoid int identity(1,1),
				Employee_Id int,					
				Employee_Code_Id varchar(100),	 
				ShiftId1 varchar(8),
				ShiftId2 varchar(8),
				ShiftId3 varchar(8),
				ShiftId4 varchar(8),
				ShiftId5 varchar(8),
			)	
			INSERT INTO #TempShiftData
			SELECT E.Employee_Id, Tbl.* FROM OPENXML (@XMLParams, ''/Dst_ShiftAlloc/Tbl_ShiftAlloc'', 2) WITH 
			(	
				EmployeeId varchar(100),						
				ShiftId1 varchar(8),
				ShiftId2 varchar(8),
				ShiftId3 varchar(8),
				ShiftId4 varchar(8),
				ShiftId5 varchar(8)
			) Tbl			
			left outer join TA_Tbl_Employee E ON E.Employee_Code_Id = convert(varchar(40),Tbl.EmployeeId)
			AND E.IsDeleted = 0 AND E.Employee_Status = 1


			

			INSERT INTO @ErrorMsg
			SELECT autoid,Employee_Code_Id,'''',1,getdate() FROM #TempShiftData
			EXEC SP_XML_RemoveDocument @XMLParams
				--select ''1''
			--Empty excel File error checking--
			IF NOT EXISTS(SELECT Employee_Code_Id FROM #TempShiftData where Employee_Code_Id is not null or Employee_Code_Id='''')
			BEGIN
				SET @ErrMsg = ''There is no record in the Excel File Please Upload Valid File''
				SET @ErrIds = 0
				RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
			END		
			--Valid Employee Code Id checking--	
			IF EXISTS(SELECT Employee_Code_Id FROM #TempShiftData WHERE ISNULL(Employee_Code_Id, '''') = '''')
			BEGIN
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Employee Id is missing;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID 
				WHERE ISNULL(tot.Employee_Code_Id, '''') = ''''
			END	
			UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Employee Id is Invalid <br />'',flag=0 FROM @ErrorMsg EM
			inner join #TempShiftData tot on tot.autoid=EM.RecordID 
			where (tot.Employee_Id is null or tot.Employee_Id = '''')
			IF EXISTS(SELECT ShiftId1 FROM #TempShiftData WHERE ShiftId1 = '''' or ShiftId1 is null)
			Begin
						UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 1 Name is missing;<br />'',flag=0 FROM @ErrorMsg EM
						inner join #TempShiftData tot on tot.autoid=EM.RecordID 	
						where (tot.ShiftId1 is null or tot.ShiftId1 = '''')	
			END
			--First shift Id 1 valid Id checking--		
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 1 Name is not Valid;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId1 != '''' 				
				where tot.ShiftId1 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 2 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 2 Name is not Valid;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId2 != '''' 				
				where tot.ShiftId2 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 3 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 3 Name is not Valid;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId3 != '''' 				
				where tot.ShiftId3 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 4 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 4 Name is not Valid;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId4 != '''' 				
				where tot.ShiftId4 not in (select Shift_ShortName from ta_tbl_shift a)
			--First shift Id 5 valid Id error checking--	
				UPDATE @ErrorMsg set Error_Msg=isnull(Error_Msg,'''')+''Shift 5 Name is not Valid;<br />'',flag=0 FROM @ErrorMsg EM
				inner join #TempShiftData tot on tot.autoid=EM.RecordID and  tot.ShiftId5 != '''' 				
				where tot.ShiftId5 not in (select Shift_ShortName from ta_tbl_shift a)
			--Duplicate Employee id Check --	
			IF Exists(
			SELECT autoid FROM 
			(
				SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,Employee_Id ORDER BY Employee_Code_Id ASC)AS duplicate,
						autoid FROM #TempShiftData
			)AS A WHERE duplicate>1)
			BEGIN
				set @alertMsg=''Duplication Record Found;Please find and remove duplicate record in excel file;<br />''				
				UPDATE @ErrorMsg SET Error_Msg=	CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN
				(
					SELECT ROW_NUMBER()OVER(PARTITION BY Employee_Code_Id,Employee_Id ORDER BY Employee_Code_Id ASC)AS duplicate,
					Employee_Code_Id,autoid FROM #TempShiftData
				)AS A on EM.RecordID=a.autoid WHERE a.duplicate>1
				and ISNULL(a.Employee_Code_Id, '''') != ''''
			END
			--Level Rights Check ---
			IF EXISTS(SELECT t.Employee_Code_Id FROM #TempShiftData t INNER JOIN ta_tbl_employee e on convert(varchar(40),t.Employee_Code_Id)=e.Employee_Code_Id
			LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID=''''))
			BEGIN
				set @alertMsg=''Employee is not available or you are not having an previlege to import overtime data for this employee;<br />''				
				UPDATE @ErrorMsg SET Error_Msg=CASE	WHEN Error_Msg!='''' THEN Error_Msg+@alertMsg
														Else @alertMsg
												END,
				flag=0 FROM @ErrorMsg EM
				INNER JOIN #TempShiftData t on EM.RecordID=t.autoid				
				INNER JOIN ta_tbl_employee e on t.Employee_Code_Id=e.Employee_Code_Id
				LEFT OUTER JOIN #EMPLEVEL EL on e.Employee_Id=EL.EMPLOYEEID WHERE (EL.EMPLOYEEID IS NULL OR EL.EMPLOYEEID='''')
				and ISNULL(t.Employee_Code_Id, '''') != ''''
			END
			--Insert or Update function only all records are valid--
				Declare @IsValidImport int
				Declare @TotLeaveRecord int
				select @IsValidImport = isnull(COUNT(*),0) from @ErrorMsg where flag=0
				
				IF(@IsValidImport = 0)
				begin
						select @TotLeaveRecord=COUNT(*) from #TempShiftData				
						Declare @start int
						set @start=1	
						while @TotLeaveRecord>=@start
							begin	
								Declare @Employeeid int
								select @Employeeid=Employee_Id from #TempShiftData where autoid=@start

									IF NOT EXISTS(SELECT EmployeeId from TA_Tbl_AutoShiftConfiguration a inner join #TempShiftData b on b.Employee_Id= a.EmployeeId where EmployeeId=@Employeeid)
										BEGIN
										
											INSERT INTO TA_Tbl_AutoShiftConfiguration(EmployeeId,ShiftId1,ShiftId2,ShiftId3,ShiftId4,ShiftId5,CreatedBy, CreatedDate, IsImport) 
											Select Employee_Id, isnull(c.Shift_Id,0), isnull(d.Shift_Id,0),isnull(e.Shift_Id,0), isnull(f.Shift_Id,0), isnull(g.Shift_Id,0),@EmpId,getdate(),1 from #TempShiftData	a
											left outer join ta_tbl_shift c on c.Shift_ShortName = a.ShiftId1
											left outer join ta_tbl_shift d on d.Shift_ShortName = a.ShiftId2
											left outer join ta_tbl_shift e on e.Shift_ShortName = a.ShiftId3
											left outer join ta_tbl_shift f on f.Shift_ShortName = a.ShiftId4
											left outer join ta_tbl_shift g on g.Shift_ShortName = a.ShiftId5										
										END
									ELSE IF EXISTS(SELECT isnull(EmployeeId,0) from TA_Tbl_AutoShiftConfiguration a inner join #TempShiftData b on b.Employee_Id= a.EmployeeId where EmployeeId=b.Employee_Id )
										BEGIN
											Update a set
											ShiftId1 = isnull(c.Shift_Id,0),
											ShiftId2 = isnull(d.Shift_Id,0),
											ShiftId3 = isnull(e.Shift_Id,0),
											ShiftId4 = isnull(f.Shift_Id,0),
											ShiftId5 = isnull(g.Shift_Id,0),
											ModifiedBy = @EmpId,
											ModifiedDate = getdate(),
											isimport=1
											from TA_Tbl_AutoShiftConfiguration a
											inner join #TempShiftData b on b.Employee_Id= a.EmployeeId 
											left outer join ta_tbl_shift c on c.Shift_ShortName = b.ShiftId1
											left outer join ta_tbl_shift d on d.Shift_ShortName = b.ShiftId2
											left outer join ta_tbl_shift e on e.Shift_ShortName = b.ShiftId3
											left outer join ta_tbl_shift f on f.Shift_ShortName = b.ShiftId4
											left outer join ta_tbl_shift g on g.Shift_ShortName = b.ShiftId5
											where EmployeeId=@Employeeid							
										END
							set @start=@start+1
							End
							SELECT ''Msg:DataImportedSuccessfully'' [Message]
				End
				ELSE 
					BEGIN
							SELECT	RecordID=RecordID,
							Employee_Id, 
							Error_Msg,
							date
							FROM @ErrorMsg where flag=0
					END
					drop table #TempShiftData
		COMMIT TRAN ImportAutoShift
	END TRY		
	BEGIN CATCH
		SET @ErrMsg = ERROR_MESSAGE()
		SET @ErrIds = @@ERROR
		ROLLBACK TRAN ImportAutoShift
		RAISERROR(@ErrMsg, 16, @ErrIds, ''Error'')
	END CATCH
	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtenderForReports]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteExtenderForReports]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By : Thilakraj.C
ON- 29-Jul-2013
For Reports AutoComplete Extender
Exec Proc_TA_AutoCompleteExtenderForReports '''',''EmployeeName'',1,0
Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level
Modified By : Manjula.P for dynamic query with checking whether the usergroup is superadmin or not  :Mantis Bug 0025802 (TimecheckV1.5)
*/
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteExtenderForReports] 
	-- Add the parameters for the stored procedure here
	@Id varchar(50),
	@ParameterName varchar(25),
	@EmpAutoId int,
	@ParentLevelId varchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;	
Declare @GradeLevel int
--Added by Manjula.P on 08-Sep-2014 for checking whether it is super admin group or not 
declare @UserGroupName varchar(250)
declare @sqlQuery varchar(max)
set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId  
set @GradeLevel=(select Grade_Level from ta_tbl_grade G
Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
where eDesig.EffectiveDate =
(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) 
and eDesig.EmployeeId=@EmpAutoId )
    -- Insert statements for procedure here
		if(@ParameterName = ''CardNo'')
		 BEGIN
		    IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
				 set @sqlQuery='' select swipecardNo from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID 
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
				where SwipeCardNo like  ''''''+CAST(@Id as varchar(100))+''%''''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+'''''' ''
				if(@UserGroupName<>''SuperAdmin'')
				begin
				SET @sqlQuery = @sqlQuery + '' AND G.Grade_Level>=''''''+cast(@GradeLevel as varchar(150))+'''''' ''  
				end			
				SET @sqlQuery = @sqlQuery + '' Order by swipecardno asc '' 
			  END
		 ELSE
				BEGIN
				SET @sqlQuery ='' select swipecardno from TA_Tbl_Employee where SwipeCardNo like 
				''''''+CAST(@Id as varchar(100))+''%''''			
				and Isdeleted=0 AND ((Employee_Status=1) or		
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))		
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+'''''' Order by swipecardno asc  ''
				END
	END
	else if(@ParameterName=''EmployeeName'')
	 BEGIN
		      IF(@EmpAutoId!=1 and @EmpAutoId!=128)
		      BEGIN
				set @sqlQuery='' select Employee_FirstName + '''' ''''+ Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
			    where Employee_firstName + '''' '''' + Employee_LastName like ''''''+CAST(@Id as varchar(100))+''%''''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+'''''' ''                
                if(@UserGroupName<>''SuperAdmin'')
				begin
                set @sqlQuery=@sqlQuery+'' AND G.Grade_Level>=''''''+cast(@GradeLevel as varchar(150))+'''''' ''  
                end
			 END
		ELSE
			BEGIN
				SET @sqlQuery ='' select Employee_firstName + '''' '''' + Employee_LastName as Employee_firstName  
				from TA_Tbl_Employee where 
				Employee_firstName + '''' '''' + Employee_LastName like ''''''+CAST(@Id as varchar(100))+''%''''
				and Isdeleted=0 AND ((Employee_Status=1) or
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+'''''' ''
			END
	END	
		else if(@ParameterName=''EmployeeId'')		
		BEGIN
				IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN	
				 set @sqlQuery='' select Employee_Code_Id  from TA_Tbl_Employee E 			
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
				inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
				where Employee_Code_Id like ''''''+CAST(@Id as varchar(100))+''%''''
				and E.Isdeleted=0 AND ((Employee_Status=1) or
			   (Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+''''''''
				if(@UserGroupName<>''SuperAdmin'')
				begin
				set @sqlQuery=@sqlQuery+''  AND G.Grade_Level>=''''''+cast(@GradeLevel as varchar(150))+'''''' ''  
				end
				set @sqlQuery=@sqlQuery+'' order by Employee_Code_Id asc ''
              END
		 ELSE
		     BEGIN
				set @sqlQuery='' select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id like  ''''''+CAST(@Id as varchar(100))+''%''''
				and Isdeleted=0 AND ((Employee_Status=1) or				
				(Employee_Status=0 and convert(nvarchar(11),InActiveDate,102)>=convert(nvarchar(11),GETDATE(),102)))				
				and Employee_Code_Id<>''''''+cast(18000000 as varchar(1000))+'''''' order by Employee_Code_Id asc  ''
			END
	END
	exec(@sqlQuery);
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteExtender]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteExtender]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'--Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level 
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteExtender] 
	-- Add the parameters for the stored procedure here
	@Id varchar(50),
	@ParameterName varchar(25),
	@EmpAutoId int,	
	@ParentLevelId varchar(100)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	Declare @GradeLevel int
	--Added by Manjula.P on 08-Sep-2014 for checking whether it is super admin group or not 
	declare @UserGroupName varchar(250)
	declare @sqlQuery varchar(max)
	set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
	select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentLevelId) as LevelId  
	select @GradeLevel=Grade_Level from ta_tbl_grade G
	Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
	inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
	where eDesig.EffectiveDate =
	(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
	and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
    -- Insert statements for procedure here
	if(@ParameterName = ''CardNo'')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
							select swipecardNo from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where SwipeCardNo like ''''+@Id+ ''%''
								AND Employee_Status=1 and Employee_Code_Id<>''18000000'' 
							--where swipecardNo like @RequiredInput + ''%'' and swipecardNo not in(''18000000'') 
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds)) order by swipecardno asc 
						END
					ELSE
						BEGIN
									select swipecardNo from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where SwipeCardNo like ''''+@Id+ ''%''
								AND Employee_Status=1 and Employee_Code_Id<>''18000000'' 
							--where swipecardNo like @RequiredInput + ''%'' and swipecardNo not in(''18000000'') 
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 order by swipecardno asc 
						END
				END
			ELSE
				BEGIN
					select swipecardno from TA_Tbl_Employee where SwipeCardNo like ''''+@Id+ ''%''
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>''18000000'' order by swipecardno asc 
				END
		END
	else if(@ParameterName=''EmployeeName'')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
								select Employee_FirstName + '' '' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
							where 
							Employee_firstName + '' '' + Employee_LastName like '''' + @Id + ''%''
							AND Employee_Status=1 and Employee_Code_Id<>''18000000''
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds))
						END
					ELSE
						BEGIN
							select Employee_FirstName + '' '' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId  
							where 
							Employee_firstName + '' '' + Employee_LastName like '''' + @Id + ''%''
							AND Employee_Status=1 and Employee_Code_Id<>''18000000''
							AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0
						END
				END
			ELSE
				BEGIN
					select Employee_firstName + '' '' + Employee_LastName as Employee_firstName  from TA_Tbl_Employee where 
					Employee_firstName + '' '' + Employee_LastName like '''' + @Id + ''%''
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>''18000000''
			END
		END
	else if(@ParameterName=''EmployeeId'')
		BEGIN
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)
				BEGIN
					if(@isReportingto > 0)
						BEGIN
							select Employee_Code_Id  from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where Employee_Code_Id like '''' + @Id + ''%''
							  AND Employee_Status=1 and Employee_Code_Id<>''18000000'' 
							  AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 and (Employee_ID IN (select * from #EmployeeIds)) order by Employee_Code_Id asc 
						END
					ELSE
						BEGIN
							select Employee_Code_Id  from TA_Tbl_Employee E 			
							inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
							Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
							inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
							inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=E.Employee_Id
							inner join #LevelRights on #LevelRights.LevelId=EL.LevelId
							where Employee_Code_Id like '''' + @Id + ''%''
							  AND Employee_Status=1 and Employee_Code_Id<>''18000000'' 
							  AND G.Grade_Level>=@GradeLevel and E.Isdeleted=0 order by Employee_Code_Id asc 
						END
				END
			ELSE
				begin
					select Employee_Code_Id from TA_Tbl_Employee where Employee_Code_Id like '''' + @Id + ''%''
					and Isdeleted=0 AND Employee_Status=1 and Employee_Code_Id<>''18000000'' order by Employee_Code_Id asc 
				end
		END
		drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_AutoCompleteCommaSeparated]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_AutoCompleteCommaSeparated]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<S.Angeswaran>
-- Create date: <13-Dec-2012>
-- Description:	<To Load the auto complete comma separated>
--Modified By : A.Amsaveni on 30/09/2013 To load the data based on grade level 
--	Proc_TA_AutoCompleteCommaSeparated ''1'',''EmployeeCodeId'',4,0,0
--	Modified by : Manjula.P on 20-Aug-2014 to searching employeeid and employeename based on employee category and employee type selecting criteria
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_AutoCompleteCommaSeparated]
@RequiredInput varchar(80),
@SearchType varchar(50),
@EmpAutoId int,
@EmpCategoryShift int=0,
@EmpTypeShift int=0
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;	
	DECLARE @SQLQuery as nvarchar(max)
	Declare @GradeLevel int	
	declare @UserGroupName varchar(250)
	set @UserGroupName=(select groupName from TA_Tbl_Usergroup where groupId in (
	select UserGroup_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId))
	create table #LevelRights(LevelId int)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	select @GradeLevel=Grade_Level from ta_tbl_grade G
	Inner join Ta_tbl_Title T on T.GradeId=G.Grade_ID
	inner join ta_tbl_employeeDesignation eDesig on eDesig.DesignationId=T.TitleId
	where eDesig.EffectiveDate =
	(Select top 1 EffectiveDate from ta_tbl_employeeDesignation where  ta_tbl_employeeDesignation.EmployeeId=@EmpAutoId 
	and EffectiveDate <=CONVERT(DATETIME, cast(getdate() as nvarchar(50)), 102) order by EffectiveDate desc) and eDesig.EmployeeId=@EmpAutoId
	IF(@SearchType = ''SwipeCardNo'')
	BEGIN 
		  IF(@EmpAutoId!=1 and @EmpAutoId!=128)		  
			BEGIN
			select swipecardNo from TA_Tbl_Employee E 			
			inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
			Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
			inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
			where swipecardNo like @RequiredInput + ''%'' and swipecardNo not in(''18000000'') 
			AND G.Grade_Level>=@GradeLevel AND E.Isdeleted=0
			END
	ELSE
			 BEGIN
			    select swipecardNo from TA_Tbl_Employee where 
                swipecardNo like @RequiredInput + ''%'' and swipecardNo not in(''18000000'') and isdeleted=0				
			 END
	END		
		IF(@SearchType = ''EmployeeCodeId'')
	BEGIN
			  set @SQLQuery=''''
		      IF(@EmpAutoId!=1 and @EmpAutoId!=128)
		       BEGIN	
					set @SQLQuery='' select distinct Employee_Code_Id  from TA_Tbl_Employee E 			
					inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
					Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
					inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
					inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
					inner join ta_tbl_grade G on T.GradeID=G.Grade_ID    
					where Employee_code_Id like ''''''+CAST(@RequiredInput AS VARCHAR(100)) +''%'''' and Employee_code_Id not in(''''18000000'''')
					AND G.Grade_Level>=''''''+CAST(@GradeLevel AS VARCHAR(100))+'''''' ''
					if(@isReportingto > 0)
						BEGIN
						   set @SQLQuery = @SQLQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
						END
		       END	
			  ELSE
			 BEGIN	
				  set @SQLQuery='' select distinct Employee_code_Id from TA_Tbl_Employee E 
				  inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				  Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				  inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				  inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
				  where  Employee_code_Id like ''''''+CAST(@RequiredInput AS VARCHAR(100)) +''%'''' and Employee_code_Id not in(''''18000000'''')	''
			  END	
			 -- IF(@EmpCategoryShift>0)
			 -- BEGIN
				--SET @SQLQuery=@SQLQuery+'' AND T.TitleId = ''+cast(@EmpCategoryShift as varchar(50))+'' ''
			 -- END
			 -- IF(@EmpTypeShift>0)
			 -- BEGIN
				--SET @SQLQuery=@SQLQuery+'' AND TP.TypeId = ''+cast(@EmpTypeShift as varchar(50))+'' ''
			 -- END
			  EXEC(@SQLQuery)
   END
	IF(@SearchType = ''EmployeeName'')
	BEGIN
			set @SQLQuery=''''
			IF(@EmpAutoId!=1 and @EmpAutoId!=128)	
			BEGIN
				set @SQLQuery='' select distinct Employee_FirstName + '''' '''' + Employee_LastName as Employee_FirstName from TA_Tbl_Employee E 	
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId
				inner join ta_tbl_grade G on T.GradeID=G.Grade_ID  
				where  Employee_FirstName + '''' '''' + Employee_LastName 
				like ''''''+cast(@RequiredInput as varchar(100)) + ''%'''' and Employee_FirstName not in(''''Administrator'''')
                AND G.Grade_Level>=''''''+cast(@GradeLevel AS VARCHAR(100))+''''''  ''
                if(@isReportingto > 0)
						BEGIN
						   set @SQLQuery = @SQLQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
						END
			END		
		ELSE
		 BEGIN
				set @SQLQuery='' select distinct Employee_FirstName + '''' '''' + Employee_LastName as Employee_FirstName  from TA_Tbl_Employee E
				inner join ta_tbl_employeeDesignation eDesig on eDesig.EmployeeID=e.Employee_Id
				Inner join Ta_tbl_Title T on eDesig.DesignationID=t.TitleId
				inner join TA_Tbl_EmployeeType ET on ET.EmployeeId=E.Employee_Id
				inner join TA_Tbl_Type TP on TP.TypeId=ET.TypeId 
				where 
                Employee_FirstName + '''' '''' + Employee_LastName like ''''''+cast(@RequiredInput as varchar(100)) + ''%'''' 
                and Employee_FirstName not in(''''Administrator'''') ''					 
                END
		 --IF(@EmpCategoryShift>0)
		 -- BEGIN
			--SET @SQLQuery=@SQLQuery+'' AND T.TitleId = ''+cast(@EmpCategoryShift as varchar(50))+'' ''
		 -- END
		 -- IF(@EmpTypeShift>0)
		 -- BEGIN
			--SET @SQLQuery=@SQLQuery+'' AND TP.TypeId = ''+cast(@EmpTypeShift as varchar(50))+'' ''
		 -- END
		  EXEC(@SQLQuery)
    END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[TotalLeavesAvailedDetails_Employee]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TotalLeavesAvailedDetails_Employee]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<R.Manikandan>
-- Create date: <08-Apr-2019 06:56 PM>
-- Description:	<Get the total leave taken,balance details>
-- TotalLeavesAvailedDetails_Employee 4
-- select * from ta_tbl_employee
-- =============================================
CREATE PROCEDURE [dbo].[TotalLeavesAvailedDetails_Employee]
	@Employee_id bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @YearSettingId INT
	SELECT @YearSettingId = YearSettings_Id from TA_tbl_YearSetting where IsActive=1
	Declare @EarnedLeave decimal(18,1)
	Declare @LOP decimal(18,1)
	Declare @LeaveBal decimal(18,1)
	Declare @WaiveOff decimal(18,1)
	if not exists(select LeaveApplication_Id from TA_Tbl_LeaveApplication where Employee_Id=@Employee_id and IsDeleted=0)
	begin
		select	@EarnedLeave	=0,
				@LOP			=0,
				@LeaveBal		=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0)),
				@WaiveOff		=0
		from TA_tbl_Yearclosure yc  
		inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
		inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
		left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
		where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
		and la.Status  not in (''Rejected'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'')   
		and la.IsBorrow=0 group by la.LeaveType_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
	end
	else
	begin
		CREATE TABLE #Temp(Employee_id bigint,EarnedLeave decimal(18,1),LOP decimal(18,1),LeaveBal decimal(18,1),WaiveOff decimal(18,1))
		Insert into #Temp(Employee_id)values(@Employee_id)
		--select * from #Temp
		update T set LeaveBal=a.NumberOfDays from #Temp T inner join
		(
			select	yc.Employee_id,NumberOfDays=(ISNULL(yc.carry_PrevYear,0.0)+ ISNULL(yc.Current_Quota,0.0))- (ISNULL(sum(la.NumberOfDays),0.0) + ISNULL(yc.Encashment,0.0))
			from TA_tbl_Yearclosure yc  
			inner join TA_Tbl_YearSetting ys on yc.Year_SettingID=ys.YearSettings_Id   
			inner join TA_Tbl_LeaveType lt on lt.LeaveType_Id=yc.LeaveTypeID  
			left outer join Ta_Tbl_LeaveApplication la on  la.LeaveType_Id =lt.LeaveType_Id and  la.YearSettings_Id=ys.YearSettings_Id  
			where yc.employee_Id=@Employee_Id and la.employee_Id=@Employee_Id and ys.YearSettings_Id=@YearSettingId and la.Isdeleted=0
			and la.Status  not in (''Rejected'') and la.Type not in (''Restricted Holiday'',''Comp Off'',''ESI'')   
			and la.IsBorrow=0 group by yc.Employee_Id,lt.LeaveType,la.Type,yc.Carry_PrevYear,yc.Current_Quota,yc.Encashment
		)as a on a.Employee_Id=T.Employee_id
		update T set EarnedLeave=b.ELNumberOfDays,LOP=b.LOPNumberOfDays,WaiveOff=b.WONumberOfDays from #Temp T inner join
		(
			select ELNumberOfDays=sum(ELNumberOfDays),WONumberOfDays=sum(WONumberOfDays),LOPNumberOfDays=sum(LOPNumberOfDays),Employee_Id from
			( 
				select  ELNumberOfDays=case when lt.LeaveType=''EL'' and la.Type!=''LOP'' then la.NumberOfDays else 0 end,
						WONumberOfDays=case when lt.LeaveType=''WO'' then la.NumberOfDays else 0 end,
						LOPNumberOfDays=case when la.Type=''LOP'' then la.NumberOfDays else 0 end,
						Employee_Id from TA_Tbl_LeaveApplication la
				inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
				where la.Status  not in (''Rejected'') and la.IsDeleted=0				
			)as a group by Employee_Id
		)as b on b.Employee_Id=T.Employee_id
		--update T set WaiveOff=a.NumberOfDays from #Temp T inner join
		--(
		--	select  NumberOfDays=SUM(la.NumberOfDays),Employee_Id,la.LeaveType_id from TA_Tbl_LeaveApplication la
		--	inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
		--	where lt.LeaveType=''WO'' and la.Status  not in (''Rejected'') and la.IsDeleted=0
		--	group by Employee_Id,la.LeaveType_id
		--)as a on a.Employee_Id=T.Employee_id
		--update T set LOP=a.NumberOfDays from #Temp T inner join
		--(
		--	select  NumberOfDays=SUM(la.NumberOfDays),Employee_Id,la.LeaveType_id from TA_Tbl_LeaveApplication la
		--	inner join TA_Tbl_LeaveType lt on la.LeaveType_id=lt.LeaveType_Id
		--	where la.Type=''LOP'' and la.Status  not in (''Rejected'') and la.IsDeleted=0
		--	group by Employee_Id,la.LeaveType_id
		--)as a on a.Employee_Id=T.Employee_id
		select	@EarnedLeave=EarnedLeave,@LOP=LOP,@LeaveBal=LeaveBal,@WaiveOff=WaiveOff from #Temp
	end
	Declare @ConcernName varchar(500)
	--select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id
	select top 1 @ConcernName=name from Ta_Tbl_levelDetails where description in(select substring(Employee_Code_Id,1,2) from TA_Tbl_Employee where Employee_Id=@Employee_id)
	select	LeaveTaken=(isnull(@EarnedLeave,0)+isnull(@LOP,0)+isnull(@WaiveOff,0)),
			EarnedLeave=isnull(@EarnedLeave,0),
			LOP=isnull(@LOP,0),
			LeaveBal=isnull(@LeaveBal,0),
			WaiveOff=isnull(@WaiveOff,0),
			ConcernName=isnull(@ConcernName,'''')
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[sampleCount]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sampleCount]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
Create Procedure [dbo].[sampleCount]
(
	@TitleName NVARCHAR(50),
	@TitleDescription NVARCHAR(50),
	@TitleId int
) 
As
DECLARE @Isdel int
SET @Isdel=1
BEGIN
	Select Count(TitleName)as TName from TA_Tbl_Title
		where TitleId<>@TitleId And TitleName=@TitleName AND TitleDescription=@TitleDescription AND Isdeleted=@Isdel	
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[ReProcessEmpData]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReProcessEmpData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[ReProcessEmpData] @CompID VARCHAR(2),@frmdate datetime,@todate datetime
as
declare @Process_Rec_ID varchar(20)
declare @EmpID varchar(20)
declare @employeeid varchar(20)
declare @Company varchar(30)
declare @mSql varchar(200)
declare @Emp_Date datetime
declare @val varchar(20)
declare @Shift_Id varchar(10)
declare @NormOT varchar(5)
declare @OffOT varchar(5)
declare @HolOT varchar(5)
declare @OTtype varchar(1)
declare @eCount int
declare @MonthClosure_Id int
declare @totpresent int
declare @totAbsent int
declare @totHoliday int
declare @S_wH varchar(10) 
declare @S_wmin varchar(10) 
declare @S_workingHour varchar(10) 
declare @Shift_TotalWHours varchar(6) 
declare @WHours int
declare @shiftID int
declare @NewshiftID int
declare @totHrsWorks int
declare @totHrsOT int
declare @totNormOT int
declare @totOffOT int
declare @totHolOT int
declare @totEarlyOut int
declare @totLateIn int
declare @totWorkHrs int
declare @totHrsLess int
declare @totHrsExtra int
declare @employee_status int
declare @fromdate datetime
set @fromdate=@frmdate
select @eCount=(select count(*) from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID)
if (@eCount=0)
begin
		insert into dbo.TA_Tbl_MonthClosure(OrgLevel_Id,MonthClosure_Month,MonthClosure_Year,MonthClosure_StartDate,MonthClosure_EndDate,MonthClosure_ClosingDate,Emp_Id,Process,TimeStamp,IsDeleted,YearSettings_Id)
		values (@CompID,DateName(mm,@todate),year(@todate),@frmdate,@todate,getdate(),2,''N'',getdate(),''False'',1)
		set @MonthClosure_Id=(select MonthClosure_Id from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID )
end
else
begin
		set @MonthClosure_Id=(select MonthClosure_Id from dbo.TA_Tbl_MonthClosure  where MonthClosure_Month=DateName(mm,@todate) and 
				MonthClosure_Year=year(@todate) and OrgLevel_Id=@CompID )
end
declare emp_ReProcess cursor for 
--select EmpID,Company from  dbo.View_companyEmployees where id=@CompID order by empid
select EmpID,Company from  dbo.View_companyEmployees where id=@CompID and EmpID in(
SELECT     Employee_Code_Id
FROM         View_UnProcessEMPdata
GROUP BY Employee_Code_Id)
open emp_ReProcess
fetch emp_ReProcess into  @EmpID,@Company
while (@@fetch_status = 0 )
begin
select @fromdate=@frmdate
set @employee_status= (select employee_status from dbo.TA_Tbl_Employee where swipecardno=@EmpID)
While @fromdate <= @todate
begin
     set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
if (@eCount=0)
begin
			insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
			values(@EmpID,@fromdate,0,''Absent'',0)
end
if (@employee_status=0)
begin
	update dbo.TA_Tbl_ProcessedData set processflag=1 where Employee_Code_Id=@EmpID and  Date= @fromdate
end
set @employeeid=(select max(employee_ID) from ta_tbl_employee where swipecardno=@EmpID)
set @eCount=( select count(*) from TA_Tbl_PermanentShiftAllocation where employeeid=@employeeid and year=year(@fromdate) and month=month(@fromdate))
if (@eCount=0)
begin
insert into TA_Tbl_PermanentShiftAllocation(EmployeeId,year,month,TimeStamp,DateShift,Emp_Id) 
values(@employeeid,year(@fromdate),month(@fromdate),getdate(),dateadd(d,-1*(day(@fromdate)-1),@fromdate),1)
end
select @shiftID=(select isnull(Shift_Id,0)  from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
select @msql =''update TA_Tbl_PermanentShiftAllocation set Day'' +ltrim(str(day(@fromdate)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @employeeid +'''''' and month=''''''+ ltrim(str(month(@fromdate))) +'''''' and year=''''''+ltrim(str(year(@fromdate))) +''''''''
exec  (@mSql)
set @Shift_TotalWHours=''''
if  (@shiftID=166 )
begin
	set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
	update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@EmpID and Date= @fromdate
	set @shiftID=@NewshiftID
end
set @eCount=( select count(*) from dbo.TA_Tbl_Shift where Level_Id=@CompID and Shift_Id=  @shiftID)
if (@eCount=0)
begin
	set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
	update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@EmpID and Date= @fromdate
	set @shiftID=@NewshiftID
end
set @employeeid=(select max(employee_ID) from ta_tbl_employee where swipecardno=@EmpID)
set @eCount=( select count(*) from TA_Tbl_PermanentShiftAllocation where employeeid=@employeeid and year=year(@fromdate) and month=month(@fromdate))
if (@eCount=0)
begin
insert into TA_Tbl_PermanentShiftAllocation(employeeid,year,month,TimeStamp,DateShift,Emp_Id) values(@employeeid,year(@fromdate),month(@fromdate),getdate(),dateadd(d,-1*(day(@fromdate)-1),@fromdate),1)
end
select @msql =''update TA_Tbl_PermanentShiftAllocation set Day'' +ltrim(str(day(@fromdate)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @employeeid +'''''' and month=''''''+ ltrim(str(month(@fromdate))) +'''''' and year=''''''+ltrim(str(year(@fromdate))) +''''''''
exec  (@mSql)
if  (@shiftID>0)
begin
	set @Shift_TotalWHours =(select isnull(Shift_TotalWorkingHours,'''') from dbo.TA_Tbl_Shift where Shift_Id = @shiftID)
end
 if  (@Shift_TotalWHours='''')
begin
	set @Shift_TotalWHours =''09:00''
--(select isnull(Shift_TotalWorkingHours,'''') from dbo.TA_Tbl_Shift where Shift_Id = @shiftID)
end 
--update dbo.TA_Tbl_ProcessedData set WorkHrs=@Shift_TotalWHours where Employee_Code_Id =@EmpID and Date= @fromdate
select @S_workingHour=(select isnull(HrsWork,''0'') from  dbo.TA_Tbl_ProcessedData  where Employee_Code_Id =@EmpID and Date= @fromdate)
if (@S_workingHour=''0'')
begin
select @WHours=(select abs(datediff(minute,intime,outtime)) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Date= @fromdate)
if (isnumeric(@WHours)=1)
begin
	if (@WHours<1200)
	begin
			select @S_wH=convert(char,convert(int,(@WHours/60),2),2)
			select @S_wmin= convert(int,@WHours)%60
			if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
			if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
			select @S_workingHour= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
--
--if @RoundEnable=''Y''
--begin
--
--if (convert(int,@pHrsOT_mm)<=15 )
--	begin
--	select @pHrsOT_mm=''00''
--	end
--if (convert(int,@pHrsOT_mm)>15) and (convert(int,@pHrsOT_mm)<=30 )
--	begin
--	select @pHrsOT_mm=''30''
--	end
--if (convert(int,@pHrsOT_mm)>30 and  convert(int,@pHrsOT_mm)<=45 )
--	begin
--	select @pHrsOT_mm=''30''
--	end
--
--if  convert(int,@pHrsOT_mm)>45  
--	begin
--	select @pHrsOT_mm=''00''
--	select @pHrsOT_hh=convert(int,@pHrsOT_hh)+1
--	if (len(rtrim(@pHrsOT_hh))=1) select @pHrsOT_hh= ''0''+@pHrsOT_hh
--	end
--
---- end of  Rounding off
--end
-- 	select @pHrsOT =rtrim(@pHrsOT_hh)+'':''+rtrim(@pHrsOT_mm)
--
			--update dbo.TA_Tbl_ProcessedData set HrsWork=@S_workingHour,WorkHrs=@Shift_TotalWHours where Employee_Code_Id =@EmpID and Date= @fromdate
end
	end
end   
select @fromdate = DateAdd("D", 1, @fromdate)
end
--
--
--
--set @totpresent = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Attendance =''Present'' and date between @frmdate and @todate)
--set @totAbsent = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and (Attendance =''Absent'' or Attendance is null) and date between @frmdate and @todate)
--set @totHoliday = (select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and Attendance =''Weekly Off'' and date between @frmdate and @todate)
--set @totHrsWorks=(select sum(datediff(minute,''00:00'',isnull(hrsWork,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate)          
--
--set @totHrsOT =(select sum(datediff(minute,''00:00'',isnull(HrsOT,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate)          
--set @totNormOT =(select sum(datediff(minute,''00:00'',isnull(NormOT,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHolOT =(select sum(datediff(minute,''00:00'',isnull(HolOT,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totEarlyOut =(select sum(datediff(minute,''00:00'',isnull(EarlyOut,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totLateIn =(select sum(datediff(minute,''00:00'',isnull(LateIn,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totWorkHrs =(select sum(datediff(minute,''00:00'',isnull(WorkHrs,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHrsLess =(select sum(datediff(minute,''00:00'',isnull(HrsLess,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--set @totHrsExtra =(select sum(datediff(minute,''00:00'',isnull(HrsExtra,''00:00''))) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@EmpID and date between @frmdate and @todate) 
--
--declare @p_totHrsWork varchar(10)
--declare @p_totHrsOT varchar(10)
--declare @p_totNormOT varchar(10)
--declare @p_totOffOT varchar(10)
--declare @p_totHolOT varchar(10)
--declare @p_totEarlyOut varchar(10)
--declare @p_totLateIn varchar(10)
--declare @p_totWorkHrs varchar(10)
--declare @p_totHrsLess varchar(10)
--declare @p_totHrsExtra varchar(10)
--
--select @S_wH=convert(char,convert(int,(@totHrsWorks/60),2),2)
--select @S_wmin= convert(int,@totHrsWorks)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
--select @p_totHrsWork= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,( @totHrsOT/60),2),2)
--select @S_wmin= convert(int, @totHrsOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
--select @p_totHrsOT= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,(@totNormOT/60),2),2)
--select @S_wmin= convert(int,@totNormOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
--select @p_totNormOT= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
--select @S_wH=convert(char,convert(int,(@totOffOT/60),2),2)
--select @S_wmin= convert(int,@totOffOT)%60
--if (len(rtrim(@S_wH))=1) select @S_wH= ''0''+@S_wH
--if (len(rtrim(@S_wmin))=1) select @S_wmin= ''0''+@S_wmin
--select @p_totOffOT= rtrim(@S_wH) +'':''+   rtrim(@S_wmin)
--
--delete from dbo.TA_Tbl_PayrollProcessDetails where MonthClosure_Id=@MonthClosure_Id and Employee_Id=@EmpID 
--insert into dbo.TA_Tbl_PayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,AbsentDays,PresentDays,Holidays,LOPDays,Emp_Id,TimeStamp)
--values(@MonthClosure_Id,@EmpID,@p_totHrsWork,@p_totHrsOT,@p_totNormOT,@p_totOffOT,@totAbsent,@totpresent,@totHoliday,0,2,getdate())
  fetch emp_ReProcess into @EmpID,@Company
end   
deallocate emp_ReProcess' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataTiffany]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataTiffany]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'Create procedure [dbo].[RemoveDiscrepancyDataTiffany] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''4%''
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''3%''
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate=''2009-10-15 00:00:00.000'' or Clk_outDate=''2009-10-15 00:00:00.000'')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark=''Script IN on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_inDATE)))+''Shift''
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark=''1''
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script in 1 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name=''166'' or rtrim(@shift_name)=''0''
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #shiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_inDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_inDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_inDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID=''-1'' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+''no data with out in. so create an out based on the shift''
			set @remark=''Script in 3 on'' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark=''Script in 51 on'' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script in 52 on'' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark=''Script in 56 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
else
begin
set @remark=''Script in 57 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark=''Script in 5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark=''Script in 4Match case on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark=''Script in 3 on'' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script in 7  on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark=''Script in 3Matchcase on'' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script in 21 on'' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark=''20''
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark=''Script Out11 on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_outDATE)))+''Shift''
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script Out2 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name=''0'' or @shift_name=''166'' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_outDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_outDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_outDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID=''-1''
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=''no data with out in. so create an out based on the shift''
		set @remark=''Script Out 33 on'' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,''00:00''),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark=''Script out Void51 on'' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script out Void52 on'' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark=''Script out Void5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark=''Script out Void4 m on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script out Void6 on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark=''Script out Void61 on'' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script Out 10 on'' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataOMAN]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataOMAN]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[RemoveDiscrepancyDataOMAN] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''4%''
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''3%''
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in(''20039'')or Clk_outDeviceId in(''20039'')) order by Clk_OutDate
--and (Clk_inDate=''2009-10-15 00:00:00.000'' or Clk_outDate=''2009-10-15 00:00:00.000'')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark=''Script IN on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_inDATE)))+''Shift''
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark=''1''
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script in 1 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name=''166'' or rtrim(@shift_name)=''0''
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #shiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_inDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_inDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_inDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID=''-1'' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+''no data with out in. so create an out based on the shift''
			set @remark=''Script in 3 on'' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark=''Script in 51 on'' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script in 52 on'' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark=''Script in 56 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
else
begin
set @remark=''Script in 57 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark=''Script in 5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark=''Script in 4Match case on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark=''Script in 3 on'' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script in 7  on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark=''Script in 3Matchcase on'' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script in 21 on'' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark=''20''
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark=''Script Out11 on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_outDATE)))+''Shift''
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script Out2 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name=''0'' or @shift_name=''166'' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_outDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_outDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_outDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID=''-1''
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=''no data with out in. so create an out based on the shift''
		set @remark=''Script Out 33 on'' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,''00:00''),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark=''Script out Void51 on'' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script out Void52 on'' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark=''Script out Void5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark=''Script out Void4 m on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script out Void6 on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark=''Script out Void61 on'' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script Out 10 on'' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyDataIFFCO]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyDataIFFCO]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[RemoveDiscrepancyDataIFFCO] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''4%''
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''3%''
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
--where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate=''2009-10-15 00:00:00.000'' or Clk_outDate=''2009-10-15 00:00:00.000'')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark=''Script IN on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_inDATE)))+''Shift''
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark=''1''
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script in 1 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name=''166'' or rtrim(@shift_name)=''0''
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #shiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_inDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_inDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_inDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID=''-1'' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+''no data with out in. so create an out based on the shift''
			set @remark=''Script in 3 on'' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark=''Script in 51 on'' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script in 52 on'' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark=''Script in 56 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
else
begin
set @remark=''Script in 57 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark=''Script in 5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark=''Script in 4Match case on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark=''Script in 3 on'' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script in 7  on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark=''Script in 3Matchcase on'' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script in 21 on'' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark=''20''
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark=''Script Out11 on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_outDATE)))+''Shift''
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script Out2 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name=''0'' or @shift_name=''166'' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_outDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_outDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_outDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID=''-1''
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=''no data with out in. so create an out based on the shift''
		set @remark=''Script Out 33 on'' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,''00:00''),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark=''Script out Void51 on'' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script out Void52 on'' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark=''Script out Void5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark=''Script out Void4 m on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script out Void6 on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark=''Script out Void61 on'' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script Out 10 on'' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData' 
END
GO
/****** Object:  StoredProcedure [dbo].[RemoveDiscrepancyData]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveDiscrepancyData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[RemoveDiscrepancyData] 
as
declare @timeVal int
declare @CLK_ID varchar(20)
declare @CLK_CARDID varchar(20)
declare @CLK_inDEVICEID varchar(20)
declare @CLK_inDATE datetime
declare @CLK_inTIME datetime
declare @CLK_outDEVICEID varchar(20)
declare @CLK_outDATE datetime
declare @CLK_outTIME datetime
declare @A_OutDateTime  datetime
declare @A_InDateTime  datetime
declare  @cyear varchar(4)
declare  @cmonth varchar(2)
declare  @cday varchar(2)
declare @M_day varchar(10)
declare @msql  varchar(500)
declare @CardNo varchar(20)
declare @EMP_ID varchar(10)
declare @tdatetime varchar(25)
declare @eCount int
declare	@twmin int
declare @tsftmin int
declare @shift_name	varchar(10)
declare @remark varchar(50) 
declare @Shift_StartTime varchar(10)
declare @Shift_EndTime varchar(10)
declare @Shift_WorkingHours varchar(5)
declare @CompID VARCHAR(3)
declare @shiftID int
declare @NewshiftID int
set @timeVal=15
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''4%''
--update TA_Tbl_ProcessedData set hrswork=''10:00'',outtime=right(convert(varchar,dateadd(hh,10,intime),100),8) 
--where hrsWork like ''3%''
--tiff   (1,2,3,7,10,15,6,12)
declare RemoveDiscrepancyData cursor for 
select Clk_Id,Clk_EmpId,Clk_inDeviceId,Clk_inDate,Clk_inTime,Clk_outDeviceId,Clk_outDate,Clk_outTime from dbo.View_Discrepancy
--where Clk_inDeviceId in(4,5,13,14)or Clk_outDeviceId in(4,5,13,14) order by Clk_OutDate
where (Clk_inDeviceId in(1,2,3,7,10,15,6,12,17)or Clk_outDeviceId in(1,2,3,7,10,15,6,12,17)) order by Clk_OutDate
--and (Clk_inDate=''2009-10-15 00:00:00.000'' or Clk_outDate=''2009-10-15 00:00:00.000'')
open RemoveDiscrepancyData
fetch RemoveDiscrepancyData into @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
while (@@fetch_status = 0 )
begin
set @EMP_ID=(select max(Employee_Id) as Employee_Id From dbo.TA_Tbl_Employee where SwipeCardNo=@CLK_CARDID)
if (len(@CLK_inDATE)>0 and @CLK_inDATE is not null )
	begin -- indata
set @remark=''Script IN on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_inDATE)
set @cmonth= month(@CLK_inDATE)
set @cday= day(@CLK_inDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_inDATE)))+''Shift''
--		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE =@CLK_inDATE  AND clk_OUTDate is not null and isvoid=0  )
--			if (@eCount=0)--checking the  ClockDetails have any matched case
--				begin--1
--				set @remark=''1''
					--No match case in  ClockDetails 
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script in 1 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_inDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		if (@eCount>1)
			begin
						delete from dbo.TA_Tbl_ProcessedData where Employee_Code_Id=@CLK_CARDID and Date= @CLK_inDATE
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_inDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE)
				set @shiftID=@shift_name
	if @shift_name=0 or @shift_name=''166'' or rtrim(@shift_name)=''0''
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				set @shiftID=@NewshiftID
			end	
				create table #shiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #shiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #shiftlist )
				drop table #shiftlist
			if @eCount=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_inDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_inDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_inDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_inDATE
				end
		--Find shift end								
		if @shiftID=''-1'' or @shift_name=0
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=@remark+''no data with out in. so create an out based on the shift''
			set @remark=''Script in 3 on'' + Convert(varchar,getdate())					
		set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME)
		set @twmin=datediff(Minute,@CLK_inDATE + @CLK_inTime,@A_OutDateTime+@Shift_EndTime)
		set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_inDATE + @Shift_StartTime,@CLK_inDATE + @CLK_inTime)
					set @remark=''Script in 51 on'' + Convert(varchar,getdate())	
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script in 52 on'' + Convert(varchar,getdate())	
		set @twmin=	datediff(Minute,@CLK_inDATE + @Shift_EndTime,@CLK_inDATE + @CLK_inTime)
if @twmin>=0
begin
set @remark=''Script in 56 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																									Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
else
begin
set @remark=''Script in 57 on'' + Convert(varchar,getdate())	
update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
																									Clk_OutDate=@CLK_inDATE,
																									Clk_OutTime=@Shift_EndTime,
																							Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
end
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
							end	
				end--5
				else
				begin --5-1
					set @remark=''Script in 5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
					set @remark=''Script in 4Match case on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
set @remark=''Script in 3 on'' + Convert(varchar,getdate())
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
				set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
					AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime or 
					CLK_outDATE+CLK_outtime between @CLK_inDATE + @CLK_inTime and @A_OutDateTime)and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script in 7  on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE AND clk_OUTTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_inDEVICEID , ''Out''),
													Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_OutTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_inDATE
			end
			else
			begin --6-1
					set @remark=''Script in 3Matchcase on'' + Convert(varchar,getdate())
				--- alredy have a match cae on the same timing 
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script in 21 on'' + Convert(varchar,getdate())	
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_inDATE  or ManualTimeEntry_OUTDate =@CLK_inDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
--				end
--				else
--				begin 
--						set @remark=''20''
--						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=GetDate() where CLK_ID=@CLK_ID
--					--match case in  ClockDetails 
--
--				end
	end
------------------------------------------------------------------------------------------------------------------------
else-- out data 
begin 
set @remark=''Script Out11 on'' + Convert(varchar,getdate())
set @cyear= year(@CLK_outDATE)
set @cmonth= month(@CLK_outDATE)
set @cday= day(@CLK_outDATE)
set @M_day=''Day''+LTrim(str(day(@CLK_outDATE)))+''Shift''
	set @eCount=(select count(ManualTimeEntry_Employee_Id)  from dbo.Ta_Tbl_ManualTimeEntry where   ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_outDate =@CLK_outDATE  or ManualTimeEntry_INDate =@CLK_outDATE)  )
	if (@eCount=0)--checking the for  Manual entry 
	begin --2
		set @remark=''Script Out2 on'' + Convert(varchar,getdate())
		--No match case in  ClockDetails 
		----Finding teh shift
			  set @eCount=( select count(*) from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date=@CLK_OUTDATE)
			if (@eCount=0)
			begin
						insert into dbo.TA_Tbl_ProcessedData(Employee_Code_Id,Date,Shift_Id,Attendance,processflag)
						values(@CLK_CARDID,@CLK_OUTDATE,0,''Absent'',0)
			end
		set @shift_name=( select isnull(Shift_Id,''166'') from dbo.TA_Tbl_ProcessedData where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE)
		set @shiftID=@shift_name
	if @shift_name=''0'' or @shift_name=''166'' 
			begin
				set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
				set  @NewshiftID =(select isnull(min(Shift_Id),1) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
				update dbo.TA_Tbl_ProcessedData set Shift_Id=@NewshiftID where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				set @shiftID=@NewshiftID
			end	
				create table #oshiftlist (Emp_ID char(8), Shift varchar(20) null)
				select @msql =''insert into #oshiftlist(Emp_ID,Shift)select EMP_ID,''+@M_day+'' FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=''''''+@EMP_ID+'''''' and Year=''''''+@cyear+'''''' and Month=''''''+@cmonth+''''''''
				exec (@msql)
				set @eCount=(select count(EmployeeId) FROM dbo.TA_Tbl_TemporaryShiftAllocation where EmployeeId=@EMP_ID and Year=@cyear and Month=@cmonth)
				select @shift_name =(SELECT Shift  FROM  #oshiftlist )
				drop table #oshiftlist
			if @eCount=0 or @shift_name=0
				BEGIN
					select @msql =''update dbo.TA_Tbl_TemporaryShiftAllocation set Day'' +ltrim(str(day(@CLK_outDATE)))+ ''Shift =''''''+ltrim(str(@shiftID)) + '''''' where  employeeid= '''''' + @EMP_ID +'''''' and month=''''''+ ltrim(str(month(@CLK_outDATE))) +'''''' and year=''''''+ltrim(str(year(@CLK_outDATE))) +''''''''
					exec  (@mSql)
					select @shift_name=@shiftID
				END
				else
				begin
					update dbo.TA_Tbl_ProcessedData set Shift_Id=@shift_name where Employee_Code_Id =@CLK_CARDID and Date= @CLK_OUTDATE
				end
		--Find shift end								
		if @shiftID=''-1''
		begin
			set @CompID =(select isnull(id,0) from View_companyEmployees where empid=@CLK_CARDID)
			set  @NewshiftID =(select min(Shift_Id) from dbo.TA_Tbl_Shift where  Level_Id=@CompID)
			set @shift_name=@NewshiftID
		end
		set @Shift_StartTime= (select Shift_StartTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set	@Shift_EndTime= (select Shift_EndTime from dbo.TA_Tbl_Shift where shift_id=@shift_name)
		set @Shift_WorkingHours = (select Shift_TotalWorkingHours from dbo.TA_Tbl_Shift where shift_id=@shift_name)
	-- find any entry with out in 
	set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_OUTDATE is null   AND clk_inDate =@CLK_OUTDATE  and clk_inDate+clk_intime < @CLK_OUTDATE + @CLK_OUTTime and isvoid=0  )
if (@eCount=0) 
	begin--3
		-- no data with out in. so create an out based on the shift 
		set @remark=''no data with out in. so create an out based on the shift''
		set @remark=''Script Out 33 on'' + Convert(varchar,getdate())
				set @A_OutDateTime= DATEADD(Minute, DATEDIFF(n,@Shift_WorkingHours,''00:00''),@CLK_outDATE+@CLK_outTIME)
				set	@twmin=datediff(Minute,@A_OutDateTime,@CLK_outDATE + @CLK_outTime)
				set @tsftmin=datediff(Minute,''00:00'',@Shift_WorkingHours)
--find the is any data based on this duration 
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime and isvoid=0)
		and isvoid=0  )
		if @eCount=0--4
			begin--4
		-- no other data on this duration 
				if (@twmin >= @tsftmin)
				begin--5
					set @twmin=datediff(Minute,@CLK_outDATE + @Shift_StartTime,@CLK_outDATE + @CLK_outTime)
							if  (@twmin<0)
							begin
							 -- if he comes before shift time 
									set @remark=''Script out Void51 on'' + Convert(varchar,getdate())
											update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																									Clk_OutDate=Convert(varchar(15),@A_OutDateTime,101),
																				Clk_OutTime=Convert(varchar,DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_OUTDATE+@CLK_OUTTIME), 114),
																						Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end
							if  (@twmin>=0)
							begin													
									set @remark=''Script out Void52 on'' + Convert(varchar,getdate())
	update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
--update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
																								--	Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
																								--	Clk_inTime=@Shift_EndTime,
																							--Clk_Remarks=@remark,Clk_Process=''Y'' where CLK_ID=@CLK_ID
								update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
							end	
				end--5
				else
				begin --5-1
						--- alredy have a match cae on the same timing 
						set @remark=''Script out Void5 on'' + Convert(varchar,getdate())
						if @CLK_CARDID=''''
						begin
									set @remark=''Script NO Card '' + Convert(varchar,getdate())
						end
						update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
				end								
			end
			else--4-1
					begin --4-1
							--- alredy have a match cae on the same timing 
							set @remark=''Script out Void4 m on'' + Convert(varchar,getdate())
							update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
					end		
											--Convert(varchar,  DATEADD(Minute, DATEDIFF(n, ''00:00'',  @Shift_WorkingHours),@CLK_inDATE+@CLK_inTIME), 114),
			end
		else--3
		begin--3-1
			--if there is more than one record on the OUT with no in
			set @A_OutDateTime=(select max(clk_OUTDate+clk_OUTtime)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_INDATE is null   AND clk_OUTDate =@CLK_inDATE  and clk_OUTDate+clk_OUTtime > @CLK_inDATE + @CLK_inTime and isvoid=0  )
		set @eCount=(select count(clk_EmpID)  from dbo.TA_Tbl_ClockDetails where  CLK_ID<>@CLK_ID 
		AND clk_EmpID=@CLK_CARDID and (CLK_inDATE+CLK_intime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime or 
		CLK_outDATE+CLK_outtime between @CLK_OUTDATE + @CLK_OUTTime and @A_OutDateTime)	and isvoid=0  )
		if @eCount=0--6
			begin--6
				set @remark=''Script out Void6 on'' + Convert(varchar,getdate())
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID<>@CLK_ID and clk_EmpID=@CLK_CARDID and CLK_outDATE is null   AND clk_inDate =@CLK_outDATE AND clk_inTime <>Convert(varchar, @A_OutDateTime, 114)  and isvoid=0 
				update dbo.TA_Tbl_ClockDetails set Clk_OutDeviceId=dbo.Func_TA_SelectMatchingDevice(@CLK_outDEVICEID , ''IN''),
													Clk_inDate=Convert(varchar(15),@A_OutDateTime,101),
													Clk_inTime=Convert(varchar, @A_OutDateTime, 114),
													Clk_Remarks=@remark,Clk_Process=''Y''	 where CLK_ID=@CLK_ID
				update dbo.TA_Tbl_ProcessedData set processflag=0,attendance=''Present'' where employee_code_id=@CLK_CARDID and date=@CLK_OUTDATE
			end
			else
			begin --6-1
				--- alredy have a match cae on the same timing 
				set @remark=''Script out Void61 on'' + Convert(varchar,getdate())	
				update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks=@remark where  CLK_ID=@CLK_ID 
			end		
		end
end--2
else
	begin --2-1
	set @remark=''Script Out 10 on'' + Convert(varchar,getdate())
	--update dbo.TA_Tbl_ClockDetails set isvoid=1,Clk_Remarks= GetDate() where CLK_ID=@CLK_ID
	--Nothing to do manauly done 
	update dbo.Ta_Tbl_ManualTimeEntry set isdeleted=1 where   
	ManualTimeEntry_Employee_Id=@EMP_ID and (ManualTimeEntry_InDate =@CLK_OUTDATE  or ManualTimeEntry_OUTDate =@CLK_OUTDATE)  
	and ManualTimeEntry_Reason =''Script Entry''
									-- can delete the data  or set void flag
	end
	end
  fetch RemoveDiscrepancyData into  @CLK_ID,@CLK_CARDID,@CLK_inDEVICEID,@CLK_inDATE,@CLK_inTIME,@CLK_outDEVICEID,@CLK_outDATE,@CLK_outTIME
end   
deallocate RemoveDiscrepancyData' 
END
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternDeleteById]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPatternDeleteById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE  PROCEDURE [dbo].[SelectShiftPatternDeleteById]
AS
DECLARE @Isdel int
SET @Isdel=0
BEGIN
	SET NOCOUNT ON;
	SELECT * FROM TA_Tbl_ShiftRoaster WHERE Isdeleted=@Isdel 
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPatternById]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPatternById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*
Modified by	:	P.Prabakaran
Modified on	:	06-Feb-08
*/
CREATE    PROCEDURE [dbo].[SelectShiftPatternById](@PatternId int)
AS
	DECLARE @Isdel int
	SET @Isdel=0
	BEGIN
		SET NOCOUNT ON;
		--SELECT * FROM TA_Tbl_ShiftPattern WHERE Isdeleted=@Isdel and ShiftPattern_Id=@PatternId
		SELECT TA_Tbl_ShiftPattern.*,TA_Tbl_Leveldetails.Name 
		FROM TA_Tbl_ShiftPattern INNER JOIN TA_Tbl_Leveldetails ON TA_Tbl_ShiftPattern.Level_Id=TA_Tbl_Leveldetails.ID  
		WHERE ShiftPattern_Id=@PatternId
	END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[SelectShiftPattern]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelectShiftPattern]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,Janakaraj>
-- ALTER  date: <ALTER  Date,,04July2007>
-- Description:	<Description,,>
-- SelectShiftPattern ''SuperAdmin'',''1,137,138,2,3,140,47,113,132,134,135,150,136,145,146,147,151,152,153,154,155,159,160,161,162,133''
-- =============================================
CREATE  PROCEDURE [dbo].[SelectShiftPattern]
@usergroupname nvarchar(250),
@UserLevels nvarchar(2000),
@ParentID int
AS
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
DECLARE @Isdel int
declare @Query as varchar(7000)
SET @Isdel=0
if(@usergroupname=''SuperAdmin'')
	BEGIN
		SET NOCOUNT ON;
		--set @Query = ''SELECT LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,SP.Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id WHERE SP.Level_Id in ( ''+ @UserLevels +'' )''
		set @Query = ''SELECT LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,case when SP.IsDeleted=1 then ''''True'''' else ''''False'''' end Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id INNER JOIN #LevelRights ON #LevelRights.LevelId = SP.Level_Id''
	END
else
	BEGIN
		SET NOCOUNT ON;
		--set @Query = ''SELECT  LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,SP.Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id WHERE SP.Isdeleted=''+cast(@Isdel as nvarchar(5))+'' and SP.Level_Id in ( ''+ @UserLevels +'' )''
		set @Query = ''SELECT  LD.name,SP.ShiftPattern_Id,SP.Pattern_Name,SP.Shift_days,case when SP.IsDeleted=1 then ''''True'''' else ''''False'''' end Isdeleted FROM TA_Tbl_ShiftPattern SP INNER JOIN TA_Tbl_LevelDetails LD ON LD.[id] = SP.Level_Id INNER JOIN #LevelRights ON #LevelRights.LevelId = SP.Level_Id WHERE SP.Isdeleted=''+cast(@Isdel as nvarchar(5))+''''
	END
exec(@Query)
drop table #LevelRights
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertMasterData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertMasterData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
--	Modified By		:	Manjula.P
--	Modified On		:	04-Oct-2013
--	Descriptions		:	Inserting Religion into its table then taking its id
--	Modified By		:	Manjula.P
--	Modified On		:	09-Oct-2013
--	Descriptions		:	Adding Timestamp to GETDATE() because of cannot insert null values in EmpPay by Manjula.P on 09-Oct-2013 Mantis : 0019368
--	Modified By		:	Manjula.P
--	Modified On		:	10-Jan-2013
--	Descriptions		:	Added @ParentLevelId param for adding ParentLevelId into title master table 
--	Modified By		:	A.K.T.MOORTHI
--	Modified On		:	13-Jan-2013
--	Descriptions		:	To Comment All @ParentLevelId Variable
--	Modified By		:	Manjula.P
--	Modified On		:	17-JAn-2013
--	Descriptions		:	Adding Condition for Enterprise and standard seperately
--	Modified By		:	A.K.T.MOORTHI
--	Modified On		:	08-Apr-2014
--	Descriptions		:	To Add Parameter For Check Application Mode And Add Condition Based On Application Mode
-- =============================================

create PROCEDURE [dbo].[Proc_TA_InsertMasterData]
	@ApplnMode BIT
AS
BEGIN
	set nocount on
	declare @GradeName as nvarchar(255)
	declare @GradeLevel as nvarchar(255)
	declare @ImportGradeLevel as nvarchar(255)
	--Added by Manjula.P on 10-Jan-2014 for getting levelid from designation after included levelid in title table
	--declare @ParentLevelId as int;
	--set @ParentLevelId=0;
	--set @ParentLevelId=(select top 1 isnull(id,0) from  TA_Tbl_LevelDetails t2 inner join Ta_Tbl_ImportMasterData t1 on t2.name=t1.Level1)
	--************************************************************
	select top 1 @GradeName=grade_Name,@GradeLevel=Grade_Level,@ImportGradeLevel=GradeNo from
	(select  distinct ta_tbl_grade.grade_Name,ta_tbl_grade.Grade_Level,Ta_tbl_importMasterData.GradeNo from Ta_tbl_importMasterData 
	inner join ta_tbl_grade on ta_tbl_grade.grade_Name=Ta_tbl_importMasterData.grade and ta_tbl_grade.Grade_Level<>Ta_tbl_importMasterData.GradeNo 
	where ta_tbl_grade.isdeleted=0) GradeTable
	declare @errMessage as nvarchar(4000)
	--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
	if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
		begin
			if(@GradeName<>'''')
			BEGIN
				set @errMessage=''Grade Name : '' + @GradeName +  '' has different GradeNo ('' + @ImportGradeLevel + '') in the Employee Import file. Change the GradeNo as '' + @GradeLevel + '' in the Employee Import file''
			END
		end
	declare @Designation as nvarchar(255)
	declare @Grade as nvarchar(255)
	declare @ImportGrade as nvarchar(255)
	select top 1 @Designation=TitleName,@Grade=grade_Name,@ImportGrade=Grade from
	(select  distinct ta_tbl_title.TitleName,ta_tbl_grade.grade_Name,Ta_tbl_importMasterData.Grade from Ta_tbl_importMasterData
	inner join ta_tbl_title on  ta_tbl_title.TitleName=Ta_tbl_importMasterData.Designation 
	inner join ta_tbl_grade on ta_tbl_grade.Grade_Id=ta_tbl_title.GradeId and ta_tbl_grade.grade_Name<>Ta_tbl_importMasterData.grade
	where ta_tbl_grade.isdeleted=0 ) GradeTable --and TA_Tbl_Title.LevelID=@ParentLevelId
	--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
	if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
	begin
	if(@Designation<>'''')
	BEGIN
	set @errMessage=''Designation : '' + @Designation +  '' has different Grade ('' + @ImportGrade + '') in the Employee Import file. Change the Grade as '' + @Grade + '' in the Employee Import file''
	END
	END
	declare @EmployeeCode as nvarchar(15)
	select Top 1 @EmployeeCode=Ta_Tbl_Employee.Employee_Code_Id
	from Ta_Tbl_Employee
	inner join Ta_tbl_importMasterData on Ta_Tbl_Employee.Employee_Code_Id=Ta_tbl_importMasterData.Employee_Code
	where Ta_Tbl_Employee.IsDeleted=0
	if(@EmployeeCode<>'''')
	BEGIN
	set @errMessage=''Employee Code : '' + @EmployeeCode +  '' is already exists. Remove it from Employee Import file''
	END
	declare @SwipeCardNo as nvarchar(15)
	select Top 1 @SwipeCardNo=Ta_Tbl_Employee.Employee_Code_Id
	from Ta_Tbl_Employee
	inner join Ta_tbl_importMasterData on Ta_Tbl_Employee.SwipeCardNo=Ta_tbl_importMasterData.SwipeCardNo
	where Ta_Tbl_Employee.IsDeleted=0
	if(@SwipeCardNo<>'''' and @SwipeCardNo is not null)
	BEGIN
	set @errMessage=''SwipeCardNo (Biometerc Number) : '' + @SwipeCardNo +  '' is already exists. Remove it from Employee Import file''
	END
	if(@errMessage<>'''')
	BEGIN
			RAISERROR (@errMessage,16,1);
	END
	else
	BEGIN
		--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
		if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
		begin
		insert into ta_tbl_grade (Grade_Name,Grade_Level,Isdeleted) 
		select  distinct Grade,Gradeno,''0'' as Isdeleted from Ta_tbl_importMasterData 
		where grade not in (select grade_Name from ta_tbl_grade  where isdeleted=0) 
		order by Ta_tbl_importMasterData.grade
		END
		DECLARE @TblDesignation TABLE (UniqueId BIGINT IDENTITY(1,1), LevelId BIGINT, Desingation nvarchar(MAX), GradeId BIGINT, Prog BIT)
		DECLARE @Id BIGINT, @LevelId BIGINT, @Title nvarchar(MAX)
		IF NOT EXISTS(SELECT Grade_Name FROM TA_Tbl_Grade WHERE Grade_Name = ''SEGrade'' AND Isdeleted = 0)
		BEGIN
		--Enterprise	
			INSERT INTO @TblDesignation
				SELECT DISTINCT ID.Level1_Id, ID.Designation, G.Grade_ID, 0 FROM Ta_tbl_importMasterData ID
				INNER JOIN TA_Tbl_Grade G on G.Grade_Name = ID.Grade
			WHILE(EXISTS(SELECT LevelId FROM @TblDesignation WHERE Prog = 0))
			BEGIN
				SELECT TOP 1 @Id = UniqueId, @LevelId = LevelId, @Title = Desingation FROM @TblDesignation WHERE Prog = 0
				IF NOT EXISTS(SELECT TitleName FROM TA_Tbl_Title T WHERE T.LevelID = @LevelId AND T.TitleName = @Title)
				BEGIN
					INSERT INTO TA_Tbl_Title(TitleName, TitleDescription, GradeID, Isdeleted, LevelID)
						SELECT Desingation, Desingation, GradeId, 0, LevelId FROM @TblDesignation WHERE UniqueId = @Id
				END
				UPDATE @TblDesignation SET Prog = 1 WHERE UniqueId = @Id
			END
		END
		ELSE
		BEGIN
		--Standard
			INSERT INTO @TblDesignation
				SELECT DISTINCT ID.Level1_Id, ID.Designation, G.Grade_ID, 0 FROM Ta_tbl_importMasterData ID
				INNER JOIN TA_Tbl_Grade G on G.Grade_Name = ''SEGrade''
			WHILE(EXISTS(SELECT LevelId FROM @TblDesignation WHERE Prog = 0))
			BEGIN
				SELECT TOP 1 @Id = UniqueId, @LevelId = LevelId, @Title = Desingation FROM @TblDesignation WHERE Prog = 0
				IF NOT EXISTS(SELECT TitleName FROM TA_Tbl_Title T WHERE T.LevelID = @LevelId AND T.TitleName = @Title)
				BEGIN
					INSERT INTO TA_Tbl_Title(TitleName, TitleDescription, GradeID, Isdeleted, LevelID)
						SELECT Desingation, Desingation, GradeId, 0, LevelId FROM @TblDesignation WHERE UniqueId = @Id
				END
				UPDATE @TblDesignation SET Prog = 1 WHERE UniqueId = @Id
			END
		END		
		--***********************************************************************************
		insert into ta_tbl_category(CategoryName,Isdeleted)
		select distinct Employeecategory,''0'' as Isdeleted from Ta_tbl_importMasterData 
		where Employeecategory not in (select CategoryName from ta_tbl_Category where isdeleted=0)
		insert into ta_tbl_type(TypeName,Isdeleted)
		select distinct Employeetype,''0'' as Isdeleted from Ta_tbl_importMasterData 
		where Employeetype not in (select typeName from ta_tbl_Type where isdeleted=0)
		--Adding By Manjula.P on 04-Oct-2013 to inserting religion to master table if its <> null or ''''
		insert into TA_Tbl_Religion(Name,IsDeleted,Description)
		select distinct Religion,0 as Isdeleted,Religion from Ta_tbl_importMasterData
		where Religion is not null and Religion<>'''' and Religion not in (select Name from TA_Tbl_Religion where isdeleted=0) 
		--*********************************************************************************************
		Declare @UserGroup_Id int
		set @UserGroup_Id=0
		if not exists(select groupId from TA_Tbl_Usergroup where groupName=''IndividualUsers'')
		begin
			INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N''IndividualUsers'', 1, 0, GETDATE(), 0, N''1'')
		end
		select @UserGroup_Id=groupId from TA_Tbl_Usergroup where groupName=''IndividualUsers''
		set @UserGroup_Id=ISNULL(@UserGroup_Id,0)	
			
		INSERT INTO [TA_Tbl_Employee]           
				   ([Employee_FirstName]
				   ,[Employee_MiddleName]
				   ,[Employee_LastName]
				   ,[Father_name]
				   ,[Mother_name]
				   ,[DateofBirth]
				   ,[DateofBirth_Record]
				   ,[Blood_Group]
				   ,[EmailId]
				   ,[Contact_Address]
				   ,[Permanent_Address]
				   ,[Phone_Number]
				   ,[Mobile_Number]
				   ,[Gender]
				   ,[Marital_status]
				   ,[Nationality]
				   --Commented by MAnjula.P on 04-Oct-2013 to avoiding Religion Converstion error
				   --,[Religion]          
				   ,[Personal_mailid]
				   ,[Passport_No]
				   ,[Passport_expirydate]
				   ,[Visa_No]
				   ,[Visa_expirydate]          
				   ,[Employee_Code_Id]
				   ,[DateOfJoining]                    
				   ,[UserName]
				   ,[Emp_password]
				   ,[Qual_JoiningTime]
				   ,[Qual_Employment]
				   ,[OutDoorJob]
				   ,[CompOff_Eligible]
				   ,[OT_Eligible]
				   ,[ESI_Eligible]
				   ,[PF_Eligible]
				   ,[Report_Exclude]
				   ,[Employee_Status]
				   ,[SwipeCardNo]           
				   ,[Isdeleted]
				   ,[Hostel],
				   IsImported, InActive_Status,UserGroup_Id
				   )
		select [Emp_FirstName]
				   ,[Emp_MiddleName]
				   ,[Emp_LastName]
				   ,[Father_name]
				   ,[Mother_name]
				   ,[DateofBirth]
				   ,[DateofBirth_Record]
				   ,[Blood_Group]
				   ,[Email_Id]
				   ,[Contact_Address]
				   ,[Permanent_Address]
				   ,[Phone_Number]
				   ,[Mobile_Number]
				   ,[Gender]
				   ,[Marital_status]
				   ,[Nationality]
				 --Commented by MAnjula.P on 04-Oct-2013 to avoiding Religion Converstion error
				 --  ,[Religion]          
				   ,[Personal_emailid]
				   ,[Passport_No]
				   ,case when [Passport_expirydate] IS null or [Passport_expirydate]='''' then null else Passport_ExpiryDate end
				   ,[Visa_No]
				   ,case when [Visa_expirydate] IS null or [Visa_expirydate]='''' then null else [Visa_expirydate] end
				   ,[Employee_Code] as [Employee_Code_Id]
				   ,[DateOfJoining]                    
				   ,[Employee_Code] as [UserName]
				   ,''QL5OWbmiorXf+5GMDoaz1w=='' as [Emp_password]
				   ,[Qualification_JoiningTime]
				   ,[Qualification_Employement]
				   ,[OutDoorJob]
				   ,[CompOff_Eligible]
				   ,[OT_Eligible]
				   ,[ESI_Eligible]
				   ,[PF_Eligible]
				   ,[Report_Exclude]
				   ,[Employee_Status]
				   ,[SwipeCardNo]           
				   ,[Isdeleted]
				   ,[Hostel],1,0,@UserGroup_Id
		from Ta_tbl_importMasterData
		where [Employee_Code] not in (select employee_code_id from ta_tbl_employee where ((Isdeleted = 0 OR (1 =1 AND @ApplnMode = 0))))
		insert into ta_tbl_employeecategory (EmployeeId, CategoryID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_category.CategoryID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id = Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_category on ta_tbl_category.CategoryName = Ta_Tbl_ImportMasterData.EmployeeCategory
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeecategory)
		insert into ta_tbl_employeeType (EmployeeId, TypeID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_type.typeID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_type on ta_tbl_type.TypeName = Ta_Tbl_ImportMasterData.EmployeeType
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeeType)
		--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
		if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
		begin
			--Enterprise
		insert into ta_tbl_employeeDesignation (EmployeeId, DesignationID, EffectiveDate) 
		select Ta_tbl_employee.Employee_ID, ta_tbl_title.TitleID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		inner join ta_tbl_title on ta_tbl_title.TitleName = Ta_Tbl_ImportMasterData.Designation 
		AND ta_tbl_title.LevelID = Ta_Tbl_ImportMasterData.Level1_Id
		inner join ta_tbl_Grade on ta_tbl_Grade.Grade_Id =ta_tbl_title.GradeId 
		--and ta_tbl_Grade.Grade_Level=Ta_Tbl_ImportMasterData.GradeNo
		and ta_tbl_Grade.Grade_ID=TA_Tbl_Title.GradeID
		where Ta_tbl_employee.Employee_Id 
		not in (select EmployeeId from ta_tbl_employeeDesignation)
		--TA_Tbl_Title.LevelID=@ParentLevelId and 
		end
		else
		begin
			--Standard
			insert into ta_tbl_employeeDesignation (EmployeeId, DesignationID, EffectiveDate) 
			select Ta_tbl_employee.Employee_ID, ta_tbl_title.TitleID,Ta_Tbl_ImportMasterData.DateOfJoining from Ta_Tbl_ImportMasterData 
			inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
			inner join ta_tbl_title on ta_tbl_title.TitleName = Ta_Tbl_ImportMasterData.Designation 
			AND ta_tbl_title.LevelID = Ta_Tbl_ImportMasterData.Level1_Id
			inner join ta_tbl_Grade on ta_tbl_Grade.Grade_Name =''SEGrade''
			where Ta_tbl_employee.Employee_Id 
			not in (select EmployeeId from ta_tbl_employeeDesignation)
			--TA_Tbl_Title.LevelID=@ParentLevelId and 
		end
		--***********************************************************************************
		--Adding Timestamp to GETDATE() because of cannot insert null values in EmpPay by Manjula.P on 09-Oct-2013 Mantis : 0019368
		insert into ta_tbl_employeePay (EmployeeId, BasicPay, EffectiveDate,Timestamp) 
		select Ta_tbl_employee.Employee_ID, Ta_Tbl_ImportMasterData.BasicSalary,Ta_Tbl_ImportMasterData.DateOfJoining,GETDATE() from Ta_Tbl_ImportMasterData 
		inner join Ta_tbl_employee on ta_tbl_employee.employee_code_id= Ta_Tbl_ImportMasterData.employee_code
		where Ta_tbl_employee.Employee_Id not in (select EmployeeId from ta_tbl_employeePay)
		--Adding By Manjula.P on 04-Oct-2013 for updating Religion 
		update E set Religion=R.ID from ta_tbl_Employee E 
		inner join Ta_Tbl_ImportMasterData IM on IM.Employee_Code=E.Employee_Code_Id and IM.Religion is not null and IM.Religion <>'''' 
		inner join TA_Tbl_Religion R on R.Name=IM.Religion
		where E.Isdeleted=0
		--********************************************************
		END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RestoreShiftRoster]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RestoreShiftRoster]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
--	Author		:	A.K.T.MOORTHI
--	Create date	:	17-Dec-2013
--	Description	:	Check Pattern Exists Are Not
--	EXEC [Proc_TA_RestoreShiftRoster] ''10''
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_RestoreShiftRoster]
	-- Add the parameters for the stored procedure here
	@ShiftRosterIds VARCHAR(MAX)	
AS
BEGIN
	DECLARE @TblShiftRoster TABLE(ShiftRosterId BIGINT, ShiftRosterName VARCHAR(50), LevelId BIGINT, PatternsCount INT, RetMessage VARCHAR(20), Process BIT)
	INSERT INTO @TblShiftRoster
		SELECT Value, SR.ShiftRoaster_Name, SR.Level_Id, SR.NumberOfPatterns, '''', 0 FROM dbo.Split(@ShiftRosterIds, '','') Id
			INNER JOIN TA_Tbl_ShiftRoaster SR ON SR.ShiftRoaster_Id = ID.Value
		WHERE SR.IsDeleted = 1
	WHILE(EXISTS(SELECT ShiftRosterId FROM @TblShiftRoster WHERE Process = 0))
	BEGIN
		DECLARE @RosterId BIGINT, @Patterns INT, @LevelId BIGINT
		DECLARE @RosterName VARCHAR(50)
		DECLARE @SQLQuery VARCHAR(MAX), @Query VARCHAR(MAX)
		DECLARE @TblRosterId TABLE(ShiftRosterId BIGINT)
		SET @SQLQuery = ''SELECT DISTINCT ShiftRoaster_Id FROM TA_Tbl_ShiftRoaster SR''
		SET @Query = ''''
		SELECT @RosterId = ShiftRosterId, @Patterns = PatternsCount, @RosterName = ShiftRosterName, @LevelId = LevelId FROM @TblShiftRoster WHERE Process = 0
		;WITH Patterns AS(
			SELECT PC = 1
			UNION ALL
			SELECT PC = PC + 1 FROM Patterns WHERE PC < @Patterns
		)
		SELECT 
			@SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ShiftPattern SP'' + CAST(PC AS VARCHAR(2)) + '' ON SP'' + CAST(PC AS VARCHAR(2)) + ''.ShiftPattern_Id = SR.Pattern'' + CAST(PC AS VARCHAR(2)),
			@Query = @Query + '' AND SP'' + CAST(PC AS VARCHAR(2)) + ''.Isdeleted = 0''
		FROM Patterns
		IF(@Query != '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' WHERE SR.ShiftRoaster_Id = '' + CAST(@RosterId AS VARCHAR(20)) +  @Query
			INSERT INTO @TblRosterId
				EXEC(@SQLQuery)
			IF(EXISTS(SELECT * FROM @TblRosterId))
			BEGIN
				IF(NOT EXISTS(SELECT * FROM TA_Tbl_ShiftRoaster WHERE ShiftRoaster_Name LIKE '''' + @RosterName + '''' AND IsDeleted = 0 AND Level_Id = @LevelId ))
				BEGIN
					UPDATE TA_Tbl_ShiftRoaster SET IsDeleted = 0 WHERE ShiftRoaster_Id = @RosterId
					UPDATE @TblShiftRoster SET RetMessage = ''Successfully'' WHERE ShiftRosterId = @RosterId
				END
				ELSE
				BEGIN
					UPDATE @TblShiftRoster SET RetMessage = ''Exists'' WHERE ShiftRosterId = @RosterId
				END
			END
			ELSE
			BEGIN
				UPDATE @TblShiftRoster SET RetMessage = ''Failed'' WHERE ShiftRosterId = @RosterId
			END
		END
		UPDATE @TblShiftRoster SET Process = 1 WHERE ShiftRosterId = @RosterId
	END
	SELECT DISTINCT RetMessage FROM @TblShiftRoster
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpCategory_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpCategory_MusterRoll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 06-08-2015 02.30 pm
-- Description:	Get the employee details based on selecte levels
-- [Proc_TA_EmpCategory_MusterRoll]''2014-09-11'',''787,788,789,8,888'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpCategory_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeCategory int,
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here		
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql=''	select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
					from TA_Tbl_EmployeeCategory	ec 
					inner join ta_tbl_employee		emp	on ec.EmployeeId = emp.Employee_Id
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 
					group by ec.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)EmpCategory
				inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
				AND ECategory.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and ECategory.CategoryId is not null ''
	if (@Employee_Code_Id<>'''')
		if(@employeeCategory<>0 and @employeeCategory!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and ECategory.CategoryId=''+convert(varchar(20),@employeeCategory)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	else 
		if(@employeeCategory<>0 and @employeeCategory!='''')
			BEGIN					
				Set @sql=@sql+'' and ECategory.CategoryId=''+convert(varchar(20),@employeeCategory)
			End
		else
			Begin				
				Set @sql=@sql 
			end
	execute(@sql)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]    Script Date: 03/25/2021 10:22:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name : Proc_TA_UpdateLeaveApplicationSanction  
Description : Update Leave Application Details of Employees Based on their LeaveApplication_Id  
Tables Included : TA_Tbl_LeaveApplication   
Created By : Prabakaran  
Created On : 24-Jul-07  
Modified By :   
Modified On :   
*/  
Create PROCEDURE [dbo].[Proc_TA_UpdateLeaveApplicationSanction_Angler]  
  --Proc_TA_UpdateLeaveApplicationSanction  '''','''',''''
@LeaveApplication_Id int,  
@Status nvarchar(250),  
@Remarks nvarchar(250),
@auEmpId int,
@IntimationType nvarchar(20)
as  
BEGIN
declare @sql nvarchar(4000)
set @sql=''''
set @sql = @sql + ''UPDATE TA_TBL_LeaveApplication set Status=N'''''' + @Status + '''''',Remarks= N'''''' + @Remarks + '''''',InTimationType= N'''''' + @IntimationType + '''''',Emp_Id=''''''+ cast(@auEmpId as nvarchar(20))+'''''' Where LeaveApplication_Id= '' + cast (@LeaveApplication_Id  as nvarchar(10))
exec (@sql)
set @sql=''''
set @sql = @sql + ''UPDATE TA_TBL_LeaveApplicationMaster set Status=N'''''' + @Status + '''''',InTimationType= N'''''' + @IntimationType + '''''',Emp_Id=''''''+ cast(@auEmpId as nvarchar(20))+'''''' Where LeaveApplication_Id= '' + cast (@LeaveApplication_Id  as nvarchar(10)) 
exec (@sql)
--update the processflag
update Ta_Tbl_ProcessedData set processflag=0
from Ta_Tbl_LeaveApplication t2
inner join Ta_Tbl_Employee t3 on t3.Employee_Id=t2.Employee_Id
inner join Ta_Tbl_ProcessedData t1 on t1.Employee_Code_Id=t3.SwipeCardNo and
t1.date between t2.Leave_FromDate and t2.Leave_ToDate
where t2.LeaveApplication_Id=@LeaveApplication_Id 
declare @intEmployeeId as int
set @intEmployeeId=(Select distinct(Employee_Id) from Ta_Tbl_LeaveApplication where LeaveApplication_Id=@LeaveApplication_Id) 
--and CheckedIDs in(@CheckedLeaveApplicationIDs))
--Update year closure
update ta_tbl_yearclosure set Leave_Taken=
(select isnull(sum(NumberOfDays),0.0)
from Ta_Tbl_LeaveApplication
inner join TA_Tbl_YearSetting on Ta_Tbl_LeaveApplication.YearSettings_ID=TA_Tbl_YearSetting.YearSettings_ID
where ta_tbl_yearclosure.Employee_Id=Ta_Tbl_LeaveApplication.Employee_Id
and ta_tbl_yearclosure.LeaveTypeId=Ta_Tbl_LeaveApplication.LeaveType_Id
and ta_tbl_yearclosure.Year_SettingID=Ta_Tbl_LeaveApplication.YearSettings_ID
and Ta_Tbl_LeaveApplication.Isdeleted=0 and Ta_Tbl_LeaveApplication.Status=''Approved''
and Ta_Tbl_LeaveApplication.Employee_Id=@intEmployeeId
)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author		:	A.K.T.MOORTHI
-- Create date	:	06-SEP-2013
-- Description	:	Import the Employees
--	Modified By		:	Manjula.P
--	Modified On		:	15-Jan-14
--	Descriptinos	:	Adding this and ISNULL(TLD.LevelName,'''')!='''' condition to avoiding empty value that saved in levelname in level details tble
--						this issue was occurs when child level name is empty via import master
--Modified By		:	A.K.T.MOORTHI
--Date Of Modified	:	07-Apr-2014
--Description			:	Update IsDeleted = 1, InActiveDate = DateOfJoinDate, Employee_Status = 0, Report_Exclude = 1 When Employee Count Greater Then 5, Bze User Can Able To Create N Number Of User.
--								But They Can Access Only 5 Employee For Hole Application.
-- =============================================
Create PROCEDURE [dbo].[Proc_TA_CreateUpdateMasterDataLevelsChild]
	@ApplnMode BIT
AS
BEGIN
	-- Update the LevelId with First Parent Level  
	UPDATE TA_Tbl_ImportMasterData SET ChildLevelId = Level1_Id  
-- Insert the Lower Child Level Id from Import Master Data Table into the Employee Level Table for each employee  
	DECLARE @LevelId INT, @LevelCount INT, @Inc INT
	DECLARE @Query nvarchar(MAX)
	DECLARE @TempLevel TABLE(Id INT IDENTITY(1, 1), LevelId INT)
	DECLARE @TempLevelDetails TABLE(LevelName nvarchar(MAX), LevelId INT, ParentId INT)
	INSERT INTO @TempLevel
		SELECT levelID FROM TA_Tbl_Level L WHERE L.isDeleted = 0 ORDER BY parentLevelID
	SELECT @LevelCount = COUNT(levelID) FROM TA_Tbl_Level L WHERE L.isDeleted = 0
	SET @Inc = 2
	WHILE(@LevelCount>=@Inc)
	BEGIN
		SELECT @LevelId = LevelId FROM @TempLevel WHERE Id = @Inc
		SET @Query = ''SELECT DISTINCT Level'' + CAST(@Inc AS nvarchar(10)) + '', '' + CAST(@LevelId AS nvarchar(10)) + '', Level'' + CAST(@Inc-1 AS nvarchar(10)) + ''_Id FROM Ta_Tbl_ImportMasterData IMD ''
		SET @Query = @Query + ''LEFT JOIN Ta_Tbl_levelDetails LD ON LD.parentId = IMD.Level'' + CAST(@Inc-1 AS nvarchar(10)) + ''_Id AND LD.name = IMD.Level'' + CAST(@Inc AS nvarchar(10)) + '' AND LD.LevelId = '' + CAST(@LevelId AS nvarchar(10)) + '' ''
		SET @Query = @Query + ''WHERE IMD.Level'' + CAST(@Inc AS nvarchar(10)) + ''_Id IS NULL  AND LD.LevelId IS NULL''
		INSERT INTO @TempLevelDetails
			EXEC(@Query)
		--Adding this and ISNULL(TLD.LevelName,'''')!='''' condition to avoiding empty value that saved in levelname in level details tble
		-- this issue was occurs when child level name is empty via import master
		INSERT INTO Ta_Tbl_levelDetails(levelId, parentId, name, [description])
			SELECT TLD.LevelId, TLD.ParentId, TLD.LevelName, TLD.LevelName FROM @TempLevelDetails TLD		
				WHERE TLD.LevelName NOT IN (SELECT TL.LevelName FROM @TempLevelDetails TL 
				INNER JOIN Ta_Tbl_levelDetails LD ON LD.name = TL.LevelName AND LD.parentId = TL.ParentId AND TLD.LevelId != @Inc  ) and ISNULL(TLD.LevelName,'''')!=''''
		SET @Query = ''UPDATE Ta_Tbl_ImportMasterData SET Level'' + CAST(@Inc AS nvarchar(10)) + ''_Id = LD.id FROM Ta_Tbl_ImportMasterData IMD ''
		SET @Query = @Query + ''INNER JOIN Ta_Tbl_levelDetails LD ON LD.parentId = IMD.Level'' + CAST(@Inc-1 AS nvarchar(10)) + ''_Id AND LD.name = IMD.Level'' + CAST(@Inc AS nvarchar(10))
		EXEC(@Query)
		DELETE FROM @TempLevelDetails
		SET @Inc = @Inc + 1
	END
	INSERT INTO TA_Tbl_EmployeeLevel (EmployeeId, LevelId, EffectiveDate)
		SELECT 
			Emp.Employee_Id,
			(CASE
				WHEN IMD.Level10_Id IS NOT NULL THEN IMD.Level10_Id 
				WHEN IMD.Level9_Id IS NOT NULL THEN IMD.Level9_Id 
				WHEN IMD.Level8_Id IS NOT NULL THEN IMD.Level8_Id 
				WHEN IMD.Level7_Id IS NOT NULL THEN IMD.Level7_Id 
				WHEN IMD.Level6_Id IS NOT NULL THEN IMD.Level6_Id 
				WHEN IMD.Level5_Id IS NOT NULL THEN IMD.Level5_Id 
				WHEN IMD.Level4_Id IS NOT NULL THEN IMD.Level4_Id 
				WHEN IMD.Level3_Id IS NOT NULL THEN IMD.Level3_Id 
				WHEN IMD.Level2_Id IS NOT NULL THEN IMD.Level2_Id 
				WHEN IMD.Level1_Id IS NOT NULL THEN IMD.Level1_Id
				ELSE IMD.ChildLevelId END
			),
			IMD.DateOfJoining FROM Ta_Tbl_ImportMasterData IMD
			INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Code_Id = IMD.Employee_Code
		WHERE Emp.Employee_Id NOT IN (SELECT EmployeeId FROM TA_Tbl_EmployeeLevel)	
		--Added by Manjula.P on 30-Jan-2014 for inserting dummy values to yearclosure when the employee is imported
		create table #temp_Employee
		(
		Employee_Id int,
		LeaveTypeId int,
		MaxValue decimal(18,1),
		LevelId int,
		YearSettingsId int
		)
		insert into #temp_Employee
		select e.Employee_Id,LT.LeaveType_Id,0,EL.LevelId,(select YearSettings_Id from TA_Tbl_YearSetting where IsActive=1) from TA_Tbl_Employee e
		cross join TA_Tbl_LeaveType LT
		inner join TA_Tbl_EmployeeLevel EL on EL.EmployeeId=e.Employee_Id
		where e.Employee_Id not in (select Y.Employee_Id from TA_Tbl_YearClosure Y)
		and Employee_Code_Id<>''18000000'' and Employee_Status=1 and e.Isdeleted=0 and LT.IsDeleted=0
		insert into TA_Tbl_YearClosure (Year_SettingID,OrgLevelId,Employee_Id,LeaveTypeID,Current_Quota,Available_Leaves,Emp_ID) 
		select YearSettingsId,LevelId,Employee_Id,LeaveTypeId,MaxValue,MaxValue,Employee_Id from #temp_Employee
		drop table #temp_Employee
		--**********************************************************************************************************
	DELETE Ta_Tbl_ImportMasterData FROM Ta_Tbl_ImportMasterData IMD
	INNER JOIN TA_Tbl_Employee Emp ON Emp.Employee_Code_Id = IMD.Employee_Code
	--Added by Manikandan.R
	--On 05-02-2014 05.22PM
	declare @groupId as bigint
	set @groupId=(select GroupId from ta_tbl_usergroup where groupName=''SuperAdmin'')
	insert into TA_Tbl_LevelRights (GroupId,LevelId,Emp_Id) 
	select @groupId,id,1 from Ta_Tbl_levelDetails where id not in(select levelId from TA_Tbl_LevelRights where @groupId=@groupId)
	--select * from TA_Tbl_LevelRights order by GroupId,LevelId 
	IF(@ApplnMode = 0)
	BEGIN
		/* Start(07-Apr-2014): Update IsDeleted = 1 When Employee Count Greater Then 5 */
		UPDATE TA_Tbl_Employee SET
			Isdeleted = 1
			--,
			--Report_Exclude = 1
			--Employee_Status = 0,
			--InActiveDate = DATEADD(D, 1, DateOfJoining)
		WHERE Employee_Id NOT IN(SELECT TOP 5 Employee_Id FROM TA_Tbl_Employee WHERE Isdeleted = 0 AND Employee_Code_Id <> ''18000000'') AND
			Employee_Code_Id <> ''18000000'' AND ISNULL(InActive_Status, 0) = 0
		/* End */
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_rptAbsent]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_rptAbsent]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_Ta_rptAbsent ''2020/04/01'',''2020/07/02'','''',0,''Nila ,Manikandan ,Ranjith ,'',''0'',0,0,''superadmin'',0,'''',0,0,''both'',3,0,1
CREATE PROCEDURE [dbo].[Proc_Ta_rptAbsent]
(
	@fromDat DATETIME,
	@ToDat DATETIME,
	@empId NVARCHAR(max),
	@shift INT,
	@EmployeeName NVARCHAR(max),
	@LevelID NVARCHAR(max),
	@employeeCategory INT,
	@employeeType INT,
	@UserGroupName NVARCHAR(250),
	@GradeLevel NVARCHAR(20),
	@EmpSwipeCard NVARCHAR(20),
	@ParentId INT,
	@DesignationID INT,
	@Gender NVARCHAR(10),
	@session INT,
	@EmpAutoId bigint,
	@ExportType int
)     
AS
BEGIN
	SET NOCOUNT ON;
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
	if(@UserGroupName!=''SuperAdmin'' and @isReportingto!=1)
	begin
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
		insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	end
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #LevelRights(LevelId INT)
	CREATE TABLE #TempProcessedData(EmpAutoId bigint,Date DATETIME,Employee_Code_Id NVARCHAR(20),InTime nVARCHAR(25),OutTime nVARCHAR(25),Attendance nVARCHAR(50),fnattendanceCode nVARCHAR(50),anattendanceCode nVARCHAR(50),Shift_Id INT)
	CREATE TABLE #TempEmployee(EmpAutoId bigint,EmpSwipeCardNo NVARCHAR(20))      
	--Get current date time format.
	DECLARE @dateFormat as INT
	select  @dateFormat=DateFormat from Func_TA_GetDateTimeFormat()
	--insert in Temporary table
	INSERT INTO  #LevelRights SELECT * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID  
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType 
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory
	CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
	CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
	if(@empId is not null and @empId <> '''')
	BEGIN                  
		INSERT INTO #EmployeeID SELECT * from SplitupEmployeeCode(@empId)
	END
	if(@EmployeeName is not null and @EmployeeName <> '''')
	BEGIN
		INSERT INTO #EmployeeName SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
	end
	INSERT INTO #EmpLevel 
	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from 
	(
		SELECT      max(el.EffectiveDate) as EffectiveDate,   el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
		from TA_Tbl_EmployeeLevel el
		INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
		INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId
		Left Outer JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id
		Left Outer JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id
		WHERE emp.Isdeleted=0 
		and (ISNULL(@empId,'''')= '''' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeID))
		and (ISNULL(@EmployeeName,'''')= '''' or emp.Employee_Code_Id in(select EmployeeID from #EmployeeName))
		and (@Gender=''Both'' or emp.Gender=@Gender)
		group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
	) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nVARCHAR(50)),102) and EL.LevelId is not null
	  
	INSERT INTO #TempEmployee SELECT Employee_ID,SwipeCardNo from TA_Tbl_Employee
	INNER JOIN #EmpLevel ON #EmpLevel.EmployeeId=TA_Tbl_Employee.Employee_Id 
	
	INSERT INTO #TempProcessedData 
	SELECT      TE.EmpAutoId,
	PD.Date,
	PD.Employee_Code_Id,
	PD.InTime,
	PD.OutTime,
	PD.Attendance,
	PD.fnattendanceCode,
	PD.anattendanceCode,
	PD.Shift_Id 
	from TA_Tbl_ProcessedData PD 
	INNER JOIN #TempEmployee TE ON TE.EmpSwipeCardNo=PD.Employee_Code_Id
	WHERE (PD.fnAttendanceCode = ''Absent'' OR PD.AnAttendanceCode =''Absent'' OR PD.fnAttendanceCode = ''LOP'' OR PD.AnAttendanceCode =''LOP'')          
	And (PD.Date >= @fromDat AND PD.Date <= @todat)
	and(isnull(@shift,0)=0 or PD.Shift_Id = @shift)
	and
	(
		(isnull(@session,0)=0 and (PD.anattendanceCode like ''absent%'' or PD.fnattendancecode like ''absent%'')) or 
		(@session=1 And PD.fnattendancecode like ''absent%'')or 
		(@session=2 And PD.anattendanceCode like ''absent%'') or
		(@session=3 and (PD.anattendanceCode like ''absent%'' and PD.fnattendancecode like ''absent%''))
	)
	
	UPDATE #TempProcesseddata SET  fnAttendanceCode=fnAttendanceCode + '' (L-''+ L.Status+'')''  from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
	WHERE L.isdeleted=0 and L.Leave_SessionFrom=''First Half'' and L.Status <> ''Approved''
	
	UPDATE #TempProcesseddata SET fnAttendanceCode=fnAttendanceCode + '' (P-''+PER.Permission_status+'')'' from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
	WHERE PER.isdeleted=0 and PER.Permission_status<> ''Approved''
	
	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + '' (L-''+ L.Status+'')''  from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_leaveApplication L ON L.Employee_Id=E.Employee_Id and P.date >=L.Leave_FromDate and P.date <=L.Leave_ToDate
	WHERE L.isdeleted=0 and L.Leave_SessionTo=''Second Half'' and L.Status <> ''Approved''
	
	UPDATE #TempProcesseddata SET anAttendanceCode=anAttendanceCode + '' (P-''+PER.Permission_status+'')'' from #TempProcesseddata P
	INNER JOIN ta_tbl_employee E ON P.employee_code_Id=E.swipecardNo
	INNER JOIN ta_tbl_permission PER ON PER.Employee_Id=E.Employee_Id and P.date=PER.Permission_Date
	WHERE PER.isdeleted=0 and PER.Permission_status<> ''Approved''
	
	DECLARE @sqlQuery as NVARCHAR(max)
	SET @sqlQuery = ''''
	if(@ExportType=1)
	begin
		SET @sqlQuery = @sqlQuery + '' SELECT E.Employee_Code_Id, 
		isnull(E.Employee_FirstName,'''''''') + SPACE(1)+ 
		isnull(E.Employee_LastName,'''''''') AS ''''EmpName'''',
		replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName ,
		replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as ''''Name'''',E.Gender,case when ''+CONVERT(varchar,@dateFormat) +''=106 then
											REPLACE(CONVERT(VARCHAR, PD.Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
											else CONVERT(VARCHAR, PD.Date, ''+CONVERT(varchar,@dateFormat)+'') end  AS Date, ta_tbl_shift.Shift_ShortName,PD.fnAttendanceCode as ''''FirstSession'''', PD.anAttendanceCode as ''''SecondSession'''' ''
	end
	else
	begin
		SET @sqlQuery = @sqlQuery + '' SELECT PD.fnAttendanceCode as FirstSession, PD.anAttendanceCode as SecondSession,#EmpLevel.LevelID, #EmpDesignation.DesignationId, E.Employee_Code_Id, case when ''+CONVERT(varchar,@dateFormat) +''=106 then
										REPLACE(CONVERT(VARCHAR, PD.Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
										else CONVERT(VARCHAR, PD.Date, ''+CONVERT(varchar,@dateFormat)+'') end  AS Date, ''
		SET @sqlQuery = @sqlQuery + '' isnull(E.Employee_FirstName,'''''''') + SPACE(1)'' 
		SET @sqlQuery = @sqlQuery + '' + isnull(E.Employee_LastName,'''''''') AS empname, PD.Attendance,replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&'''') as TitleName ,'' 
		SET @sqlQuery = @sqlQuery + ''      replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as name, ta_tbl_shift.Shift_ShortName,E.Gender,PD.Date format ''
	end
	
	SET @sqlQuery = @sqlQuery + '' FROM #TempProcessedData PD INNER JOIN''
	SET @sqlQuery = @sqlQuery + '' TA_Tbl_Employee E ON PD.EmpAutoId = E.Employee_ID''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpLevel ON #EmpLevel.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN Ta_Tbl_levelDetails ON #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpDesignation ON #EmpDesignation.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = TA_Tbl_Title.TitleId''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade ON TA_Tbl_Title.GradeId = TA_Tbl_Grade.Grade_ID''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Shift ON TA_Tbl_Shift.Shift_ID = PD.Shift_ID  ''    
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpType ON #EmpType.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmpCategory ON #EmpCategory.employeeid=E.Employee_Id ''
	SET @sqlQuery = @sqlQuery + '' WHERE 
								  (E.Isdeleted = 0) AND 
								  (E.Report_Exclude = 0) AND 
								  (
										(E.Employee_Status = 1)
										or
										(E.employee_status=0 and convert(nVARCHAR(11),E.InActiveDate,102)>=convert(nVARCHAR(11),PD.Date,102))
								  )
								  --While clicking the dashboard data, its showing wrong data in popu up screen. due to this i have commented as per testing team suggestion.
								  --16-11-2016 13.37 bug id is 0035540
								  and 
								  cast(convert(NVARCHAR, PD.Date, 111) + '''' '''' + convert(NVARCHAR,cast(Shift_StartTime as DATETIME),114) as DATETIME) <= getdate() ''
	if(@UserGroupName<>''SuperAdmin'')
	BEGIN
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	END
	if(@isReportingto > 0)
	BEGIN
		set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
	END
	SET @sqlQuery = @sqlQuery + '' order by PD.Employee_Code_Id,PD.Date''
	
	if(@ExportType=2)
	begin
		create table #AbsentTable(FirstSession nvarchar(100),SecondSession nvarchar(100),LevelID int,DesignationID int,Employee_Code_Id nvarchar(50),Date nvarchar(50),empname nvarchar(100),Attendance nvarchar(50),TitleName nvarchar(100),name nvarchar(150),Shift_ShortName nvarchar(10),Gender nvarchar(10),format datetime)
		insert into #AbsentTable exec(@sqlQuery)
		create table #TempLevelName(ID int identity(1,1),Name nvarchar(100))
		insert into #TempLevelName select distinct name from #AbsentTable
		declare @cou int
		select @cou=COUNT(distinct name) from #AbsentTable
		declare @i int
		set @i=1
		declare @SQLString nvarchar(Max)
		set @SQLString=''''
		while @i<=@cou
		begin
			set @SQLString = @SQLString + cast((select Name from #TempLevelName where ID=@i) as nvarchar(MAX)) + ''$'' + cast((select COUNT(*) from #AbsentTable where name=(select Name from #TempLevelName where ID=@i)) as nvarchar(MAX)) +''%''
			set @i=@i+1
		end
		select @SQLString as ReturnString
		create table #TempDate(ID int identity(1,1),format datetime,Date nvarchar(20))
		insert into #TempDate select distinct CAST(format as datetime),Date from #AbsentTable order by format
		declare @couLevel int
		declare @couDate int
		select @couLevel=COUNT(*) from #TempLevelName
		select @couDate=COUNT(*) from #TempDate
		declare @j int
		set @j=1
		declare @k int
		set @k=1
		declare @SQLString1 nvarchar(Max)
		set @SQLString1=''''
		while @j<=@couLevel
		begin
			declare @Levelstr nvarchar(100)
			set @Levelstr =(select Name from #TempLevelName where ID=@j)
			set @SQLString1 = @SQLString1 + @Levelstr + ''@''
			while @k<=@couDate
			begin
				declare @RowCount int
				set @RowCount=(select COUNT(*) from #AbsentTable where name=@Levelstr and Date=(select date from #TempDate where ID=@k))
				if(@RowCount!=0)
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + ''$'' + cast(@RowCount as nvarchar(20)) + ''%''
				end
				else
				begin
					set @SQLString1 = @SQLString1 + cast((select date from #TempDate where ID=@k) as nvarchar(Max)) + ''$'' + cast(0 as nvarchar(1)) + ''%''
				end
				set @k=@k+1
			end
			SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
			set @SQLString1 = @SQLString1 + ''#''
			set @k=1
			set @j=@j+1
		end
		SET @SQLString1 = SUBSTRING(@SQLString1, 0, LEN(@SQLString1))
		select @SQLString1 as ''Value''
	end
	else
	begin
		exec(@sqlQuery)
	end
	--Remove the temporary tables here 
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory 
	drop table #LevelRights
	drop table #TempProcessedData
	drop table #TempEmployee      
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
--	Modified By		:	Manjula.P., K.Gopinath
--	Modified On		:	30-Sep-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--	Descriptions	:	Selecting LOP with Leave type like LOP-CL, LOP-SL Mantis :0019151 
-- =============================================
--	Proc_TA_Rpt_LeaveSummaryDetails_Angler ''01/01/2017'',''10/31/2017'','''','''','''',''All'',''All'',0,0,''SuperAdmin'','''','''',0,0,''Both''
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails_Angler] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @YearSettingID int
	select @YearSettingID =max(yearsettings_ID) from ta_tbl_yearsetting where yearsettings_ID<(select yearsettings_ID from ta_tbl_yearsetting where isActive=1)
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	create table #TempLeaveDetails 
	(
	Employee_Id bigint,
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Id int,
	LeaveType_Name nvarchar(10),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1),
	LOP_Days decimal(18,1),
	LOP_Days_Availed_Approved decimal(18,1),
	LOP_Days_Availed_InProgress decimal(18,1),
	LOP_Days_Remaining decimal(18,1),
	RestrictedHoliday decimal(18,1),
	RestrictedHoliday_Availed_Approved decimal(18,1),
	RestrictedHoliday_Availed_InProgress decimal(18,1),
	RestrictedHoliday_Remaining decimal(18,1),
	YearSettingsId int
	)
    declare @sqlQuery varchar(8000)
    set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempLeaveDetails ''
	set @sqlQuery = @sqlQuery + ''(Employee_Id,Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,LeaveType_Id,LeaveType_Name, ''
	set @sqlQuery = @sqlQuery + ''Leave_Days ,LOP_Days,RestrictedHoliday,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining, ''
	set @sqlQuery = @sqlQuery + ''LOP_Days_Availed_Approved,LOP_Days_Availed_InProgress,LOP_Days_Remaining,RestrictedHoliday_Availed_Approved,RestrictedHoliday_Availed_InProgress,RestrictedHoliday_Remaining,YearSettingsId) ''
	set @sqlQuery = @sqlQuery + ''select E.Employee_Id,E.Employee_Code_Id,isnull(E.Employee_FirstName,'''''''') + space(1) + isnull(E.Employee_lastName,''''''''),replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&''''),LP.PolicyName,Emp_LP.FromDate,Emp_LP.ToDate, ''
	set @sqlQuery = @sqlQuery + ''LPD.LeaveType_Id,LT.LeaveType,Emp_LPD.No_Of_Days ,LPD.Max_LOP_Days,HS.Yearly_Maxdays as RestrictedHoliday, 0,	0,0,0,0,0,0,0,0,ys.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + ''from TA_Tbl_Employee E ''
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=E.Employee_Code_Id ''
		End
	set @sqlQuery = @sqlQuery + ''Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id ''
   	set @sqlQuery = @sqlQuery + ''INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId ''
	set @sqlQuery = @sqlQuery + ''INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID ''
	set @sqlQuery = @sqlQuery + ''Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_Emp_LeavePolicy Emp_LP on Emp_LP.employeeId=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id = Emp_LP.LeavePolicy_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id = Emp_LP.YearSettingId ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=Emp_LP.LeavePolicy_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id = LPD.LeaveType_Id  ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_Emp_LeavePolicyDetails Emp_LPD on Emp_LPD.Emp_LeavePolicyId = Emp_LP.Emp_LeavePolicyId ''
	set @sqlQuery = @sqlQuery + ''and Emp_LPD.LeaveType_Id = LPD.LeaveType_Id ''
	set @sqlQuery = @sqlQuery + ''left join TA_Tbl_HolidaySettings HS on HS.YearSettingId = YS.YearSettings_Id ''
	--set @sqlQuery = @sqlQuery + ''inner join ta_tbl_emp_LeaveTypedetails empltd on empltd.employeeid = Emp_LP.EmployeeId and empltd.leavetypeid=lpd.leavetype_id  ''
	set @sqlQuery = @sqlQuery + ''where E.IsDeleted =0 and E.Employee_Code_Id<>''''18000000'''' and E.Employee_Status = 1 ''
	set @sqlQuery = @sqlQuery + ''and YS.YearSettings_Id=''+@YearSettingID
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
	If Not (@EmpSwipeCard = '''')  
		Begin  
		 Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	if(@Gender<>''Both'')
		begin
		   set @sqlQuery = @sqlQuery + '' and E.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
		 set @sqlQuery = @sqlQuery + '' order by Employee_Id ''
exec(@sqlQuery)
	update #TempLeaveDetails set Leave_Days=case when Carry_PrevYear<>0 then Leave_Days+Carry_PrevYear
	else Leave_Days end from #TempLeaveDetails 
	inner join TA_Tbl_YearClosure yc on #TempLeaveDetails.YearSettingsId=yc.Year_SettingID
	and #TempLeaveDetails.Employee_Id=yc.Employee_Id 
	update #TempLeaveDetails set Leave_Days_Availed_Approved =Leave_Days_Availed_Approved+ A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type=''Leave'' and LA.Status = ''Approved'' and LA.isdeleted=0 and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id 
	and #TempLeaveDetails.LeaveType_id = A.LeaveType_id
	update #TempLeaveDetails set Leave_Days_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type=''Leave'' and LA.Status in (''Pending'',''Forwarded'') and LA.isdeleted=0 and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id 
	and #TempLeaveDetails.LeaveType_id = A.LeaveType_id
	update #TempLeaveDetails set Leave_Days_Remaining = (Leave_Days - (Leave_Days_Availed_Approved + Leave_Days_Availed_InProgress))
	update #TempLeaveDetails set LOP_Days_Availed_Approved = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id 
	where LA.type=''LOP'' and LA.Status = ''Approved'' and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set LOP_Days_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
	and LD.LeaveType_Id = LA.LeaveType_id and LA.isdeleted=0 
	where LA.type=''LOP'' and LA.Status in (''Pending'',''Forwarded'') and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set LOP_Days_Remaining = (LOP_Days - (LOP_Days_Availed_Approved + LOP_Days_Availed_InProgress))
	update #TempLeaveDetails set RestrictedHoliday_Availed_Approved = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type=''Restricted Holiday'' and LA.Status = ''Approved'' and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type=''Restricted Holiday'' and LA.Status in (''Pending'',''Forwarded'') and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Remaining = (RestrictedHoliday - (RestrictedHoliday_Availed_Approved + RestrictedHoliday_Availed_InProgress))
	create table #TempLeaveDetails_Final 
	(
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Name nvarchar(20),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1))
	insert into #TempLeaveDetails_Final select Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining from #TempLeaveDetails
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,''LOP-''+#TempLeaveDetails.LeaveType_Name,isnull(LOP_Days,0),isnull(LOP_Days_Availed_Approved,0),isnull(LOP_Days_Availed_InProgress,0),isnull(LOP_Days_Remaining,0) 
	from #TempLeaveDetails where LOP_Days<>0.0
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select distinct Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,''Restricted Holiday'',isnull(RestrictedHoliday,0),isnull(RestrictedHoliday_Availed_Approved,0),isnull(RestrictedHoliday_Availed_InProgress,0),
	isnull(RestrictedHoliday_Remaining,0) from #TempLeaveDetails
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	select 
	Employee_Code_Id,
	Employee_Name,
	Designation,
	PolicyName,
	REPLACE(CONVERT(VARCHAR(20), FromDate,@dateFormat),'' '',''-''),
	REPLACE(CONVERT(VARCHAR(20), ToDate,@dateFormat),'' '',''-''),
	LeaveType_Name,
	Leave_Days,
	Leave_Days_Availed_Approved,
	Leave_Days_Availed_InProgress,
	Leave_Days_Remaining
	from #TempLeaveDetails_Final order by Employee_Code_Id,LeaveType_Name
	drop table #TempLeaveDetails
	drop table #TempLeaveDetails_Final
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Rpt_LeaveSummaryDetails]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Rpt_LeaveSummaryDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
--	Modified By		:	Manjula.P., K.Gopinath
--	Modified On		:	30-Sep-2013 & 11-Jan-2014
-- Description	:	SQL Query Optimazation & Emp name filtering
--	Descriptions	:	Selecting LOP with Leave type like LOP-CL, LOP-SL Mantis :0019151 
-- =============================================
--	Proc_TA_Rpt_LeaveSummaryDetails ''01/01/2014'',''10/31/2015'',''787,78'','''','''',''All'',''All'',0,0,''SuperAdmin'','''','''',0,0,''Both'',1
CREATE PROCEDURE [dbo].[Proc_TA_Rpt_LeaveSummaryDetails] 
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@LeaveType varchar(50),
	@LeaveStatus varchar(30),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20)	,
	@EmpSwipeCard varchar(20),
	@ParentId int,
	@DesignationID int,
	@Gender varchar(10),
	@EmpAutoID int
)
AS
BEGIN
	SET NOCOUNT ON;
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime,Employee_Code_Id varchar(50),SwipeCard varchar(50))
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoID) as EmpAutoId
	--Employee Level Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Designation Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	--Employee Type Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	--Employee Category Indexes
	/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	insert into #EmpDesignation exec Proc_TA_EmpDesignation @todat,@empId,@DesignationID	
	insert into #EmpType exec [Proc_TA_EmpType] @todat,@empId,@employeeType	
	insert into #EmpCategory exec [Proc_TA_EmpCategory] @todat,@empId,@employeeCategory	
	insert into #EmpLevel exec  [Proc_TA_EmpLevel] @todat,@empId
	if(@EmployeeName is not null and @EmployeeName <> '''')
		begin
			create table #EmployeeName(EmployeeID varchar(25))
			insert into #EmployeeName
			select [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	create table #TempLeaveDetails 
	(
	Employee_Id bigint,
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Id int,
	LeaveType_Name nvarchar(10),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1),
	LOP_Days decimal(18,1),
	LOP_Days_Availed_Approved decimal(18,1),
	LOP_Days_Availed_InProgress decimal(18,1),
	LOP_Days_Remaining decimal(18,1),
	RestrictedHoliday decimal(18,1),
	RestrictedHoliday_Availed_Approved decimal(18,1),
	RestrictedHoliday_Availed_InProgress decimal(18,1),
	RestrictedHoliday_Remaining decimal(18,1),
	YearSettingsId int
	)
    declare @sqlQuery varchar(8000)
    set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempLeaveDetails ''
	set @sqlQuery = @sqlQuery + ''(Employee_Id,Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,LeaveType_Id,LeaveType_Name, ''
	set @sqlQuery = @sqlQuery + ''Leave_Days ,LOP_Days,RestrictedHoliday,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining, ''
	set @sqlQuery = @sqlQuery + ''LOP_Days_Availed_Approved,LOP_Days_Availed_InProgress,LOP_Days_Remaining,RestrictedHoliday_Availed_Approved,RestrictedHoliday_Availed_InProgress,RestrictedHoliday_Remaining,YearSettingsId) ''
	set @sqlQuery = @sqlQuery + ''select E.Employee_Id,E.Employee_Code_Id,isnull(E.Employee_FirstName,'''''''') + space(1) + isnull(E.Employee_lastName,''''''''),replace(TA_Tbl_Title.TitleName,''''&amp;'''',''''&''''),LP.PolicyName,Emp_LP.FromDate,Emp_LP.ToDate, ''
	set @sqlQuery = @sqlQuery + ''LPD.LeaveType_Id,LT.LeaveType,case when YS.YearSettings_Id = empltd.YearSettingsId then Emp_LPD.No_Of_Days + empltd.PreviousYearBalance	     
	else Emp_LPD.No_Of_Days end,LPD.Max_LOP_Days,HS.Yearly_Maxdays as RestrictedHoliday,case when YS.YearSettings_Id = empltd.YearSettingsId then empltd.NoOffLeaveAvailed
	else 0 end,	0,0,0,0,0,0,0,0,ys.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + ''from TA_Tbl_Employee E ''
		If Not (@EmployeeName = '''')  
		Begin  
			SET @sqlQuery = @sqlQuery + '' Inner join #EmployeeName on #EmployeeName.EmployeeID=E.Employee_Code_Id ''
		End
	set @sqlQuery = @sqlQuery + ''Inner join #EmpLevel on #EmpLevel.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpCategory on #EmpCategory.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpType on #EmpType.employeeid = E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''Inner join #EmpDesignation on #EmpDesignation.employeeid = E.Employee_Id ''
   	set @sqlQuery = @sqlQuery + ''INNER JOIN TA_Tbl_Title ON #EmpDesignation.DesignationId = dbo.TA_Tbl_Title.TitleId ''
	set @sqlQuery = @sqlQuery + ''INNER JOIN TA_Tbl_Grade ON dbo.TA_Tbl_Title.GradeId = dbo.TA_Tbl_Grade.Grade_ID ''
	set @sqlQuery = @sqlQuery + ''Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_Emp_LeavePolicy Emp_LP on Emp_LP.employeeId=E.Employee_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeavePolicy LP on LP.Policy_Id = Emp_LP.LeavePolicy_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_YearSetting YS on YS.YearSettings_Id = Emp_LP.YearSettingId ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeavePolicyDetails LPD on LPD.Policy_Id=Emp_LP.LeavePolicy_Id ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_LeaveType LT on LT.LeaveType_Id = LPD.LeaveType_Id  ''
	set @sqlQuery = @sqlQuery + ''inner join TA_Tbl_Emp_LeavePolicyDetails Emp_LPD on Emp_LPD.Emp_LeavePolicyId = Emp_LP.Emp_LeavePolicyId ''
	set @sqlQuery = @sqlQuery + ''and Emp_LPD.LeaveType_Id = LPD.LeaveType_Id ''
	set @sqlQuery = @sqlQuery + ''left join TA_Tbl_HolidaySettings HS on HS.YearSettingId = YS.YearSettings_Id ''
	set @sqlQuery = @sqlQuery + ''inner join ta_tbl_emp_LeaveTypedetails empltd on (empltd.employeeid = Emp_LP.EmployeeId and empltd.leavetypeid=lpd.leavetype_id and empltd.YearSettingsId= YS.YearSettings_Id)''
	set @sqlQuery = @sqlQuery + ''where E.IsDeleted =0 and E.Employee_Code_Id<>''''18000000'''' and E.Employee_Status = 1 ''
	set @sqlQuery = @sqlQuery + ''and YS.IsActive=1  ''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
		end		
	If Not (@EmpSwipeCard = '''')  
		Begin  
		 Set @sqlQuery = @sqlQuery + ''And E.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
		End 
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpCategory.CategoryID = '' + cast (@employeeCategory as nvarchar(20))
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' and #EmpType.TypeID = '' + Cast(@employeeType  as nvarchar(20))
		end
	if(@DesignationID<>0)
		begin
		   set @sqlQuery = @sqlQuery + '' and #EmpDesignation.DesignationId = '' + cast(@DesignationID as nvarchar(8))
		end	
	if(@Gender<>''Both'')
		begin
		   set @sqlQuery = @sqlQuery + '' and E.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
		end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		 set @sqlQuery = @sqlQuery + '' order by Employee_Id ''
	exec(@sqlQuery)
	update #TempLeaveDetails set Leave_Days=case when Carry_PrevYear<>0 then Leave_Days+Carry_PrevYear
	else Leave_Days end from #TempLeaveDetails 
	inner join TA_Tbl_YearClosure yc on (#TempLeaveDetails.YearSettingsId=yc.Year_SettingID and #TempLeaveDetails.LeaveType_Id=yc.LeaveTypeID)
	and #TempLeaveDetails.Employee_Id=yc.Employee_Id 
	update #TempLeaveDetails set Leave_Days_Availed_Approved =Leave_Days_Availed_Approved+ A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type=''Leave'' and LA.Status = ''Approved'' and LA.isdeleted=0 and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set Leave_Days_Availed_InProgress = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type=''Leave'' and LA.Status in (''Pending'',''Forwarded'') and LA.isdeleted=0 and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set Leave_Days_Remaining = (Leave_Days - (Leave_Days_Availed_Approved + Leave_Days_Availed_InProgress))
	update #TempLeaveDetails set LOP_Days_Availed_Approved = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id 
		where LA.type=''LOP'' and LA.Status = ''Approved'' and LA.isdeleted=0  and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set LOP_Days_Availed_InProgress = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays,LA.LeaveType_id from TA_Tbl_LeaveApplication LA
		inner join #TempLeaveDetails LD on LD.Employee_Id = LA.Employee_Id
		and LD.LeaveType_Id = LA.LeaveType_id and LA.isdeleted=0 
		where LA.type=''LOP'' and LA.Status in (''Pending'',''Forwarded'') and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id,LA.LeaveType_id
	) as A inner join #TempLeaveDetails on (#TempLeaveDetails.Employee_Id = A.Employee_Id and #TempLeaveDetails.LeaveType_id = A.LeaveType_id)
	update #TempLeaveDetails set LOP_Days_Remaining = (LOP_Days - (LOP_Days_Availed_Approved + LOP_Days_Availed_InProgress))
	update #TempLeaveDetails set RestrictedHoliday_Availed_Approved = A.NumberOfDays from
	(
		select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
		inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
		where LA.type=''Restricted Holiday'' and LA.Status = ''Approved'' and LA.isdeleted=0  and
		(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
		and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
		group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Availed_InProgress = A.NumberOfDays from
	(
	select LA.Employee_Id,sum(LA.NumberOfDays) as NumberOfDays from TA_Tbl_LeaveApplication LA
	inner join (select distinct Employee_Id,FromDate,ToDate from #TempLeaveDetails) as LD on LD.Employee_Id = LA.Employee_Id
	where LA.type=''Restricted Holiday'' and LA.Status in (''Pending'',''Forwarded'') and LA.isdeleted=0  and
	(LA.Leave_FromDate between LD.FromDate and LD.ToDate)
	and (LA.Leave_ToDate between LD.FromDate and LD.ToDate)
	group by  LA.Employee_Id
	) as A inner join #TempLeaveDetails on #TempLeaveDetails.Employee_Id = A.Employee_Id
	update #TempLeaveDetails set RestrictedHoliday_Remaining = (RestrictedHoliday - (RestrictedHoliday_Availed_Approved + RestrictedHoliday_Availed_InProgress))
	create table #TempLeaveDetails_Final 
	(
	Employee_Code_Id nvarchar(15),
	Employee_Name nvarchar(150),
	Designation nvarchar(250),
	PolicyName nvarchar(50),
	FromDate datetime,
	ToDate datetime,
	LeaveType_Name nvarchar(20),
	Leave_Days decimal(18,1),
	Leave_Days_Availed_Approved decimal(18,1),
	Leave_Days_Availed_InProgress decimal(18,1),
	Leave_Days_Remaining decimal(18,1))
	insert into #TempLeaveDetails_Final select Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining from #TempLeaveDetails
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,''LOP-''+#TempLeaveDetails.LeaveType_Name,isnull(LOP_Days,0),isnull(LOP_Days_Availed_Approved,0),isnull(LOP_Days_Availed_InProgress,0),isnull(LOP_Days_Remaining,0) 
	from #TempLeaveDetails where LOP_Days<>0.0
	insert into #TempLeaveDetails_Final(Employee_Code_Id,Employee_Name,Designation,PolicyName,
	FromDate,ToDate,LeaveType_Name,Leave_Days,Leave_Days_Availed_Approved,Leave_Days_Availed_InProgress,Leave_Days_Remaining)
	select distinct Employee_Code_Id,Employee_Name,Designation,PolicyName,FromDate,ToDate,''Restricted Holiday'',isnull(RestrictedHoliday,0),isnull(RestrictedHoliday_Availed_Approved,0),isnull(RestrictedHoliday_Availed_InProgress,0),
	isnull(RestrictedHoliday_Remaining,0) from #TempLeaveDetails
	DECLARE @dateFormat as int
	SET @dateFormat=(Select DateFormat from Func_TA_GetDateTimeFormat())
	select 
	Employee_Code_Id,
	Employee_Name,
	Designation,
	PolicyName,
	REPLACE(CONVERT(VARCHAR(20), FromDate,@dateFormat),'' '',''-''),
	REPLACE(CONVERT(VARCHAR(20), ToDate,@dateFormat),'' '',''-''),
	LeaveType_Name,
	Leave_Days,
	Leave_Days_Availed_Approved,
	Leave_Days_Availed_InProgress,
	Leave_Days_Remaining
	from #TempLeaveDetails_Final order by Employee_Code_Id,LeaveType_Name
	drop table #TempLeaveDetails
	drop table #TempLeaveDetails_Final
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ExportLeaveData]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ExportLeaveData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 18-Aug-2011
-- Description:	ihave
-- =============================================
--Proc_TA_ExportLeaveData '' Employee_Code_Id, Leave_FromDate, Leave_Todate, LeaveType, NoOfDays, TransactionType'',4,''SuperAdmin'',1,''D'',1
CREATE PROCEDURE [dbo].[Proc_TA_ExportLeaveData]
(
 @SelectedFieldNames nvarchar(2000),
 @MonthClosureId int,
 @UserGroupName varchar(250),
 @ParentID int,
 @Option varchar(10),
 @strFTPOption varchar(10)
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @QUERY VARCHAR(250)
	declare @FromDate datetime
	set @FromDate = (select MonthClosure_Startdate from TA_Tbl_MonthClosure where MonthClosure_Id=@MonthClosureId)
	declare @ToDate datetime
	set @ToDate = (select MonthClosure_Enddate from TA_Tbl_MonthClosure where MonthClosure_Id=@MonthClosureId)
	create table #LevelRights(LevelId int)
    insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
    create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempLeaveData (	
									LeaveApplication_Id int,
									Employee_Code_Id nvarchar(15),
									Employee_Name nvarchar(150),
									Leave_FromDate varchar(25),
									Leave_ToDate varchar(25),
									LeaveType varchar(30),
									LeaveType_Id int,
									NoOfDays numeric(18,1),
									TransactionType varchar(5)
									,ExportSummary_InsertFlag bit default(0),
									ExportSummary_DeleteFlag bit default(0),
									ExportDetail_InsertFlag bit default(0),
									ExportDetail_DeleteFlag bit default(0),
									IsDeleted bit default (0)
								)
    if (@strFTPOption=''1'')
		BEGIN
			insert into #TempLeaveData 					
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + '' '' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''D'' else ''I'' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = ''Approved'' 
					and (ExportDetail_InsertFlag=0 and ExportDetail_DeleteFlag=0)
		END
   else
		BEGIN
			insert into #TempLeaveData 						
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + '' '' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''D'' else ''I'' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = ''Approved'' 
		END
	update #TempLeaveData set LeaveType = LT.LeaveType from #TempLeaveData
	left join TA_tbl_LeaveType LT on #TempLeaveData.LeaveType_Id = LT.LeaveType_Id
	where #TempLeaveData.LeaveType = ''Leave''
	if(@Option = ''D'')
	Begin
	    SET @QUERY=''''
	    SET @QUERY=''select ''+ @SelectedFieldNames + '' from #TempLeaveData''
	    update #TempLeaveData set ExportDetail_InsertFlag=1 where TransactionType=''I'' 
	    update #TempLeaveData set ExportDetail_DeleteFlag =1 where TransactionType=''D''
	End
	else
	Begin 
		SET @QUERY=''''
		SET @QUERY=''SELECT '' + @SelectedFieldNames + '' from (select Employee_Code_Id,sum(NoOfDays) as NoOfDays from #TempLeaveData where TransactionType=''''I'''' group by Employee_Code_Id) ppd ''
		  update #TempLeaveData set ExportSummary_InsertFlag=1 where TransactionType=''I'' 
	      update #TempLeaveData set ExportSummary_DeleteFlag =1 where TransactionType=''D''
	End
	EXEC(@QUERY)
				select	LeaveApplication_Id,
						E.employee_Code_Id,
						E.Employee_FirstName + '' '' + E.employee_LastName as Employee_Name,
						Leave_FromDate,
						Leave_ToDate,
						Type as LeaveType,
						Leavetype_Id,
						NumberOfDays as NoOfDays,
						case TA_Tbl_LeaveApplication.IsDeleted when 1 then ''D'' else ''I'' end as TransactionType,
						TA_Tbl_LeaveApplication.IsDeleted,
						0,0,0,0
				from TA_Tbl_LeaveApplication 
					inner join TA_Tbl_employee E on E.Employee_Id = TA_Tbl_LeaveApplication.Employee_Id
					inner join #EmpLevel EL on EL.EmployeeId = E.Employee_Id
					inner join #LevelRights on #LevelRights.LevelId = EL.levelId
					where (Leave_FromDate between @FromDate and @ToDate) and TA_Tbl_LeaveApplication.Status = ''Approved'' 
					and (ExportDetail_InsertFlag=0 and ExportDetail_DeleteFlag=0)
	drop table #EmpLevel
	drop table #TempLeaveData
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EnterpriseGradeUpdation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EnterpriseGradeUpdation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Created By		:	Manjula.P
Created Date	:	03-Oct-2013
Descriptinos	:	For updating grade while uploading LIC file as Enterprise
*/
CREATE proc [dbo].[Proc_TA_EnterpriseGradeUpdation]
as 
begin
	set nocount on
	UPDATE TA_Tbl_Grade SET Isdeleted =1 where Grade_ID=(select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'')
	UPDATE TA_Tbl_Grade SET Isdeleted =0 where Grade_ID!=(select Grade_ID from Ta_Tbl_Grade where Grade_Name=''SEGrade'')
	update TA_Tbl_Employee set Leave_Sanc_Authority=Te.Leave_Sanc_Authority,Reporting_To=TE.Reporting_To from TA_Tbl_Employee E
	inner join tempemployee Te on E.Employee_Id=Te.Employee_Id
	WHERE Employee_Code_Id <> ''18000000''	
	update TA_Tbl_Title set GradeID=tt.GradeID from TA_Tbl_Title t
	inner join temptitle tt on t.TitleId =tt.TitleId 
	Insert into TA_Tbl_ApprovalSettings
	select CompanyId, OTApproval, LeaveSanction, PermissionSanction, ManualEntry, Emp_Id, Roster, Pattern, ODEntry ,Approval,0
	from TempApprovalSettings
	delete from TempApprovalSettings	
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpType_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpType_MusterRoll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- [Testingcomma]''2014-09-11'',''787,788,789,8,888'',0
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpType_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@employeeType int,
	@UserGroupName varchar(250),
	@ParentId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    if (@Employee_Code_Id<>'''')
		begin
			declare @NextString nvarchar(4000)
			declare @Pos int
			declare @NextPos int
			declare @CommaCheck nvarchar(1) 
			declare @Delimiter nvarchar (10)
			declare @String nvarchar (max)
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
	Declare @sql varchar(max)
	Set @sql=''	select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate,Employee_Code_Id,SwipeCardNo from 
				(
					select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo from TA_Tbl_EmployeeType et
					inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id
					inner join TA_Tbl_EmployeeLevel el	on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights			LR	on LR.LevelId	 = EL.LevelId
					where emp.Isdeleted=0 group by et.EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				) EmpType
				inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
				AND EType.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102)  and EType.TypeId is not null''
	if (@Employee_Code_Id<>'''')
		if(@employeeType<>0 and @employeeType!='''')
			BEGIN									
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'') and EType.TypeId=''+CONVERT(varchar(20),@employeeType)
			End
		else
			begin					
				Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
			End
	else 
		if(@employeeType<>0 and @employeeType!='''')
			BEGIN					
				Set @sql=@sql+'' and EType.TypeId=''+CONVERT(varchar(20),@employeeType)
			End
		else
			Begin				
				Set @sql=@sql 
			end				
	execute(@sql)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckHolidays]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckHolidays]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name 	: Proc_TA_CheckHolidays  ''G'',''09/25/2008'',''10/31/2008'',''test''  
Description 	: check holidays count  
Tables Included : TA_Tbl_Holiday    
Created By 	: Janakaraj.P   
Created On 	: 20-Aug-2007  
Modified By	:    
Modified On 	:  
Proc_TA_CheckHolidays ''G'',''05/Dec/2016'',''09/Dec/2016'',''checking'',1
*/  
CREATE procedure [dbo].[Proc_TA_CheckHolidays]
(
	@HolidayType nvarchar(2),
	@HolidayFdate nvarchar(20),
	@HolidayTodate nvarchar(20),
	@HolidayDescription nvarchar(50),
	@LevelId int
)
AS
BEGIN
	DECLARE @yearSetingId int
	SET @yearSetingId = 0
	SELECT @yearSetingId = YearSettings_Id FROM TA_Tbl_YearSetting WHERE IsActive = 1
	IF(@LevelId = 0)
	BEGIN	
		SELECT COUNT(*) as HCount FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
		where 
		(
			((TA_Tbl_Holiday.Holiday_FromDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0) 
			or 
			(TA_Tbl_Holiday.Holiday_ToDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId
		) 
		or 
		(TA_Tbl_Holiday.Holiday_Description= @HolidayDescription and TA_Tbl_Holiday.Isdeleted=0 and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId) 
		or 
		(
			((@HolidayFdate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
		 or 
			(@HolidayTodate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId
		) 
	END
	ELSE
	BEGIN
 		SELECT COUNT(*) as HCount FROM TA_Tbl_Holiday 
		inner join TA_Tbl_HolidayChildTable hct on ta_tbl_holiday.Holiday_Id=hct.Holiday_Id
		INNER JOIN TA_Tbl_YearSetting ON TA_Tbl_Holiday.YearSettings_Id = TA_Tbl_YearSetting.YearSettings_Id
		where 
		(
			((TA_Tbl_Holiday.Holiday_FromDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0) 
			or 
			(TA_Tbl_Holiday.Holiday_ToDate between @HolidayFdate and @HolidayTodate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (hct.LevelId = @LevelId or hct.LevelId=0)
		) 
		or 
		(TA_Tbl_Holiday.Holiday_Description= @HolidayDescription and TA_Tbl_Holiday.Isdeleted=0 and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and 
		(hct.LevelId= @LevelId or hct.LevelId = 0)) 
		or 
		(
			((@HolidayFdate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0)
		 or 
			(@HolidayTodate between TA_Tbl_Holiday.Holiday_FromDate and TA_Tbl_Holiday.Holiday_ToDate and TA_Tbl_Holiday.Isdeleted=0))
		and TA_Tbl_YearSetting.YearSettings_Id = @yearSetingId and (hct.LevelId = @LevelId or hct.LevelId = 0)
		) 
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[TA_Proc_EmployeeLog]    Script Date: 03/25/2021 10:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TA_Proc_EmployeeLog]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Thilakraj Chinaaraj>
-- Create date: <10-Dec-2015>
-- Description:	<For Sample Web services>
/*
Exec TA_Proc_EmployeeLog ''789'',''2016-02-26''
*/
-- =============================================
CREATE PROCEDURE [dbo].[TA_Proc_EmployeeLog]
(	@EmployeeCodeID  int=null,
	@date  date =null
)
AS
BEGIN
Declare @Monday as Date
Declare @Saturday as Date
DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), 
	    TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
Create table #TempAttendanceDetails (FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),LevelName nvarchar(250),Designation nvarchar(250),Date VARCHAR(20),InTime varchar(20),OutTime varchar(20),HrsWork varchar(20),
	TotalMinsWorked varchar(20),Shift_ShortName varchar(100),ShiftId int,shift_TotalWorkingHours nvarchar(50),LunchHours varchar(50),DefinedWorkHours varchar(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId int, CategoryName NVARCHAR(50),thirdSat bit,DinnerHours varchar(50),
	ArmisMin BIGINT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10), MinWorkHours BIGINT, ToolTip VARCHAR(MAX))
if (@EmployeeCodeID is null)
	Begin
		Set @EmployeeCodeID=973;
	End
if (@date is null)
	Begin
		Set @date=GETDATE();
	End
	SELECT RD.CLK_ID,RD.CLK_CARDID as ''Employee ID'',RD.CLK_DATE as ''Date'' ,RD.CLK_TIME as ''Time'' ,T.Terminal_Name,PT.PunchType
	from TA_Tbl_Clk_RawData RD
	Inner join TA_Tbl_Terminal T on T.Terminal_ReaderID=RD.CLK_DEVICEID
	Inner join TA_Tbl_PunchTypes PT on PT.Value=RD.CLK_TYPE and T.Terminal_Id=PT.Terminal_Id 
	Where RD.CLK_CARDID=@EmployeeCodeID and  RD.CLK_DATE=@date
	order by CLK_ID 
	SELECT E.Employee_FirstName + '' '' +E.Employee_LastName,PD.Employee_Code_Id as ''Employee ID'',
	PD.Date as ''Date'' , PD.InTime,PD.OutTime,
	CASE WHEN LEN(CAST((B.TotalBreakmin/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((B.TotalBreakmin/60) AS VARCHAR(25)) ELSE  CAST((B.TotalBreakmin/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((B.TotalBreakmin%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((B.TotalBreakmin%60) AS VARCHAR(25)) ELSE CAST((B.TotalBreakmin%60) AS VARCHAR(25)) END as ''Break Hrs'',
	PD.HrsWork , ''00:00'' as ''Work so For''
	from  TA_Tbl_ProcessedData PD 
	Inner join TA_Tbl_Employee E On E.Employee_Code_Id=PD.Employee_Code_Id
	Inner Join ta_tbl_TotalBreakHours B on B.Employee_Code_Id=PD.Employee_Code_Id and B.ShiftDate=PD.Date
	Where PD.Employee_Code_Id=@EmployeeCodeID and  PD.Date=@date
Set @Monday= dateadd(wk, datediff(wk, 0, @date), 0)
Set @Saturday= dateadd(wk, datediff(wk, 0, @date), 0) + 5 
INSERT INTO @ArmisData
SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,''00:00'',REPLACE(CAST(ISNULL(TotalTask, ''0.0'') AS VARCHAR), ''.'', '':'')) AS BIGINT) END) FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@Monday, @Saturday, @EmployeeCodeID)
	insert into #TempAttendanceDetails
		select 
			pd.fnAttendanceCode + case  when Status is null then '''' else ''(BL)'' end as FirstSession,
			pd.anAttendanceCode + case  when Status is null then '''' else ''(BL)'' end  as SecondSession, 
			e.Employee_Code_Id as Employee_Id,
			isnull(e.Employee_FirstName,'''') +  space(1) + isnull(e.Employee_LastName,'''') as empName,
			replace(dbo.Ta_Tbl_levelDetails.name,''&amp;'',''&'') as BranchName,
			replace(T.TitleName,''&amp;'',''&'') as Designation,
			convert(varchar(11),pd.date,101) as Date,
			ISNULL(pd.InTime, ''-''),
			ISNULL(pd.OutTime, ''-''),
			ISNULL(pd.HrsWork, ''-''), 
			((substring(isnull(pd.HrsWork,''00:00''),0,3)*60) + (substring(isnull(pd.HrsWork,''00:00''),4,2))) as TotalMinsWorked
			,(shf.Shift_ShortName + ''('' + shf.Shift_StartTime + '' - ''  + shf.Shift_EndTime + '')'') as Shift_ShortName,
			pd.shift_id as ShiftID,
			shf.shift_TotalWorkingHours,
			ISNULL(pd.BreakHours, ''-'') as LunchHours , 
			TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours,
			DATENAME(DW,pd.date), 
			(CASE WHEN ((DATENAME(DW,pd.date) != ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''Saturday'') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''.5'', ''.3''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '':'', ''.'') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END)
			,(CASE WHEN ISNULL(Pd.BreakIn, '''') <> '''' AND ISNULL(Pd.BreakOut, '''') <> '''' AND (DATEDIFF(MI, ISNULL(SS.MaxLunchHours, ''00:40''), ISNULL(REPLACE(pd.BreakHours, ''-'', ''''), ''00:00'')) > 0) THEN 1 ELSE 0 END),TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,0,DinnerHours, 0, DATEDIFF(MI, ''00:00'', ISNULL(SS.MaxWorkPlaceInHours, ''00:10'')), ''00:00'', TBH.TotalBreakmin, (CASE WHEN (DATENAME(DW,pd.date) != ''Saturday'') THEN DATEDIFF(MI, ''00:00'',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''.5'', ''.3''), 0.0)), ''.'', '':'')) ELSE DATEDIFF(MI, ''00:00'',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''.5'', ''.3''), 0.0)), ''.'', '':'')) END), NULL
		from Ta_Tbl_Employee e 
		inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id 	
		inner join ta_tbl_TotalBreakHours TBH on TBH.Employee_Code_Id=pd.Employee_Code_Id and TBH.Shiftdate=pd.date 
		inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId
		inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id
		inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID 	
		inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId
		inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId   
		inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId
		inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId
		inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId
		inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId
		inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId 
		left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id
		LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId 
		where e.Isdeleted=0 and e.report_exclude=0 AND TA_Tbl_Grade.Grade_Level>=0 and (e.Employee_Code_Id = '''' + cast(@EmployeeCodeID as nvarchar(100)) + '''') and e.employee_Status=1 and((pd.date >= CONVERT(DATETIME, '''' + cast(@Monday as nvarchar(11)) + '''', 102) and pd.date <= CONVERT(DATETIME, '''' + cast(@Saturday as nvarchar(11)) + '''', 102)))
	Declare @firstsat date
	Declare @ThirdSat date
	 Select  @firstsat= dateadd(dd,(datediff(dd,-53685,dateadd(mm,datediff(mm,0,@Saturday),6))/7)*7,-53685)
	 Select @ThirdSat=DATEADD(dd,14,@firstsat)
	 Update #TempAttendanceDetails set thirdSat=1 where  #TempAttendanceDetails.Day=''Saturday'' and #TempAttendanceDetails.Date=@ThirdSat
	 create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATE, ArmisHrs BIGINT)
   INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.DefinedWorkHours,
			SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
			0,
			SUM(CAST(TA.totalMinsWorked AS INT)),
			0,
			TA.CategoryName,
			CAST(MAX(TA.[Date]) AS DATE),
			SUM(ArmisMin)
		FROM #TempAttendanceDetails TA
			INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != ''Sunday''
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
	 update #TempAttendanceSummary set SupposedToWorkHours = (DefinedWorkHours - (HoursToDeduct))
	 update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	 update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	 select 
		Employee_Code_Id,
		EmployeeName,
		DefinedWorkHours,		
		HoursToDeduct,
	    SupposedToWorkHours,
		CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN ''0'' +  cast((ActualWorkHours/60) as varchar(25)) ELSE  cast((ActualWorkHours/60) as varchar(25)) END  + '':'' + CASE  WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN ''0'' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
		CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN ''0'' +  cast((LessHours/60) as varchar(25)) ELSE  cast((LessHours/60) as varchar(25)) END  + '':'' + CASE  WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN ''0'' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
		CategoryName,
		(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN ''0'' +  CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END  + ''.'' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid,
		CASE WHEN LEN(CAST((ArmisHrs/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((ArmisHrs/60) AS VARCHAR(25)) ELSE  CAST((ArmisHrs/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((ArmisHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisHrs%60) AS VARCHAR(25)) ELSE CAST((ArmisHrs%60) AS VARCHAR(25)) END AS ArmisHrs
	 from #TempAttendanceSummary
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeBonusLeave]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeBonusLeave]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================      
-- Author:  Kumuthini      
-- ALTER  date: 12-Jan-09         
-- Proc_TA_EmployeeBonusLeave '''','''','''',0,0,''SuperAdmin'',''1'',3      
-- Description: Employee Bonus Leave Details      
-- =============================================      
CREATE      PROCEDURE [dbo].[Proc_TA_EmployeeBonusLeave]
 @Employee_ID int,
 @EmployeeId nvarchar(100),      
 @EmployeeName nvarchar(50),      
 @LevelID nvarchar(max),      
 @EmployeeCategory int,      
 @EmployeeType int,      
 @UserGroupName nvarchar(250),      
 @GradeLevel nvarchar(20),  
 @YearSettingsId int,
 @EmpSwipeCard nvarchar(20),
 @ParentID int       
AS      
BEGIN      
	SET NOCOUNT ON;
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@Employee_ID) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@Employee_ID) as EmpAutoId
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
(
	[DesignationId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
(
	[TypeId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate] ASC
)ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
(
	[CategoryId] ASC
) ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
(
	[EmployeeId] ASC
) ON [PRIMARY]
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and EL.LevelId is not null
--select * from #EmpLevel
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102) and ED.DesignationId is not null
--select * from #EmpDesignation
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)  and EType.TypeId is not null
--select * from #EmpType
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(getdate() as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--select * from #EmpCategory
declare @sqlQuery as nvarchar(max)   
create table #empBonusLeave(Department nvarchar(500),Department1 nvarchar(500),EmployeeCodeId nvarchar(500),EmployeeId nvarchar(500),EmpAutoId int,DateOfJoining datetime,EmpName nvarchar(500),BonusLeaveQuota int,BonusLeaveTaken int,BonusLeaveAvailable int,YearSettings_Id int)  
  set @sqlQuery = ''''   
  set @sqlQuery = @sqlQuery + ''SELECT replace(Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as Department, replace(dept.name,''''&amp;'''',''''&'''') as Department1, dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId, dbo.TA_Tbl_Employee.SwipeCardNo as EmployeeId, dbo.TA_Tbl_Employee.Employee_Id as EmpAutoId,dbo.TA_Tbl_Employee.DateOfJoining,''      
  set @sqlQuery = @sqlQuery + '' ISNULL(Employee_firstName,'''''''') + Space(1) + isnull(Employee_LastName,'''''''') as EmpName,''''0'''' AS BonusLeaveQuota,''''0'''' AS BonusLeaveTaken,''''0'''' AS BonusLeaveAvailable,'''''' + cast(@YearSettingsId as nvarchar(20)) + '''''' as YearSettings_Id ''      
  set @sqlQuery = @sqlQuery + '' FROM dbo.TA_Tbl_Employee ''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN TA_Tbl_EmployeeLevel ON TA_Tbl_Employee.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER JOIN dbo.Ta_Tbl_levelDetails ON dbo.TA_Tbl_EmployeeLevel.LevelID = dbo.Ta_Tbl_levelDetails.id ''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER join Ta_Tbl_levelDetails dept  on Ta_Tbl_levelDetails.ParentId = dept.id''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeCategory  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_EmployeeType  on ta_tbl_Employee.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''      
  set @sqlQuery = @sqlQuery + '' LEFT OUTER join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''       
  SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation edes ON ta_tbl_Employee.Employee_Id = edes.EmployeeId ''      
  SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Title tit ON tit.TitleId=edes.DesignationId ''      
  SET @sqlQuery = @sqlQuery + '' INNER JOIN TA_Tbl_Grade grd ON grd.Grade_ID = tit.GradeId ''      
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=edes.EffectiveDate and #EmpDesignation.employeeid=edes.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
		set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''
 set @sqlQuery = @sqlQuery + '' where   (dbo.TA_Tbl_Employee.Isdeleted = 0) AND (dbo.TA_Tbl_Employee.Employee_Code_Id <> ''''18000000'''') ''      
if(@UserGroupName<>''SuperAdmin'')      
  begin      
  set @sqlQuery = @sqlQuery + '' AND grd.Grade_Level>='' + @GradeLevel + '' ''      
  end      
if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
  if not(@EmployeeName='''')      
  begin      
   set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''      
  end      
  if not (@EmployeeId='''')      
  begin      
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_Employee.Employee_Code_Id = '''''' + cast (@EmployeeId as nvarchar(50)) + '''''' ''      
  end      
  If Not (@EmpSwipeCard = '''')  
    Begin  
		  Set @sqlQuery = @sqlQuery + ''And TA_Tbl_Employee.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
	End 
  if not (@EmployeeCategory=0)      
  begin      
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@EmployeeCategory as nvarchar(8))      
  end      
  if not (@EmployeeType=0)      
  begin      
   set @sqlQuery = @sqlQuery + '' and TA_Tbl_EmployeeType.TypeId = '' + cast(@EmployeeType as nvarchar(8))      
  end      
  set @sqlQuery = @sqlQuery + '' order by dbo.TA_Tbl_Employee.Employee_code_Id ''      
insert into #empBonusLeave exec(@sqlQuery)   
update #empBonusLeave set BonusLeaveQuota=EBL.BonusLeaveQuota  
from TA_Tbl_EmployeeBonusLeave EBL   
inner join #empBonusLeave TBL  
on   
EBL.EmployeeId=TBL.EmpAutoId and  
EBL.YearSettingId=TBL.YearSettings_Id  
select * from #empBonusLeave  
drop table #empBonusLeave  
drop table #EmpLevel
drop table #EmpDesignation
drop table #EmpType
drop table #EmpCategory
drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employee_ForShiftReAllocation1]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Employee_ForShiftReAllocation1] ''05/23/2011'',''05/23/2011'',''1'',18,'''',''SuperAdmin'',323,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation1]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id varchar(20),EmployeeAutoID bigint,EmpName varchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	create table #TempShiftAllocatedEmployeeTS (EmployeeID int,Year int,Month int,Day varchar(20),ShiftId int,Date varchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''''''') as EmployeeName ''
	set @sqlQuery = @sqlQuery + '' from ta_tbl_Employee ''
    set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)''
	if not(@EmployeeName='''')
	begin
		set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if not (@empId='''')
	begin
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_Employee.Employee_code_id= '''''' + @empId + '''''' )''
	end
	set @sqlQuery = @sqlQuery + ''  order by ta_tbl_Employee.Employee_FirstName ''
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployeeTS (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 or ShiftId=0
	delete from #TempShiftAllocatedEmployeeTS where isDate(Date) = 0 or ShiftId=0
	insert into #TempShiftAllocatedEmployeeTS  
	select * from #TempShiftAllocatedEmployee where 
	not exists (select * from #TempShiftAllocatedEmployeeTS where EmployeeID=#TempShiftAllocatedEmployee.EmployeeID
	and Date=#TempShiftAllocatedEmployee.Date) and Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from #TempEmployeeWithDate
	--select * from #TempShiftAllocatedEmployee where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from  #TempShiftAllocatedEmployeeTS where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,''0'' as SelectedRecords from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	delete from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where LoggedInEmployeId = @LoggedInemployeeId
    -- select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= cast(E.Date as datetime) and (E.Date between dateadd(dd,-1,@fromDat) 
	--and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId<>0
	--and PS.ShiftId=@shift
    --inserts the employee with current shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId=@shift
	--Updates the Previous day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.PreviousDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--Updates the Next day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.NextDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
	--select * from ta_tbl_employee
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
drop table #TempShiftAllocatedEmployeeTS
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_Employee_ForShiftReAllocation]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_Employee_ForShiftReAllocation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Sashma
-- Create date: 24-May-2011
-- Description:	To select employees with the specific shift Id and specified duration for shift re-allocating.
-- [dbo].[Proc_Ta_Employee_ForShiftReAllocation] ''05/23/2011'',''05/23/2011'',''1'',18,'''',''SuperAdmin'',323,1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_Ta_Employee_ForShiftReAllocation]
(
	@fromDat datetime,
	@ToDat datetime,
	@empId varchar(100),
	@shift int,
	@EmployeeName varchar(50),
	@UserGroupName varchar(250),
    @ParentId int,
    @LoggedInEmployeeId int
)
AS
BEGIN	
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #LevelRights(LevelId int)
insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #EmployeeIds(EmpAutoId int)
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@LoggedInEmployeeId) as EmpAutoId  
    insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@LoggedInEmployeeId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
(
	[LevelId] ASC
) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
(
	[EmployeeId] ASC
)ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
	create table #TempEmployee(Employee_Code_Id nvarchar(20),EmployeeAutoID bigint,EmpName nvarchar(150))
	create table #TempEmployeeWithDate(Employee_Code_Id nvarchar(20),EmployeeAutoID bigint,EmpName nvarchar(150),Date datetime)
	create table #TempShiftAllocatedEmployee (EmployeeID int,Year int,Month int,Day nvarchar(20),ShiftId int,Date nvarchar(20))
	create table #TempShiftAllocatedEmployeeTS (EmployeeID int,Year int,Month int,Day nvarchar(20),ShiftId int,Date nvarchar(20))
	declare @sqlQuery as varchar(8000)
	set @sqlQuery = ''''
	set @sqlQuery = @sqlQuery + ''insert into #TempEmployee select dbo.TA_Tbl_Employee.Employee_Code_Id as EmployeeCodeId,dbo.TA_Tbl_Employee.Employee_Id as EmployeeAutoId,ta_tbl_Employee.Employee_FirstName + space(1) + isnull(ta_tbl_employee.Employee_LastName,'''''''') as EmployeeName ''
	set @sqlQuery = @sqlQuery + '' from ta_tbl_Employee ''
    set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.employeeid=TA_Tbl_Employee.Employee_Id ''
    set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on #EmpLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' Inner join #LevelRights on #LevelRights.LevelId = #EmpLevel.levelId ''
	set @sqlQuery = @sqlQuery + '' where (ta_tbl_employee.isdeleted=0 and ta_tbl_employee.employee_status=1)''
	if not(@EmployeeName='''')
	begin
		set @sqlQuery = @sqlQuery + ''and (dbo.TA_Tbl_Employee.Employee_FirstName + '''' ''''+  isnull(dbo.TA_Tbl_Employee.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
	end
	if not (@empId='''')
	begin
		set @sqlQuery = @sqlQuery + '' And (TA_Tbl_Employee.Employee_code_id= '''''' + @empId + '''''' )''
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (TA_Tbl_Employee.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	set @sqlQuery = @sqlQuery + ''  order by ta_tbl_Employee.Employee_FirstName ''
	exec(@sqlQuery)
	--select * from #TempEmployee
	;WITH DateField AS
	(
	SELECT dateadd(dd,-1,@fromDat) Dates
	UNION ALL
	SELECT (Dates + 1)
	FROM DateField
	WHERE Dates < dateadd(dd,1,@ToDat)
	)
	insert into #TempEmployeeWithDate SELECT TE.Employee_Code_Id,TE.EmployeeAutoID,TE.EmpName,DF.Dates from #TempEmployee TE
	cross join DateField as DF  where Df.Dates between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat) Option (maxrecursion 1000) 
	--select * from #TempEmployeeWithDate
	--Unpivot the permanent shift allocation table.
	insert into #TempShiftAllocatedEmployee (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_tbl_PermanentShiftAllocation PS inner join #TempEmployee E on E.EmployeeAutoID=PS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--Unpivot the temporaray shift allocation table.
	insert into #TempShiftAllocatedEmployeeTS (EmployeeID,Year,Month,Day,ShiftId,Date)SELECT EmployeeID, Year, Month ,Day,ShiftId,
	Date = cast(Month as varchar(10)) + ''/'' + Replace(Replace(Day,''Day'',''''),''Shift'','''') + ''/'' + cast(Year as varchar(10))
	FROM 
	   (SELECT EmployeeID,Year, Month, Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift
		FROM TA_Tbl_TemporaryShiftAllocation TS inner join #TempEmployee E on E.EmployeeAutoID=TS.EmployeeId
		where Year in (Year(@fromDat),Year(@ToDat))) p
	UNPIVOT
	   (ShiftId FOR Day IN 
		  (Day1Shift, Day2Shift, Day3Shift, Day4Shift, Day5Shift, Day6Shift, Day7Shift, Day8Shift, Day9Shift, Day10Shift,
		  Day11Shift, Day12Shift, Day13Shift, Day14Shift, Day15Shift, Day16Shift, Day17Shift, Day18Shift, Day19Shift, Day20Shift,
		  Day21Shift, Day22Shift, Day23Shift, Day24Shift, Day25Shift, Day26Shift, Day27Shift, Day28Shift, Day29Shift, Day30Shift,Day31Shift)
	)AS unpvt;
	--delete from permanant table if the date is not valid
	delete from #TempShiftAllocatedEmployee where isDate(Date) = 0 or ShiftId=0
	delete from #TempShiftAllocatedEmployeeTS where isDate(Date) = 0 or ShiftId=0
	insert into #TempShiftAllocatedEmployeeTS  
	select * from #TempShiftAllocatedEmployee where 
	not exists (select * from #TempShiftAllocatedEmployeeTS where EmployeeID=#TempShiftAllocatedEmployee.EmployeeID
	and Date=#TempShiftAllocatedEmployee.Date) and Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from #TempEmployeeWithDate
	--select * from #TempShiftAllocatedEmployee where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	--select * from  #TempShiftAllocatedEmployeeTS where Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)
	select distinct E.EmployeeAutoID,E.Employee_Code_Id,E.EmpName,''0'' as SelectedRecords from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between @fromDat and @ToDat) and PS.ShiftId=@shift
	delete from TA_Tbl_EmployeeShiftId_ForShiftReAllocation where LoggedInEmployeId = @LoggedInemployeeId
    -- select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	--from #TempShiftAllocatedEmployee PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	--where cast(PS.Date as Datetime)= cast(E.Date as datetime) and (E.Date between dateadd(dd,-1,@fromDat) 
	--and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId<>0
	--and PS.ShiftId=@shift
    --inserts the employee with current shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	insert into TA_Tbl_EmployeeShiftId_ForShiftReAllocation select E.EmployeeAutoID,E.Date,PS.ShiftId,0,0,@LoggedInEmployeeId,0
	from #TempShiftAllocatedEmployeeTS PS inner join  #TempEmployeeWithDate E on E.EmployeeAutoID=PS.EmployeeID
	where cast(PS.Date as Datetime)= E.Date and (E.Date between dateadd(dd,-1,@fromDat) and dateadd(dd,1,@ToDat)) 
	--and PS.ShiftId=@shift
	--Updates the Previous day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.PreviousDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,-1,A.Date)
	--Updates the Next day shift Id in the "TA_Tbl_EmployeeShiftId_ForShiftReAllocation" to check overlapping
	update A set A.NextDayShift = B.CurrentShiftId
	from TA_Tbl_EmployeeShiftId_ForShiftReAllocation A inner join TA_Tbl_EmployeeShiftId_ForShiftReAllocation B on B.Date=dateadd(dd,1,A.Date)
	--select * from ta_tbl_employee
--Remove the temporary tables here   
drop table #EmpLevel
drop table #LevelRights
drop table #TempEmployee
drop table #TempEmployeeWithDate
drop table #TempShiftAllocatedEmployee
drop table #TempShiftAllocatedEmployeeTS
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmpLevel_MusterRoll]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmpLevel_MusterRoll]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		R.Manikandan
-- Create date: 06-08-2015
-- Description:	Get the employee details based on selecte levels
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_EmpLevel_MusterRoll]
	-- Add the parameters for the stored procedure here
	@todat datetime,
	@Employee_Code_Id varchar(max),
	@UserGroupName varchar(250),
	@ParentId int,
	@EmployeeName varchar(max)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @NextString nvarchar(4000)
	declare @Pos int
	declare @NextPos int
	declare @CommaCheck nvarchar(1) 
	declare @Delimiter nvarchar (10)
	declare @String nvarchar (max)
	if (@Employee_Code_Id<>'''')
		begin			
			set @Delimiter = '',''
			set @NextString = ''''
			set @CommaCheck = right(@Employee_Code_Id,1)  
			set @Employee_Code_Id = @Employee_Code_Id + @Delimiter 
			set @Pos = charindex(@Delimiter,@Employee_Code_Id)
			set @NextPos = 1 
			while (@pos <>  0)  
			begin
				if @NextString=''''
					begin
						set @NextString =''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				else
					begin
						set @NextString =@NextString+'',''+''''''''+substring(@Employee_Code_Id,1,@Pos - 1)+''''''''
					end
				set @Employee_Code_Id = substring(@Employee_Code_Id,@pos +1,len(@Employee_Code_Id))
				set @NextPos = @Pos
				set @pos  = charindex(@Delimiter,@Employee_Code_Id)
			end
			set @Employee_Code_Id=@NextString
		end	
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentId)
    -- Insert statements for procedure here
	Declare	@sql varchar(max)
	Set @sql=''	select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,Employee_Code_Id,SwipeCardNo  from 
				(
					select max(el.EffectiveDate) as EffectiveDate,EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
					from TA_Tbl_EmployeeLevel el					
					inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
					Inner join #LevelRights on #LevelRights.LevelId = EL.LevelId
					where emp.Isdeleted=0 group by EmployeeId,Employee_Code_Id,emp.SwipeCardNo
				)ELevel
				inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId				
				AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nvarchar(50))+'''''', 102) and EL.LevelId is not null
			''	
	if (@Employee_Code_Id<>'''')
		begin					
			Set @sql=@sql+'' and Employee_Code_Id in(''+cast(@Employee_Code_Id as varchar(max))+'')''
		End
	else
		Begin				
			Set @sql=@sql 
		end	
	execute(@sql)		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- Proc_TA_EmployeeDetailsForPayrollProcess ''2019-05-30 00:00:00.000'',''1'',''SuperAdmin'',1,3,1,0,''Process'',''<NewDataSet />'','''',''''
/*
Modified By       :     Manjula.P
Modified On       :     07-Oct-2013
Descriptinos      :     Added where condition by Manjula.P on 07-Oct-2013 to avoiding Date out of range error while updating Early out Mantis : 0019299 
*/
CREATE PROCEDURE [dbo].[Proc_TA_EmployeeDetailsForPayrollProcess]
@MonthClosureEndDate nVarchar(15),
@Levels varchar(8000),
@UserGroupName varchar(250),
@ParentId int,
@MonthCloseID int,
@AuditEmpId int,
@ProcessCount int,
@ProcessType varchar(50),
@strEmployees xml,
@Employee_code_Id varchar(25),
@Employeename varchar(50)
AS
BEGIN TRY
      BEGIN TRANSACTION    -- Start the transaction
            SET NOCOUNT ON;
            Declare @RowCountEmployeeID int
            Declare @RowCountEmployeeName int
    create table #EmployeeID(EmployeeID varchar(25))
            create table #EmployeeName(EmployeeName varchar(25))
            if(@Employee_code_Id is not null and @Employee_code_Id <> '''')
            begin
                  if(SUBSTRING(@Employee_code_Id,LEN(@Employee_code_Id),len(@Employee_code_Id)) = '','')
                  begin
                        set @Employee_code_Id=SUBSTRING(@Employee_code_Id,0,len(@Employee_code_Id))             
                  end
                        insert into #EmployeeID
                        select value from dbo.split(@Employee_code_Id,'','')
                        select @RowCountEmployeeID=COUNT(EmployeeID) from #EmployeeID                        
          end
            if(@EmployeeName is not null and @EmployeeName <> '''')
            begin
                  if(SUBSTRING(@EmployeeName,LEN(@EmployeeName),len(@EmployeeName)) = '','')
                  begin
                        set @EmployeeName=SUBSTRING(@EmployeeName,0,len(@EmployeeName))                        
                  end 
                        insert into #EmployeeName
                        select value from dbo.split(@EmployeeName,'','')                    
                        select @RowCountEmployeeName=COUNT(EmployeeName) from #EmployeeName                       
                  end
      --Temporary table''s creation
      create table #ReprocessEmployees(EmployeeCodeId varchar(15))
      create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
      create table #LevelRights(LevelId int)
      insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
      --Employee Level Indexes
      /****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
      CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
      (
            [EffectiveDate] ASC
      ) ON [PRIMARY]
      /****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
      CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
      (
            [LevelId] ASC
      ) ON [PRIMARY]
      /****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
      CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
      (
            [EmployeeId] ASC
      )ON [PRIMARY]
      CREATE TABLE #TempProcessedData
      (
            [Process_Rec_ID] bigint,[Employee_Code_Id] nvarchar(20),
            [Date] datetime,  [Shift_Id] int,
            [InTime] nvarchar(25),[OutTime] nvarchar(25),
            [HrsWork] nvarchar(10),[HrsOT] nvarchar(10),
            [NormOT] nvarchar(10),[OffOT] nvarchar(10),
            [HolOT] nvarchar(10),[EarlyOut] nvarchar(10),
            [LateIn] nvarchar(10),[Attendance] nvarchar(20),
            [WorkHrs] nvarchar(10),[HrsLess] nvarchar(10),
            [HrsExtra] nvarchar(10),[LateInMins] float,
            [EarlyOutMins] float,[ExtraMins] float,
            [OtMins] float,[OvertimeStatus] nvarchar(50),
            [TotalDays] numeric(18, 1),[LeaveCode] nvarchar(20),
            [LateEntryReason] nvarchar(260),[EarlyOutReason] nvarchar(260),
            [ProcessFlag] bit,[Status] nvarchar(50),
            [FNAttendanceCode] nvarchar(15),[ANAttendanceCode] nvarchar(15),[HoursWorkInMins] float,
            [LessHoursInMins] float,[WorkedHrsInMins] float,
            SPEC_NormOT1 nvarchar(10),
            SPEC_NormOT2 nvarchar(10),
            SPEC_OffOT1	nvarchar(10),
            SPEC_OffOT2	nvarchar(10),
            SPEC_HOLOT1	nvarchar(10),
            SPEC_HOLOT2	nvarchar(10)
      )
      Declare @Index int
      Set @Index = 0;
      EXEC sp_xml_preparedocument @Index OUTPUT, @strEmployees
      insert into #ReprocessEmployees (EmployeeCodeId)
      select EmployeeId from OpenXML(@Index, ''/NewDataSet/ReprocessEmployees'')
      With (EmployeeId varchar(15) ''EmployeeId'')
      Exec sp_xml_removedocument @Index   
      DECLARE @SQLQUERY VARCHAR(8000)
      SET @SQLQUERY=''''
      --select * from #ReprocessEmployees
      --Employee Level insert in Temporary table
      if exists(select * from #ReprocessEmployees)
      BEGIN
                  insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
                  select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
                  inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
                  inner join #ReprocessEmployees on #ReprocessEmployees.EmployeeCodeId=emp.Employee_Code_Id
                  where emp.Isdeleted=0 group by EmployeeId) ELevel
                  inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
                  AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@MonthClosureEndDate as nvarchar(50)), 102) and EL.LevelId is not null
      ENd
      else
      BEGIN
                  insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
                  select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
                  inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
                  where emp.Isdeleted=0 group by EmployeeId) ELevel
                  inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
                  AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@MonthClosureEndDate as nvarchar(50)), 102) and EL.LevelId is not null
      END
      if (@ProcessType=''BindGrid'')
      BEGIN
            SET @SQLQUERY='''' + ''SELECT E.Employee_Id,E.Employee_Code_Id,E.SwipeCardNo,E.Employee_FirstName + Space(1) + isnull(E.Employee_LastName,'''''''') as "Employee Name" FROM TA_Tbl_Employee E ''
            SET @SQLQUERY=@SQLQUERY +'' INNER JOIN TA_Tbl_EmployeeLevel ON E.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId ''
            SET @SQLQUERY=@SQLQUERY +'' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
            SET @SQLQUERY=@SQLQUERY +'' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.Levelid ''
            IF(@RowCountEmployeeID >0)
            BEGIN
                        SET @SQLQUERY=@SQLQUERY +'' Inner join #EmployeeID ON #EmployeeID.EmployeeID  = E.EMPLOYEE_CODE_ID ''
            END
            if(@RowCountEmployeeName >0)
            begin
                        SET @SQLQUERY=@SQLQUERY +'' Inner join #EmployeeName on #EmployeeName.EmployeeName = E.Employee_FirstName '' 
            end
            SET @SQLQUERY=@SQLQUERY +'' WHERE E.Employee_Firstname<>''''Administrator'''' AND E.Isdeleted = 0''        
            EXEC(@SQLQUERY)
      END
      else
      BEGIN
            declare @fromDat datetime
            declare @todat datetime
            select @fromDat=MonthClosure_StartDate,@todat=MonthClosure_EndDate from Ta_Tbl_MonthClosure where MonthClosure_Id=@MonthCloseID
            insert into #TempProcessedData
            select [Process_Rec_ID],pd.[Employee_code_id],pd.[Date],[Shift_Id],[InTime],[OutTime],[HrsWork],[HrsOT],[NormOT],[OffOT],[HolOT],[EarlyOut],
            [LateIn],[Attendance],[WorkHrs],[HrsLess],[HrsExtra],[LateInMins],[EarlyOutMins],[ExtraMins],[OtMins],[OvertimeStatus],[TotalDays],
            [LeaveCode],[LateEntryReason],[EarlyOutReason],[ProcessFlag],[Status],[FNAttendanceCode],[ANAttendanceCode],[HoursWorkInMins],[LessHoursInMins],substring([WorkHrs],0,charindex('':'',[WorkHrs]))*60+substring([WorkHrs],charindex('':'',[WorkHrs])+1,len([WorkHrs])) as [WorkedHrsInMins],
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_NormOTHrs1 end,
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_NormOTHrs2 end,
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_OffOTHrs1 end,
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_OffOTHrs2 end,
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_HolOTHrs1 end,
            Case when PD.OvertimeStatus=''Approved'' then spot.Modified_Spec_HolOTHrs2 end
            from TA_Tbl_ProcessedData PD
            Left outer join Ta_tbl_specialOvertimeDetails spot on (PD.Employee_Code_Id=spot.Employee_code_id and PD.Date=spot.Date)
            where PD.Employee_Code_Id in (select SwipeCardNo from ta_tbl_employee e
            inner join #EmpLevel el on el.employeeid=e.employee_id
            inner join #LevelRights lr on lr.levelId=el.levelid WHERE e.Employee_Firstname<>''Administrator'' AND e.Isdeleted = 0) AND
            (PD.Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
            AND (PD.Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
            --select * from #TempProcessedData 
            CREATE TABLE #TempPayrollProcessDetails(
            [MonthClosure_Id] [int] NULL,
            [Employee_Id] [nvarchar](20) NULL,
            [HrsWork] [nvarchar](25) NULL default(''00:00''),
            [HrsOT] [nvarchar](25) NULL default(''00:00''),
            [NormOT] [nvarchar](25) NULL default(''00:00''),
            [OffOT] [nvarchar](25) NULL default(''00:00''),
            [HolOT] [nvarchar](25) NULL default(''00:00''),
            [OtMins] int default(0),
            [EarlyOut] [nvarchar](25)  default(''00:00''),
            [LateIn] [nvarchar](25)  default(''00:00''),
            [WorkHrs] [nvarchar](25)  default(''00:00''),
            [HrsLess] [nvarchar](25)  default(''00:00''),
            [HrsExtra] [nvarchar](25)  default(''00:00''),
            [LeaveDays] [numeric](18, 1) default(0.0),
            [AbsentDays] [numeric](18, 1) default(0.0),
            [PresentDays] [numeric](18, 1) default(0.0),
            [Holidays] [numeric](18, 1) default(0.0),
            [LOPDays] [numeric](18, 1) default(0.0),
            [Emp_Id] [int] NULL,
            [TimeStamp] [datetime] NULL
            ,TotalPermissionHours nvarchar(25)null default(''00:00'')
            ,WeekOffDays [numeric](18, 1) default(0.0),
            SPEC_NormOT1 nvarchar(10)default(''00:00''),
            SPEC_NormOT2 nvarchar(10)default(''00:00''),
            SPEC_OffOT1	nvarchar(10)default(''00:00''),
            SPEC_OffOT2	nvarchar(10)default(''00:00''),
            SPEC_HOLOT1	nvarchar(10)default(''00:00''),
            SPEC_HOLOT2	nvarchar(10)default(''00:00'')
            )
            insert into #TempPayrollProcessDetails (Employee_Id) select distinct [Employee_Code_Id] as Employee_Id from #TempProcessedData
            update #TempPayrollProcessDetails set [MonthClosure_Id]=@MonthCloseID
            select E.employee_code_id,sum(convert(int,substring(no_of_hours,1,(charindex('':'',no_of_hours)-1))))as PermissionHours,
            sum(convert(int,substring(no_of_hours,charindex('':'',no_of_hours)+1,len(no_of_hours)))) as permissionminutes 
            into #Permission_Details  from ta_tbl_permission P inner join 
            ta_tbl_employee E on E.employee_id=P.employee_id WHERE       (p.Permission_Date >= CONVERT(DATETIME,cast( @fromDat as nvarchar(50)), 102)) 
            AND (p.Permission_Date <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102))
            and P.IsDeleted=0 and P.Permission_Status = ''Approved''
            group by E.employee_code_id
            update #TempPayrollProcessDetails set TotalPermissionHours=
            case when   len(convert(varchar(20),PermissionHours + permissionminutes/60))=1 and len(convert(varchar(20),permissionminutes%60))=1 then             
                        ''0''+convert(varchar(20),PermissionHours + permissionminutes/60)      +'':0''+convert(varchar(20),permissionminutes%60)
            when  len(convert(varchar(20),PermissionHours + permissionminutes/60))=1 and len(convert(varchar(20),permissionminutes%60))!=1 then
                        ''0''+convert(varchar(20),PermissionHours + permissionminutes/60)      +'':''+convert(varchar(20),permissionminutes%60)
            when  len(convert(varchar(20),PermissionHours + permissionminutes/60))!=1 and len(convert(varchar(20),permissionminutes%60))=1 then
                        ''0''+convert(varchar(20),PermissionHours + permissionminutes/60)      +'':''+convert(varchar(20),permissionminutes%60)
            else
                        ''0''+convert(varchar(20),PermissionHours + permissionminutes/60)      +'':''+convert(varchar(20),permissionminutes%60)
            end
            from #TempPayrollProcessDetails PD
            inner join #Permission_Details PerD on PD.Employee_Id=PerD.employee_code_id
            
            update #TempPayrollProcessDetails 
            set NormOT=convert(varchar, cast(T1.OTMins as int) / 60) + '':'' + right(convert(char(3), 100 + cast(cast(T1.OTMins as int) as numeric) % 60), 2)
            from (select sum(OTMins) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus=''Approved'' and NormOT is not null and NormOT<>'''' and NormOT<>''00:00''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id     
            update #TempPayrollProcessDetails set NormOT=isnull(NormOT,''00:00'')
            
            /**********************/
            update TPP set SPEC_NormOT1=TP.SPEC_NormOT1,
            SPEC_NormOT2=TP.SPEC_NormOT2,
            SPEC_HOLOT1=TP.SPEC_HOLOT1,
            SPEC_HOLOT2=TP.SPEC_HOLOT2,
            SPEC_OffOT1=TP.SPEC_OffOT1,
            SPEC_OffOT2=TP.SPEC_OffOT2
            from #TempPayrollProcessDetails TPP inner join #TempProcessedData TP
            on TPP.Employee_Id=TP.Employee_Code_Id     
            
            update #TempPayrollProcessDetails 
            set OffOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then ''0''+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+'':''+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.OTMins%60))=1 then ''0''+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus=''Approved'' and OffOT is not null and OffOT<>'''' and OffOT<>''00:00''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id  
            
            
            update #TempPayrollProcessDetails 
            set OffOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then ''0''+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+'':''+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.OTMins%60))=1 then ''0''+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus=''Approved'' and OffOT is not null and OffOT<>'''' and OffOT<>''00:00''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id  
            
               
            update #TempPayrollProcessDetails set OffOT=isnull(OffOT,''00:00'')
            update #TempPayrollProcessDetails 
            set HolOT=case when len(convert(varchar(20),T1.OTMins/60))=1 then ''0''+convert(varchar(20),T1.OTMins/60)
       else convert(varchar(20),T1.OTMins/60)end+'':''+
       case when convert(varchar(20),T1.OTMins%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.OTMins%60))=1 then ''0''+convert(varchar(20),T1.OTMins%60)
       else convert(varchar(20),T1.OTMins%60)end end
            from (select CONVERT(int,sum(OTMins)) as OTMins,Employee_Code_Id from #TempProcessedData  where OvertimeStatus=''Approved'' and HolOT is not null and HolOT<>''''  and HolOT<>''00:00''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id     
            update #TempPayrollProcessDetails set HolOT=isnull(HolOT,''00:00'') 
            update #TempPayrollProcessDetails 
            set HrsWork=case when len(convert(varchar(20),T1.HrsWork/60))=1 then ''0''+convert(varchar(20),T1.HrsWork/60)
       else convert(varchar(20),T1.HrsWork/60)end+'':''+
       case when convert(varchar(20),T1.HrsWork%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.HrsWork%60))=1 then ''0''+convert(varchar(20),T1.HrsWork%60)
       else convert(varchar(20),T1.HrsWork%60)end end
            from (
            select employee_code_id , CONVERT(int,SUM(HoursWorkInMins)) as HrsWork
            from #TempProcessedData group by employee_code_id ) as T1 
            inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id           
            --select * from #TempProcessedData
            update #TempPayrollProcessDetails 
            set WorkHrs=case when (charindex('':'',T1.WorkHrs)=2 and charindex('':'',reverse(T1.WorkHrs))=2) then ''0''+T1.WorkHrs + ''0''  
            when charindex('':'',reverse(T1.WorkHrs))=2 then T1.WorkHrs +''0''
            when charindex('':'',T1.WorkHrs)=2 then ''0''+T1.WorkHrs
            when T1.WorkHrs is null then ''00:00''
            else T1.WorkHrs end
            from (select cast(cast((sum(DATEPART(hour,WorkHrs)) * 60 + (sum(DATEPART(minute,WorkHrs)))) / 60  as int) as varchar(50)) + '':'' + cast(sum(DATEPART(minute,WorkHrs)) % 60 as varchar(2)) as WorkHrs,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set EarlyOut=case when len(convert(varchar(20),T1.EarlyOut/60))=1 then ''0''+convert(varchar(20),T1.EarlyOut/60)
       else convert(varchar(20),T1.EarlyOut/60)end+'':''+
       case when convert(varchar(20),T1.EarlyOut%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.EarlyOut%60))=1 then ''0''+convert(varchar(20),T1.EarlyOut%60)
       else convert(varchar(20),T1.EarlyOut%60)end end
            from (select CONVERT(int,sum(EarlyOutMins)) as EarlyOut,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set LateIn=case when len(convert(varchar(20),T1.LateIn/60))=1 then ''0''+convert(varchar(20),T1.LateIn/60)
       else convert(varchar(20),T1.LateIn/60)end+'':''+
       case when convert(varchar(20),T1.LateIn%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.LateIn%60))=1 then ''0''+convert(varchar(20),T1.LateIn%60)
       else convert(varchar(20),T1.LateIn%60)end end
            from (select CONVERT(int,SUM(LateInMins)) as LateIn,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Added where condition by Manjula.P on 07-Oct-2013 to avoiding Date out of range error Mantis : 0019299  
            update #TempPayrollProcessDetails 
            set HrsLess=case when len(convert(varchar(20),T1.HrsLess/60))=1 then ''0''+convert(varchar(20),T1.HrsLess/60)
       else convert(varchar(20),T1.HrsLess/60)end+'':''+
       case when convert(varchar(20),T1.HrsLess%60)=0 then
       ''00'' else case when len(convert(varchar(20),T1.HrsLess%60))=1 then ''0''+convert(varchar(20),T1.HrsLess%60)
       else convert(varchar(20),T1.HrsLess%60)end end
            from (select CONVERT(int,SUM(LessHoursInMins)) as HrsLess,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set HrsExtra=convert(char(5), dateadd(MINUTE, T1.HrsExtra, ''''), 114)                
            from (select sum(ExtraMins) as HrsExtra,Employee_Code_Id from #TempProcessedData
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Leave Days update
            update #TempPayrollProcessDetails 
            set Leavedays=isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode in (Select LeaveType from Ta_Tbl_LeaveType where IsDeleted=0)
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Secod Half Leave Days update
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode in (Select LeaveType from Ta_Tbl_LeaveType where IsDeleted=0)
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode in (''RH'')
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Leavedays=#TempPayrollProcessDetails.Leavedays + isnull(T1.Leavedays,0.0) *0.5
            from (select count(*) as Leavedays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode in (''RH'')
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Present Days update
            update #TempPayrollProcessDetails 
            set Presentdays=isnull(T1.Presentdays,0.0) *0.5
            from (select count(*) as Presentdays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode=''Present'' or FNAttendanceCode=''Comp Off''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Present Days update
            update #TempPayrollProcessDetails 
            set Presentdays=#TempPayrollProcessDetails.Presentdays + isnull(T1.Presentdays,0.0) *0.5
            from (select count(*) as Presentdays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode=''Present''  or ANAttendanceCode=''Comp Off''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Absent Days update
            update #TempPayrollProcessDetails 
            set Absentdays=isnull(T1.Absentdays,0.0) *0.5
            from (select count(*) as Absentdays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode=''Absent''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Absent Days update
            update #TempPayrollProcessDetails 
            set Absentdays=#TempPayrollProcessDetails.Absentdays + isnull(T1.Absentdays,0.0) *0.5
            from (select count(*) as Absentdays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode=''Absent''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half Holiday/Weekly Off Days update
            update #TempPayrollProcessDetails 
            set WeekOffDays=isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode=''Weekly Off''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails        
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Holidays=isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode=''Holiday''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half Holiday/Weekly  Days update
            update #TempPayrollProcessDetails 
            set WeekOffDays=#TempPayrollProcessDetails.WeekOffDays + isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode=''Weekly Off''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails 
            set Holidays=#TempPayrollProcessDetails.Holidays + isnull(T1.Holidays,0.0) *0.5
            from (select count(*) as Holidays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode=''Holiday''
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --First Half LOP Days update
            update #TempPayrollProcessDetails 
            set LOPDays=isnull(T1.LOPDays,0.0) *0.5
            from (select count(*) as LOPDays,Employee_Code_Id from #TempProcessedData
            where FNAttendanceCode=''LOP'' 
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            --Second Half LOP Days update
            update #TempPayrollProcessDetails 
            set LOPDays=#TempPayrollProcessDetails.LOPDays + isnull(T1.LOPDays,0.0) *0.5
            from (select count(*) as LOPDays,Employee_Code_Id from #TempProcessedData
            where ANAttendanceCode=''LOP'' 
            Group by Employee_Code_Id) as T1 inner join #TempPayrollProcessDetails
            on #TempPayrollProcessDetails.Employee_Id=T1.Employee_Code_Id
            update #TempPayrollProcessDetails set Emp_Id=@AuditEmpId
            update #TempPayrollProcessDetails set [TimeStamp]=getdate()       
            if(@ProcessType=''Process'')
            BEGIN
                  if(@ProcessCount=0)
                  BEGIN
                              insert into  TA_Tbl_PayrollProcessDetails (MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                              LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2)
                              select MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                              LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2 from #TempPayrollProcessDetails
                  END
                  else
                  BEGIN
                              update TA_Tbl_PayrollProcessDetails set HrsWork=T1.HrsWork, HrsOT=T1.HrsOT, NormOT=T1.NormOT, OffOT=T1.OffOT, HolOT=T1.HolOT, EarlyOut=T1.EarlyOut, LateIn=T1.LateIn, WorkHrs=T1.WorkHrs, HrsLess=T1.HrsLess, HrsExtra=T1.HrsExtra, 
                              LeaveDays=T1.LeaveDays, AbsentDays=T1.AbsentDays, PresentDays=T1.PresentDays, Holidays=T1.Holidays, LOPDays=T1.LOPDays,TotalPermissionHours=T1.TotalPermissionHours
                              ,WeekOffDays=T1.WeekOffDays
                              ,SPEC_NormOT1=T1.SPEC_NormOT1,SPEC_NormOT2=T1.SPEC_NormOT2,SPEC_OffOT1=T1.SPEC_OffOT1,SPEC_OffOT2=T1.SPEC_OffOT2,
                              SPEC_HOLOT1=T1.SPEC_HOLOT1,SPEC_HOLOT2=T1.SPEC_HOLOT2
                              from #TempPayrollProcessDetails T1 inner join TA_Tbl_PayrollProcessDetails T2
                              on T1.MonthClosure_Id=T2.MonthClosure_Id and T1.Employee_Id=T2.Employee_Id
                  END               
      END
      else if (@ProcessType=''Preview'')
      BEGIN
                  delete from TA_Tbl_TempPayrollProcessDetails where MonthClosure_Id=@MonthCloseID
                  insert into  TA_Tbl_TempPayrollProcessDetails (MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                  LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2)
                  select MonthClosure_Id, Employee_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
                  LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1,SPEC_NormOT2,SPEC_OffOT1,SPEC_OffOT2,SPEC_HOLOT1,SPEC_HOLOT2
                  from #TempPayrollProcessDetails
      END
            select MonthClosure_Id, Employee_Id as Employee_Code_Id, HrsWork, HrsOT, NormOT, OffOT, HolOT, EarlyOut, LateIn, WorkHrs, HrsLess, HrsExtra, 
            LeaveDays, AbsentDays, PresentDays, Holidays, LOPDays, Emp_Id, [TimeStamp],TotalPermissionHours,WeekOffDays,SPEC_NormOT1=isnull(SPEC_NormOT1,''00:00''),SPEC_NormOT2=isnull(SPEC_NormOT2,''00:00''),SPEC_OffOT1=isnull(SPEC_OffOT1,''00:00''),SPEC_OffOT2=isnull(SPEC_OffOT2,''00:00''),SPEC_HOLOT1=isnull(SPEC_HOLOT1,''00:00''),SPEC_HOLOT2=isnull(SPEC_HOLOT2,''00:00'') from #TempPayrollProcessDetails
            --Remove the temporary tables here  
            drop table #TempPayrollProcessDetails
      end
      COMMIT
END TRY
BEGIN CATCH
      -- Whoops, there was an error
      IF @@TRANCOUNT > 0
      ROLLBACK
      -- Raise an error with the details of the exception
      DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
      SELECT @ErrMsg = ERROR_MESSAGE(),
      @ErrSeverity = ERROR_SEVERITY()
      RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
      --Remove the temporary tables here  
      drop table #EmpLevel
      drop table #LevelRights
      drop table #TempProcessedData
' 
END
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference_Test]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunchDifference_Test]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_FirstInPunchDifference_Test]
AS
	SELECT SIP.EmployeeCodeId, SIP.[Date], ST.Terminal_Description EntranceName, SIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), SIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName, 
        FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) PunchDifference,
		ISNULL(DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM dbo.TA_VW_ShiftInPunches SIP
		LEFT OUTER JOIN dbo.TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = SIP.EmployeeCodeId AND FIP.[Date] = SIP.[Date] AND FIP.FirstInPunch = ''Shift FIn''
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal ST ON ST.Terminal_ReaderID = SIP.DeviceId
	WHERE (ISNULL(SIP.EmployeeCodeId, N'''') <> '''') --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
	UNION ALL
	SELECT LIP.EmployeeCodeId, LIP.[Date], LT.Terminal_Description [EntranceName], LIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), LIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) [PunchDifference],
		ISNULL(DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_LunchInPunches LIP
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = LIP.EmployeeCodeId AND FIP.[Date] = LIP.[Date] AND FIP.FirstInPunch = ''Lunch FIn''
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal LT ON LT.Terminal_ReaderID = LIP.DeviceId
	WHERE ISNULL(LIP.EmployeeCodeId, '''') <> '''' --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
	UNION ALL
	SELECT DISTINCT BIP.EmployeeCodeId, BIP.[Date], BT.Terminal_Description [EntranceName], BIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), BIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) [PunchDifference],
		ISNULL(DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_BreakInPunches_Test  BIP 
		LEFT OUTER JOIN TA_VW_FirstInPunches_Test FIP ON FIP.EmployeeCodeId = BIP.EmployeeCodeId AND FIP.[Date] = BIP.[Date] AND FIP.FirstInPunch = ''Break FIn'' AND FIP.Id = BIP.Id
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal BT ON BT.Terminal_ReaderID = BIP.DeviceId
	WHERE ISNULL(BIP.EmployeeCodeId, '''') <> '''' --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
'
GO
/****** Object:  View [dbo].[TA_VW_FirstInPunchDifference]    Script Date: 03/25/2021 10:22:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[TA_VW_FirstInPunchDifference]'))
EXEC dbo.sp_executesql @statement = N'
CREATE VIEW [dbo].[TA_VW_FirstInPunchDifference]
AS
	SELECT SIP.EmployeeCodeId, SIP.[Date], ST.Terminal_Description EntranceName, SIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), SIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName, 
        FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) PunchDifference,
		ISNULL(DATEDIFF(MI, SIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM dbo.TA_VW_ShiftInPunches SIP
		LEFT OUTER JOIN dbo.TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = SIP.EmployeeCodeId AND FIP.[Date] = SIP.[Date] AND FIP.FirstInPunch = ''Shift FIn''
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN dbo.TA_Tbl_Terminal ST ON ST.Terminal_ReaderID = SIP.DeviceId
	WHERE (ISNULL(SIP.EmployeeCodeId, N'''') <> '''') --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
	UNION ALL
	SELECT LIP.EmployeeCodeId, LIP.[Date], LT.Terminal_Description [EntranceName], LIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), LIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) [PunchDifference],
		ISNULL(DATEDIFF(MI, LIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_LunchInPunches LIP
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = LIP.EmployeeCodeId AND FIP.[Date] = LIP.[Date] AND FIP.FirstInPunch = ''Lunch FIn''
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal LT ON LT.Terminal_ReaderID = LIP.DeviceId
	WHERE ISNULL(LIP.EmployeeCodeId, '''') <> '''' --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
	UNION ALL
	SELECT BIP.EmployeeCodeId, BIP.[Date], BT.Terminal_Description [EntranceName], BIP.PunchType EntranceType,
		REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), BIP.[DateTime], 109), 15)), '':000'', '' '') EntranceTime, FT.Terminal_Description FloorName,
		FIP.PunchType FloorType, REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(26), FIP.[DateTime], 109), 15)), '':000'', '' '') FloorTime,
		CONVERT(VARCHAR(5), ISNULL(CAST(DATEADD(MI, DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), ''00:00'') AS TIME), ''23:59'')) [PunchDifference],
		ISNULL(DATEDIFF(MI, BIP.[DateTime], FIP.[DateTime]), 0) PunchDifferenceMins
	FROM TA_VW_BreakInPunches BIP 
		LEFT OUTER JOIN TA_VW_FirstInPunches FIP ON FIP.EmployeeCodeId = BIP.EmployeeCodeId AND FIP.[Date] = BIP.[Date] AND FIP.FirstInPunch = ''Break FIn''
		LEFT OUTER JOIN TA_Tbl_Terminal FT ON FT.Terminal_ReaderID = FIP.DeviceId
		LEFT OUTER JOIN TA_Tbl_Terminal BT ON BT.Terminal_ReaderID = BIP.DeviceId
	WHERE ISNULL(BIP.EmployeeCodeId, '''') <> '''' --AND (ISNULL(FT.Terminal_Description, '''') <> '''')
'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPane1' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_FirstInPunchDifference', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "SIP"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 125
               Right = 208
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "FIP"
            Begin Extent = 
               Top = 6
               Left = 246
               Bottom = 125
               Right = 416
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "FT"
            Begin Extent = 
               Top = 6
               Left = 454
               Bottom = 125
               Right = 645
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "ST"
            Begin Extent = 
               Top = 6
               Left = 683
               Bottom = 125
               Right = 874
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunchDifference'
GO
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'MS_DiagramPaneCount' , N'SCHEMA',N'dbo', N'VIEW',N'TA_VW_FirstInPunchDifference', NULL,NULL))
EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'VIEW',@level1name=N'TA_VW_FirstInPunchDifference'
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_DeletePayrollLeaveDetails]    Script Date: 03/25/2021 10:22:04 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_DeletePayrollLeaveDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_DeletePayrollLeaveDetails]
(
   @MonthClosureId INT
)
AS
begin
SET NOCOUNT ON;
DELETE FROM TA_Tbl_PayrollProcessLeaveDetails WHERE MonthClosure_Id = @MonthClosureId
end
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_CheckCCGroupExists]    Script Date: 03/25/2021 10:22:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_CheckCCGroupExists]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 11-Oct-2010
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_CheckCCGroupExists] 
	@LevelId int,
	@DesignationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
   select count(*) from TA_Tbl_CCMailGroup where LevelID=@LevelId and DesignationID=@DesignationId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetPayrollDetails]    Script Date: 03/25/2021 10:22:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetPayrollDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetPayrollDetails]
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	select ppd.Employee_Id,ppd.HrsWork,ppd.HrsOT,ppd.NormOT,ppd.OffOT,ppd.HolOT,ppd.EarlyOut,ppd.LateIn,ppd.WorkHrs,ppd.HrsLess,ppd.HrsExtra from ta_tbl_payrollprocessdetails ppd,ta_tbl_monthClosure mc where ppd.MonthClosure_Id = mc.MonthClosure_Id
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Update_PayrollProcessDetails]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Update_PayrollProcessDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Update_PayrollProcessDetails]
(
   @HrsWork NVARCHAR(20),
   @HrsOT NVARCHAR(20),
   @NormOT NVARCHAR(20),
   @OffOT NVARCHAR(20),
   @HolOT NVARCHAR(20),
   @EarlyOut NVARCHAR(20),
   @LateIn NVARCHAR(20),
   @WorkHrs NVARCHAR(20),
   @HrsLess NVARCHAR(20),
   @HrsExtra NVARCHAR(20),
   @LeaveDays numeric(18,1),
   @AbsentDays numeric(18,1),
   @PresentDays numeric(18,1),
   @Holidays numeric(18,1),
   @LOPDays numeric(18,1),
   @UserId INt,
   @ProcessDateTime NVARCHAR(20),
   @MonthClosure_Id INT,
   @EmpId NVARCHAR(20)
)
AS
BEGIN
           UPDATE TA_Tbl_PayrollProcessDetails SET HrsWork = @HrsWork,HrsOT = @HrsOT,NormOT = @NormOT,OffOT = @OffOT,HolOT = @HolOT,EarlyOut = @EarlyOut,LateIn = @LateIn,WorkHrs = @WorkHrs,
           HrsLess = @HrsLess,HrsExtra = @HrsExtra,LeaveDays = @LeaveDays,AbsentDays = @AbsentDays,PresentDays = @PresentDays,Holidays = @Holidays,LOPDays=@LOPDays,[Emp_Id] = @UserId,[TimeStamp] = @ProcessDateTime 
           WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_Ta_ToGetLunchHours]    Script Date: 03/25/2021 10:22:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_Ta_ToGetLunchHours]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- ==========================================================================================
-- Author: R.Manikandan
-- Create date: 10-01-2014
-- Description: This is for Non flexi employees alone.
-- 1. To deduct the lunch hrs based on the punches. if the punches are not availed in device
-- means, that time the procedure will consider the shift break timings.
-- 2. if only one punches are avalied in device means, that time also it will consider the
-- shift break time
-- [dbo].[Proc_Ta_ToGetLunchHours] ''2002'',''08/04/2019'',-1,7,0
-- ==========================================================================================
CREATE PROCEDURE [dbo].[Proc_Ta_ToGetLunchHours]
-- Add the parameters for the stored procedure here
@EmployeeCodeId varchar(50),
@Clockdate varchar(30),
@ShiftId int,
@levelid int,
@addWeekOff int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	-- Insert statements for procedure here
	Declare @MaxluncHours datetime
	Declare @MinluncHours datetime
	Declare @Difference datetime
	Declare @Differences varchar(20)
	Declare @ClosingTime datetime
	Declare @Shift_BreakStartTime1 datetime
	Declare @Shift_BreakEndTime1 datetime
	Declare @count int
	declare @weekNumber int
	Declare @employeeId int
	declare @FirstSession varchar(20)
	declare @SecondSession varchar(20)
	--Added by Manjula.P on 02-Apr-2014 for holiday and weekly off lunch hours deduction
	declare @HolidayCount int;
	DECLARE @ParentLevelId int
	declare @ParentId int
	declare @IsLunchDeduction bit
	declare @LunchDeductionHours nvarchar(10)
	set @ParentId=@levelid;
	set @ParentLevelId=@levelid;
	--For Getting parent Levelid to taking values from shift settings table
	while(@ParentId!=0)
		begin
		set @ParentLevelId=(SELECT id FROM Ta_Tbl_levelDetails WHERE ID=@ParentId)
		set @ParentId=(SELECT parentId FROM Ta_Tbl_levelDetails WHERE ID=@ParentId)
	end
	set @IsLunchDeduction=(select isnull(IsLunchDeduction,0) from TA_Tbl_ShiftSettings where CompanyId=@ParentLevelId)
	set @LunchDeductionHours=(select isnull(LunchDeductionHours,''00:00'') from TA_Tbl_ShiftSettings where CompanyId=@ParentLevelId)
	set @weekNumber =DATEPART(WK,@Clockdate)
	set @count=0
	set @Difference=''00:00'' 
	set @ClosingTime=''''
	set @employeeId=(select Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeId and Isdeleted=0)
	--select @count=COUNT(*) from TA_Tbl_LeaveApplicationExists where Employee_Id =@employeeId And IsDeleted=0
	-- And(Leave_FromDate=@Clockdate) and Status<>''Rejected''
	select @count=COUNT(*) from TA_Tbl_LeaveApplication LA inner join TA_Tbl_LeaveApplicationExists
	LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId where la.Employee_Id =@employeeId And la.IsDeleted=0
	And(lae.Leave_FromDate=@Clockdate) and la.Status<>''Rejected''
	Select @MaxluncHours= isnull(MAX(Clk_InTime),''9999-12-31 00:00:00.000'')
	from ta_tbl_clockdetails where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and Clk_InPunchType=''Lunch In''
	AND IsVoid = 0	
	Select @MinluncHours=isnull(Min(Clk_OutTime),''9999-12-31 00:00:00.000'')
	from ta_tbl_clockdetails where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and Clk_OutPunchType=''Lunch Out''
	AND IsVoid = 0
	--Added by Manjula.P on 02-Apr-2014 for lunch deduction on holdiay and weekly off	
	create table #tempHolidayCount(HolidayCount int,holidaydescription varchar(max))
	insert into #tempHolidayCount
	execute Proc_TA_CheckHolidayBasedOnLevel @Clockdate,@Clockdate,''G'',@employeeId
	set @HolidayCount= (select count(*) from #tempHolidayCount where HolidayCount!=0)
	declare @ShiftLunchStart datetime
	declare @ShiftLunchEnd datetime
	declare @ActualShiftIn datetime
	declare @ActualShiftOut datetime
	declare @ShiftStartDate datetime
	declare @ShiftEndDate datetime
	set @ActualShiftIn=(select isnull(min(Clk_InTime),''9999-12-30 00:00:00.000'')from ta_tbl_clockdetails 
	where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and (lower(Clk_InPunchType)=''shift in'' or lower(Clk_InPunchType)=''in'')	)
	set @ActualShiftOut=(select isnull(MAX(Clk_OutTime),''9999-12-30 00:00:00.000'')from ta_tbl_clockdetails 
	where clk_empid=@EmployeeCodeId and clk_date=@Clockdate and (lower(Clk_OutPunchType)=''shift out'' or lower(Clk_OutPunchType)=''out''))
	set @ShiftStartDate=(select isnull(cast(Shift_StartTime as datetime),''9999-12-31 00:00:00.000'') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftEndDate=(select isnull(cast(Shift_EndTime as datetime),''9999-12-31 00:00:00.000'') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftLunchStart=(select isnull(CAST(Shift_BreakStartTime2 as datetime),''9999-12-31 00:00:00.000'') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	set @ShiftLunchEnd=(select  isnull(cast(Shift_BreakEndTime2 as datetime),''9999-12-31 00:00:00.000'') from TA_Tbl_Shift where Shift_Id=@ShiftId)
	--Chekcing with night shift Generally PM and AM means that shift is night shift 
	--0 to 11 - AM in 12 hours format and 12 to 23 -PM in 12 hours format	
	if( (datepart(HOUR,@ShiftStartDate) between 12 and 23) and datepart(hour,@ShiftEndDate) between 0 and 11 )
	begin
		--Checking lunch start hours
		if(datepart(HOUR,@ShiftLunchStart) between 0 and 11)
		begin
			set @ShiftLunchStart=DATEADD(day,1,@ShiftLunchStart);
		end
		--Checking lunch end hours
		if(datepart(HOUR,@ShiftLunchEnd) between 0 and 11)
		begin
			set @ShiftLunchEnd=DATEADD(day,1,@ShiftLunchEnd);
		end
		--Checking actual shift start date
		if(datepart(HOUR,@ActualShiftIn) between 0 and 11)
		begin
			set @ActualShiftIn=DATEADD(day,1,@ActualShiftIn);
		end
		--Checking actual shift end date
		if(datepart(HOUR,@ActualShiftOut) between 0 and 11)
		begin
			set @ActualShiftOut=DATEADD(day,1,@ActualShiftOut);
		end
	end	
	--Adding this condition (@MaxluncHours<>''9999-12-31 00:00:00.000'' ) and( @MinluncHours<>''9999-12-31 00:00:00.000'') for taking lunch deduction hours 
	-- if the time value is exact 12:00 am i.e 9999-12-31 00:00:00.000
	--if((@MaxluncHours<>'''' ) and( @MinluncHours<>''''))
	if((@MaxluncHours<>''9999-12-31 00:00:00.000'' ) and( @MinluncHours<>''9999-12-31 00:00:00.000''))
		begin 			
			set @Difference=@MaxluncHours-@MinluncHours 
		end
	else
		begin		
			if(@ShiftId!=-1 and @HolidayCount<=0 and @addWeekOff<=0)
				begin					
					set @count=@count+@HolidayCount
					if(@addWeekOff>0)
						begin
							set @count=@count+@addWeekOff
						end
						--@count=0 means there is no weekly off, holiday leave on that clockdate
					if(@count=0)
						begin
							select @ClosingTime=TW.ClosingTime from TA_Tbl_TemWeekday TW inner join Ta_Tbl_Temporary_WeeklyOff_Levels TWL on TW.TempWeekday_Id=TWL.TempWeekday_Id 
							where TWL.LevelId=@levelid and TW.IsDeleted=0 and TW.TempWeekday_FromDate=@Clockdate  
							if(@ClosingTime='''')
								begin
									set @Difference=(select CONVERT(datetime,Shift_BreakEndTime2)-CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId)
								end
							else
								begin
									select @Shift_BreakEndTime1=CONVERT(datetime,Shift_BreakEndTime2),@Shift_BreakStartTime1=CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId
									if (@ClosingTime >@Shift_BreakEndTime1 or @ClosingTime<@Shift_BreakStartTime1)
										begin
											set @Difference=(select CONVERT(datetime,Shift_BreakEndTime2)-CONVERT(datetime,Shift_BreakStartTime2) from TA_Tbl_Shift where Shift_Id=@ShiftId)
										end
									else if (@ClosingTime >@Shift_BreakStartTime1 and @ClosingTime<@Shift_BreakEndTime1)
										begin
											set @Difference=CONVERT(datetime,@ClosingTime)-CONVERT(datetime,@Shift_BreakStartTime1)
										end
								end
						end					
				end
			--This else part for deducting lunch hours on weekly off and holiday and Additional Weekly off : From shift Settings 
			else 
				begin					
					set @Difference=''00:00''
					--if the lunch deduction is yes from shift settings for the particular levelid
					if(@IsLunchDeduction=1)
						begin
							--checking one punch type is missning : Means either lunch in or lunch out is missing : then take lunch deduction hours 
							if((@MaxluncHours<>''9999-12-31 00:00:00.000'' ) or ( @MinluncHours<>''9999-12-31 00:00:00.000''))
								begin									
									if(@ShiftId=-1 or @HolidayCount>0 or @addWeekOff>0)
									begin
										set @Difference=@LunchDeductionHours;
									end
								end
							else
								if(@ShiftId=-1 or @HolidayCount>0 or @addWeekOff>0)
									begin
										set @Difference=@LunchDeductionHours;
									end								
						end
					--If lunch dedcution is no then no difference
					else
						begin							
							set @Difference=''00:00'';
						end
				end		
	end	
	set @Differences=CONVERT(VARCHAR(5),isnull(@Difference,''00:00''),108)
	select substring(@Differences,0,CHARINDEX('':'',@differences))*60+substring(@Differences,CHARINDEX('':'',@differences)+1,LEN(@differences)) 
END

' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_SelectCCGroups]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_SelectCCGroups]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma
-- Create date: 11-Oct-2010
-- Description:	Gets the Cc groups.
-- =============================================
--Proc_TA_SelectCCGroups 1,''a''
CREATE PROCEDURE [dbo].[Proc_TA_SelectCCGroups]
@SearchOption varchar(50),
@SearchText varchar(50)
AS
BEGIN
if(@SearchOption=1 and @SearchText<>'''')
BEGIN
    select C.CCGroupId,L.name +'' - ''+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where L.name like ''%''+ @SearchText +''%''
END
else if(@SearchOption=2 and @SearchText<>'''')
BEGIN
    select C.CCGroupId,L.name +'' - ''+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where T.TitleName like ''%'' + @SearchText +''%''
END
else if(@SearchText<>'''')
BEGIN
    select C.CCGroupId,L.name +'' - ''+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
	where T.TitleName like ''%'' + @SearchText +''%'' or L.name like ''%''+ @SearchText +''%''
	or L.name +'' - ''+ T.TitleName like ''%''+ @SearchText +''%''
END
else
BEGIN
	select C.CCGroupId,L.name +'' - ''+ T.TitleName as CCGroup from TA_tbl_CcMailGroup C 
	inner join TA_Tbl_LevelDetails L on L.Id=C.LevelID
	inner join TA_Tbl_Title T on T.TitleId=C.DesignationID
END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		<Velumani P>
-- Create date: <16/07/2019>
-- Description:	<The attendance will be marked as Absent, When employees is Absent on saturday and monday, then sunday will be marked as Absent, instead of Weekoff or Holiday as per shift setting>
-- [Proc_TA_MarkAbsentForWeekoffHoliday] ''2020/08/11 00:00:00:000'', ''5'',1
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_MarkAbsentForWeekoffHoliday]
	-- Add the parameters for the stored procedure here
	@Date datetime, @EmployeeCodeId varchar(40),@CompanyId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	--Vaiable declaration
	DECLARE @EnableAbsent int
	Declare @IsHoliday int
	Declare @IsWeekOff int
	Declare @PrevDay Datetime
	Declare @NextDay Datetime
	set @IsHoliday = 0;
	set @IsWeekOff =0;
	--This Value is updated using organization setting screen , very First condition to proceed
	SELECT @EnableAbsent = convert(int,EnableAbsent) from TA_Tbl_ShiftSettings where CompanyId = @CompanyId
	IF(isnull(@EnableAbsent,0) = 1)  -- Option Enabled For the company or not
	BEGIN
		if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=@Date and (FNAttendanceCode=''Absent''))
		begin
			if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and ((FNAttendanceCode=''Weekly off'' and ANAttendanceCode=''Weekly off'') or (ANAttendanceCode=''Holiday'')))
			begin
				if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-2,@Date) and (ANAttendanceCode=''Absent''))
				begin
					update TA_Tbl_ProcessedData set FNAttendanceCode=''Absent'',ANAttendanceCode=''Absent'',Attendance=''Absent'' where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date)
				end				
			end	
		end
		else
		begin
			if exists(select Employee_Code_Id from TA_Tbl_ProcessedData where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and Shift_Id=-1 and FNAttendanceCode=''Absent'' and FNAttendanceCode=''Absent'')
			begin
				update TA_Tbl_ProcessedData set FNAttendanceCode=''Weekly Off'',ANAttendanceCode=''Weekly off'',Attendance=''Weekly off'' where Employee_Code_Id=@EmployeeCodeId and date=dateadd(d,-1,@Date) and Shift_Id=-1 and FNAttendanceCode=''Absent'' and FNAttendanceCode=''Absent''
			end
			else
			begin
				declare @EmpAUTOID int
				select @EmpAUTOID= Employee_Id from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeId and Isdeleted=0;
				Declare @prevDate datetime
				set @prevDate=dateadd(d,-1,@Date)
				
				declare @EventId int
				CREATE TABLE #EventId (EventId int, Descr varchar(500) )
				insert into #EventId execute [Proc_TA_CheckHolidayForService] @HOLIDAYTYPE =''G'',@EMPLOYEEAUTOID = @EmpAUTOID,@FROMDATE = @PrevDate
				select @EventId = EventId from #EventId
				if(@EventId!=0)
				begin
					update TA_Tbl_ProcessedData set FNAttendanceCode=''Holiday'',ANAttendanceCode=''Holiday'',Attendance=''Holiday'' where Employee_Code_Id=@EmployeeCodeId and date=@PrevDate and FNAttendanceCode=''Absent'' and FNAttendanceCode=''Absent''
				end
				drop table #EventId 
			end
		end
	END
	--SAPCO requirement. IF Its affect anything for any other client, comment the below whole codings.
	--Implemented by manikandan.rr on 18-Dec-2020 10:29 AM
	DECLARE @ShiftID BIGINT
	DECLARE @ShiftShortName varchar(10)
	DECLARE @FNAttendance VARCHAR(50)
	DECLARE @ANAttendance VARCHAR(50)
	SELECT @ShiftID=Shift_Id,@FNAttendance=FNAttendanceCode,@ANAttendance=ANAttendanceCode FROM TA_Tbl_ProcessedData WHERE Employee_Code_Id=@EmployeeCodeId and date=@Date
	SELECT @ShiftShortName=Shift_ShortName FROM TA_Tbl_Shift WHERE Shift_Id=@ShiftID
	IF(@FNAttendance IN(''PRESENT'',''ABSENT'') or @ANAttendance IN(''PRESENT'',''ABSENT''))
	BEGIN
		IF(@ShiftShortName=''PLO'' OR @ShiftShortName=''PHO'')
		BEGIN
			UPDATE TA_Tbl_ProcessedData SET 
			FNAttendanceCode=CASE WHEN @ShiftShortName=''PLO'' and @FNAttendance IN(''PRESENT'',''ABSENT'') THEN ''PLOff''
								  WHEN @ShiftShortName=''PHO'' and @FNAttendance IN(''PRESENT'',''ABSENT'') THEN ''PHOff''
								  else FNAttendanceCode
							 END,
			ANAttendanceCode=CASE WHEN @ShiftShortName=''PLO'' and @ANAttendance IN(''PRESENT'',''ABSENT'') THEN ''PLOff''
								  WHEN @ShiftShortName=''PHO'' and @ANAttendance IN(''PRESENT'',''ABSENT'') THEN ''PHOff''
								  else ANAttendanceCode
							 END
			WHERE Employee_Code_Id=@EmployeeCodeId and date=@Date
		END
	END
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_LeaveBalanceImport]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_LeaveBalanceImport]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*
Execute [Proc_TA_LeaveBalanceImport]
''<dsLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>659</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1>15.5</LeaveType1>
  </TblLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>956</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1 />
    <LeaveType2>16.5</LeaveType2>
  </TblLeaveBalance>
  <TblLeaveBalance>
    <Sl.No />
    <EmployeeID>787</EmployeeID>
    <Employee_x0020_Name />
    <LeaveType1 />
    <LeaveType2 />
    <LeaveType3>18.5</LeaveType3>
  </TblLeaveBalance>
</dsLeaveBalance>''

*/
CREATE PROCEDURE [dbo].[Proc_TA_LeaveBalanceImport]
	@LeaveBalanceData XML = NULL
AS
BEGIN
	set nocount on
	DECLARE @XMLParams INT, @YearSettingId INT, @NosId INT
	DECLARE @ErrMsg VARCHAR(MAX), @ErrIds VARCHAR(MAX)
	DECLARE @StartDate DATETIME
	DECLARE @ErrorMsg TABLE(Employee_Id VARCHAR(100), [Year] VARCHAR(10), [Month] VARCHAR(20), Error_Msg VARCHAR(MAX))		
	DELETE FROM ImportFromExcel
	EXEC SP_XML_PrePareDocument @XMLParams OUTPUT, @LeaveBalanceData
	INSERT INTO ImportFromExcel	
	SELECT	ROW_NUMBER()over(order by EmployeeID),
			EmployeeID,
			convert(float,isnull(LeaveType1,0.0)),
			convert(float,isnull(LeaveType2,0.0)),
			convert(float,isnull(LeaveType3,0.0)),
			convert(float,isnull(LeaveType4,0.0)),
			convert(float,isnull(LeaveType5,0.0)),
			convert(float,isnull(LeaveType6,0.0)),
			convert(float,isnull(LeaveType7,0.0)),
			convert(float,isnull(LeaveType8,0.0)),
			convert(float,isnull(LeaveType9,0.0)),
			convert(float,isnull(LeaveType10,0.0)),
			convert(float,isnull(LeaveType11,0.0)),
			convert(float,isnull(LeaveType12,0.0)),
			convert(float,isnull(LeaveType13,0.0)),
			convert(float,isnull(LeaveType14,0.0)),
			convert(float,isnull(LeaveType15,0.0))		
	FROM OPENXML (@XMLParams, ''/dsLeaveBalance/TblLeaveBalance'', 2) WITH 
	(		
		[Sl.No]	int,
		EmployeeID	varchar(50),
		LeaveType1	varchar(50),
		LeaveType2	varchar(50),
		LeaveType3	varchar(50),
		LeaveType4	varchar(50),
		LeaveType5	varchar(50),
		LeaveType6	varchar(50),
		LeaveType7	varchar(50),
		LeaveType8	varchar(50),
		LeaveType9	varchar(50),
		LeaveType10 varchar(50),
		LeaveType11 varchar(50),
		LeaveType12 varchar(50),
		LeaveType13 varchar(50),
		LeaveType14 varchar(50),
		LeaveType15 varchar(50)
	) Tbl
	--LEFT OUTER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = Tbl.Employeeid
	--AND E.IsDeleted = 0 AND E.Employee_Status = 1
	Execute Proc_TA_BulkImportPrevLeaveBalance;
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdateDelete_CCGroup]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdateDelete_CCGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 09-Oct-2010
-- Description:	Fetches the Organization,Designation and UserGroup details for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdateDelete_CCGroup] 
(
@LevelId int,
@DesignationId int,
@MailTo_SecondLevel_Planned int,
@MailTo_SecondLevel_UnPlanned int,
@Parameter varchar(2)
)
AS
BEGIN
	SET NOCOUNT ON;
if(@Parameter=''I'')
	BEGIN
	  insert into TA_Tbl_CCMailGroup values (@LevelId,@DesignationId,@MailTo_SecondLevel_Planned,@MailTo_SecondLevel_UnPlanned)
	  select @@Identity as CCMailGroupId
	END
if(@Parameter=''U'')
	BEGIN
	  update TA_Tbl_CCMailGroup set MailTo_SecondLevel_Planned=@MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned=@MailTo_SecondLevel_UnPlanned
	  where LevelId=@LevelId and DesignationId=@DesignationId
	  select 0 as CCMailGroupId
	END   
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]    Script Date: 03/25/2021 10:22:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- Procedure Name : Proc_TA_InsertUpdate_TempPayrollProcessDetails  
-- Purpose        : Used to store the details for payroll in temporary table  
-- Author         : Kumuthini.L  
-- Created Date   : 18-May-09  
CREATE PROCEDURE [dbo].[Proc_TA_InsertUpdate_TempPayrollProcessDetails]  
(  
   @MonthClosure_Id int,  
   @EmpId Varchar(20),  
   @HrsWork Varchar(20),  
   @HrsOT Varchar(20),  
   @NormOT Varchar(20),  
   @OffOT Varchar(20),  
   @HolOT Varchar(20),  
   @EarlyOut Varchar(20),  
   @LateIn Varchar(20),  
   @WorkHrs Varchar(20),  
   @HrsLess Varchar(20),  
   @HrsExtra Varchar(20),  
   @LeaveDays numeric(18,1),  
   @AbsentDays numeric(18,1),  
   @PresentDays numeric(18,1),  
   @Holidays numeric(18,1),  
   @LOPDays numeric(18,1),  
   @UserId numeric(18,1),  
   @ProcessDateTime Varchar(20)  
)  
AS  
BEGIN  
  DECLARE @Count AS INT  
  SET @Count = 0    
  DELETE FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
  -- Fetch the record count by passing the month closure id and employee id  
  --SET @Count = (SELECT COUNT(*) FROM TA_Tbl_TempPayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId)  
  SET @Count =0
  IF(@Count = 0)  
    BEGIN  
       -- If the record count is 0, then INSERT the Details  
       INSERT INTO TA_Tbl_TempPayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut,LateIn,WorkHrs,HrsLess,HrsExtra,LeaveDays,AbsentDays,PresentDays,Holidays,LOPDays,[Emp_Id],[TimeStamp])   
       VALUES (@MonthClosure_Id,@EmpId,@HrsWork,@HrsOT,@NormOT,@OffOT,@HolOT,@EarlyOut,@LateIn,@WorkHrs,@HrsLess,@HrsExtra,@LeaveDays,@AbsentDays,@PresentDays,@Holidays,@LOPDays,@UserId,@ProcessDateTime)  
    END  
--  ELSE  
--    BEGIN  
--  
--        -- If the record count is not 0, then UPDATE the Details  
--       UPDATE TA_Tbl_PayrollProcessDetails SET HrsWork = @HrsWork,HrsOT = @HrsOT,NormOT = @NormOT,OffOT = @OffOT,HolOT = @HolOT,EarlyOut = @EarlyOut,LateIn = @LateIn,WorkHrs = @WorkHrs,  
--       HrsLess = @HrsLess,HrsExtra = @HrsExtra,LeaveDays = @LeaveDays,AbsentDays = @AbsentDays,PresentDays = @PresentDays,Holidays = @Holidays,LOPDays=@LOPDays,[Emp_Id] = @UserId,[TimeStamp] = @ProcessDateTime   
--       WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId  
--  
--    END  
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_Insert_PayrollProcessDetails]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_Insert_PayrollProcessDetails]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[Proc_TA_Insert_PayrollProcessDetails]
(
   @MonthClosure_Id int,
   @EmpId Varchar(20),
   @HrsWork Varchar(20),
   @HrsOT Varchar(20),
   @NormOT Varchar(20),
   @OffOT Varchar(20),
   @HolOT Varchar(20),
   @EarlyOut Varchar(20),
   @LateIn Varchar(20),
   @WorkHrs Varchar(20),
   @HrsLess Varchar(20),
   @HrsExtra Varchar(20),
   @LeaveDays numeric(18,1),
   @AbsentDays numeric(18,1),
   @PresentDays numeric(18,1),
   @Holidays numeric(18,1),
   @LOPDays numeric(18,1),
   @UserId numeric(18,1),
   @ProcessDateTime Varchar(20)
)
AS
BEGIN
           DELETE FROM TA_Tbl_PayrollProcessDetails WHERE MonthClosure_Id = @MonthClosure_Id AND Employee_Id = @EmpId
           INSERT INTO TA_Tbl_PayrollProcessDetails(MonthClosure_Id,Employee_Id,HrsWork,HrsOT,NormOT,OffOT,HolOT,EarlyOut,LateIn,WorkHrs,HrsLess,HrsExtra,LeaveDays,AbsentDays,PresentDays,Holidays,LOPDays,[Emp_Id],[TimeStamp]) 
           VALUES (@MonthClosure_Id,@EmpId,@HrsWork,@HrsOT,@NormOT,@OffOT,@HolOT,@EarlyOut,@LateIn,@WorkHrs,@HrsLess,@HrsExtra,@LeaveDays,@AbsentDays,@PresentDays,@Holidays,@LOPDays,@UserId,
           @ProcessDateTime)
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_ImportMasterData]    Script Date: 03/25/2021 10:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_ImportMasterData]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		< Karthikeyan.R >
-- Create date: < 09-Apr-2017 >
-- Description:	< Import master data from the XML >
/*
Proc_TA_ImportMasterData ''
<NewDataSet>
  <TheData>
    <Sl_x0023_No>1</Sl_x0023_No>
    <EmployeeFirstName>a</EmployeeFirstName>
    <EmployeeMiddleName>b</EmployeeMiddleName>
    <EmployeeLastName>c</EmployeeLastName>
    <FatherName>d</FatherName>
    <MotherName>e</MotherName>
    <DateOfBirth>1990-06-02T00:00:00+05:30</DateOfBirth>
    <DateOfBirthInRecord>1990-06-02T00:00:00+05:30</DateOfBirthInRecord>
    <BloodGroup>B-ve</BloodGroup>
    <OfficialMailID>manikandan.rr@angleritech.com</OfficialMailID>
    <ContactAddress>f</ContactAddress>
    <PermanentAddress>g</PermanentAddress>
    <PhoneNumber>h</PhoneNumber>
    <MobileNumber>i</MobileNumber>
    <Gender>Female</Gender>
    <MaritalStatus>Single</MaritalStatus>
    <Nationality>j</Nationality>
    <ReligionName>k</ReligionName>
    <PersonalMailID>manikandan.rr@angleritech.com</PersonalMailID>
    <PassportNo>l</PassportNo>
    <PassportExpiryDate>2020-09-01T00:00:00+05:30</PassportExpiryDate>
    <VisaNo>m</VisaNo>
    <VisaExpiryDate>2020-09-01T00:00:00+05:30</VisaExpiryDate>
    <EmployeeID>o123</EmployeeID>
    <SwipeCardNo>o123</SwipeCardNo>
    <DateOfJoining>2011-03-05T00:00:00+05:30</DateOfJoining>
    <QualificationonJoiningTime>p</QualificationonJoiningTime>
    <QualificationDuringEmployement>q</QualificationDuringEmployement>
    <CompOffEligible>0</CompOffEligible>
    <OTEligible>0</OTEligible>
    <Hostel>r</Hostel>
    <Designation>s</Designation>
    <GradeName>Grade2</GradeName>
    <GradeNo>2</GradeNo>
    <EmployeeType>t</EmployeeType>
    <EmployeeCategory>u</EmployeeCategory>
    <BasicSalary>500</BasicSalary>
    <Company>v</Company>
    <Region>w</Region>
    <Level1>x</Level1>
    <Level2>y</Level2>
  </TheData>
</NewDataSet>'',''Enterprise'',''False'',1
select * from TA_Tbl_Employee
*/
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_ImportMasterData]
	-- Add the parameters for the stored procedure here
	@Xml XML,
	@Version nvarchar(50),
	@ApplnMode BIT,
	@FromXL int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Index INT 
	set @Index= 0
	declare @Error nvarchar(Max)
	EXEC sp_xml_preparedocument @Index OUTPUT, @Xml
	create table #ImportMaster 
	(
		id bigint identity(1,1),
		Sl_x0023_No bigint,
		Emp_FirstName nvarchar(50),
		Emp_MiddleName  nvarchar(50),
		Emp_LastName nvarchar(50),
		Father_Name nvarchar(50),
		Mother_Name nvarchar(50),
		DateOfBirth nvarchar(20),
		DateOfBirth_Record nvarchar(20),
		Blood_Group nvarchar(5),
		Email_Id nvarchar(100) ,
		Contact_Address nvarchar(250),
		Permanent_Address nvarchar(250),
		Phone_Number nvarchar(50),
		Mobile_Number nvarchar(50),
		Gender nvarchar(50),
		Marital_Status nvarchar(50),
		Nationality nvarchar(50),
		Religion nvarchar(50),
		Personal_EmailID nvarchar(100),
		Passport_No nvarchar(100),
		Passport_ExpiryDate nvarchar(20),
		Visa_No nvarchar(100),
		Visa_ExpiryDate nvarchar(20),
		Employee_Code nvarchar(25),
		SwipeCardNo nvarchar(25),
		DateOfJoining nvarchar(20),
		Qualification_joiningtime nvarchar(25),
		Qualification_Employement nvarchar(25),
		CompOff_Eligible nvarchar(1),
		OT_Eligible nvarchar(1),
		Hostel nvarchar(1),
		Designation nvarchar(50),
		Grade nvarchar(50),
		GradeNo nvarchar(50),
		Employee_Type nvarchar(50),
		Employee_Category nvarchar(50),
		BasicSalary nvarchar(10),
		Level1 nvarchar(50),
		Level2 nvarchar(50),
		Level3 nvarchar(50) ,
		Level4 nvarchar(50),
		Level5 nvarchar(50),
		Level6 nvarchar(50),
		Level7 nvarchar(50),
		Level8 nvarchar(50),
		Level9 nvarchar(50),
		Level10 nvarchar(50),
		IsValid int,
		Error Nvarchar(Max)
	)
	insert into  #ImportMaster
	select 
		Sl#No,
		rtrim(ltrim(EmployeeFirstName)),
		rtrim(ltrim(EmployeeMiddleName)),
		rtrim(ltrim(EmployeeLastName)),
		rtrim(ltrim(FatherName)),
		rtrim(ltrim(MotherName)),
		rtrim(ltrim(DateOfBirth)),
		rtrim(ltrim(DateOfBirthInRecord)),
		rtrim(ltrim(BloodGroup)),
		rtrim(ltrim(OfficialMailID)),
		rtrim(ltrim(ContactAddress)),
		rtrim(ltrim(PermanentAddress)),
		rtrim(ltrim(PhoneNumber)),
		rtrim(ltrim(MobileNumber)),
		rtrim(ltrim(Gender)),
		rtrim(ltrim(MaritalStatus)),
		rtrim(ltrim(Nationality)),
		rtrim(ltrim(ReligionName)),
		rtrim(ltrim(PersonalMailID)),
		rtrim(ltrim(PassportNo)),
		rtrim(ltrim(PassportExpiryDate)),
		rtrim(ltrim(VisaNo)),
		rtrim(ltrim(VisaExpiryDate)),
		rtrim(ltrim(EmployeeID)),
		rtrim(ltrim(SwipeCardNo)),
		rtrim(ltrim(DateOfJoining)),
		rtrim(ltrim(QualificationonJoiningTime)),
		rtrim(ltrim(QualificationDuringEmployement)),
		rtrim(ltrim(CompOffEligible)),
		rtrim(ltrim(OTEligible)),
		rtrim(ltrim(Hostel)),
		rtrim(ltrim(Designation)),
		rtrim(ltrim(GradeName)),
		rtrim(ltrim(GradeNo)),
		rtrim(ltrim(EmployeeType)),
		rtrim(ltrim(EmployeeCategory)),
		rtrim(ltrim(BasicSalary)),
		rtrim(ltrim(Level1)),
		rtrim(ltrim(Level2)),
		rtrim(ltrim(Level3)),
		rtrim(ltrim(Level4)),
		rtrim(ltrim(Level5)),
		rtrim(ltrim(Level6)),
		rtrim(ltrim(Level7)),
		rtrim(ltrim(Level8)),
		rtrim(ltrim(Level9)),
		rtrim(ltrim(Level10)),
		0,'''' from OPENXML(@Index, ''/NewDataSet/TheData'',2)
	WITH(
			Sl#No nvarchar(50),
			EmployeeFirstName  nvarchar(50),
			EmployeeMiddleName   nvarchar(50),
			EmployeeLastName  nvarchar(50),
			FatherName nvarchar(50),
			MotherName nvarchar(50),
			DateOfBirth nvarchar(11),
			DateOfBirthInRecord nvarchar(11),
			BloodGroup nvarchar(5),
			OfficialMailID nvarchar(100),
			ContactAddress nvarchar(250),
			PermanentAddress nvarchar(250),
			PhoneNumber nvarchar(50),
			MobileNumber nvarchar(50),
			Gender nvarchar(50),
			MaritalStatus nvarchar(50),
			Nationality nvarchar(50),
			ReligionName nvarchar(50),
			PersonalMailID nvarchar(100),
			PassportNo nvarchar(100),
			PassportExpiryDate nvarchar(11),
			VisaNo nvarchar(100),
			VisaExpiryDate nvarchar(11),
			EmployeeID nvarchar(25),
			SwipeCardNo nvarchar(25),
			DateOfJoining nvarchar(11),
			QualificationonJoiningTime nvarchar(25),
			QualificationDuringEmployement nvarchar(25),
			CompOffEligible nvarchar(1),
			OTEligible nvarchar(1),
			Hostel nvarchar(1),
			Designation nvarchar(50),
			GradeName nvarchar(50),
			GradeNo nvarchar(50),
			EmployeeType nvarchar(50),
			EmployeeCategory nvarchar(50),
			BasicSalary nvarchar(10),
			Level1 nvarchar(50) ''Level1'',
			Level2 nvarchar(50) ''Level2'',
			Level3 nvarchar(50) ''Level3'',
			Level4 nvarchar(50) ''Level4'',
			Level5 nvarchar(50) ''Level5'',
			Level6 nvarchar(50) ''Level6'',
			Level7 nvarchar(50) ''Level7'',
			Level8 nvarchar(50) ''Level8'',
			Level9 nvarchar(50) ''Level9'',
			Level10 nvarchar(50) ''Level10''
		  ) AS OT 
		--select * from #ImportMaster
		declare @Count as int=0
		Declare @Start int
		select @Count=COUNT(*) from #ImportMaster
		set @Start=1
		declare @isDateValid int
		declare @RowCount int
		declare @isDate nvarchar(50)
		declare @DateLength int
		declare @EmployeeCodeID nvarchar(50)
		declare @ValidateEmail nvarchar(100)
		declare @ErrorCount int=0
		declare @GradeName nvarchar(50)
		declare @GradeLevel nvarchar(50)
		declare @ImportGradeLevel nvarchar(50)
		declare @Designation as nvarchar(255)
		declare @Grade as nvarchar(255)
		declare @ImportGrade as nvarchar(255)
		declare @DateOfBirth as nvarchar(50)
		set @Error = ''''
		if(@FromXL=1)
			begin
				update #ImportMaster set 
				
				DateOfBirth= case when DateOfBirth is not null and  DateOfBirth!='''' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfBirth as nvarchar(10)) as datetime),106),'' '',''-'')
				else '''' end,
				DateOfBirth_Record=case when DateOfBirth_Record is not null and  DateOfBirth_Record!='''' then
					REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfBirth_Record as nvarchar(10)) as datetime),106),'' '',''-'')
				else '''' end,
				Passport_ExpiryDate=
				case when Passport_ExpiryDate is not null and  Passport_ExpiryDate!='''' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(Passport_ExpiryDate as nvarchar(10)) as datetime),106),'' '',''-'')
				else '''' end,
				Visa_ExpiryDate=
				case when Visa_ExpiryDate is not null and  Visa_ExpiryDate!='''' then	
					REPLACE(CONVERT(NVARCHAR,CAST(CAST(Visa_ExpiryDate as nvarchar(10)) as datetime),106),'' '',''-'')
					else '''' end,
				DateOfJoining=case when DateOfJoining is not null and  DateOfJoining!='''' then
				REPLACE(CONVERT(NVARCHAR,CAST(CAST(DateOfJoining as nvarchar(10)) as datetime),106),'' '',''-'')
				else '''' end
			end
		while @Start<=@Count
			BEGIN
				--Check Employee First name is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Emp_FirstName IS NULL OR Emp_FirstName = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  ''.Employee First Name is missing<br/>''
					end
				set @RowCount =0
				select @ValidateEmail=Email_Id from #ImportMaster where id=@Start 
				if(isnull(@ValidateEmail,'''')!='''')
					begin
						if(@ValidateEmail NOT LIKE ''_%@__%.__%'')
							BEGIN
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  ''.Invalid Mail ID<br/>''
							END
					end
				--Reset all values
				set @RowCount =0
				select @ValidateEmail=Personal_EmailID from #ImportMaster where id=@Start
				if(isnull(@ValidateEmail,'''')!='''')
					begin
						if(@ValidateEmail NOT LIKE ''_%@__%.__%'')
							BEGIN
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +  ''.Invalid Mail ID<br/>''
							END
					end
				--Reset all values
				set @RowCount =0
				--Check Gender is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Gender IS NULL OR Gender = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Gender is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Code is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Code IS NULL OR Employee_Code = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Employee ID is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check DateOfJoining is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (DateOfJoining IS NULL OR DateOfJoining = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Date Of Joining is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check Designation is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Designation IS NULL OR Designation = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Designation is missing <br/>''
					end
				--Reset all values
				set @RowCount =0
				if(@Version=''Enterprise'')
					begin
						--Check Grade is null or empty
						select @RowCount=COUNT(*) from #ImportMaster where (Grade IS NULL OR Grade = '''') and id=@Start
						if(isnull(@RowCount,0)>0)
							begin	
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Grade is missing<br/>''
							end
						--Reset all values
						set @RowCount =0
						--Check GradeNo is null or empty
						select @RowCount=COUNT(*) from #ImportMaster where (GradeNo IS NULL OR GradeNo = '''') and id=@Start
						if(isnull(@RowCount,0)>0)
							begin	
								set @ErrorCount=@ErrorCount+1
								set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Grade No. is missing <br/>''
							end
							--Reset all values
							select top 1 @GradeName=grade_Name,@GradeLevel=Grade_Level,@ImportGradeLevel=GradeNo from
							(select  distinct ta_tbl_grade.grade_Name,ta_tbl_grade.Grade_Level,#ImportMaster.GradeNo from #ImportMaster 
							inner join ta_tbl_grade on ta_tbl_grade.grade_Name=#ImportMaster.grade and ta_tbl_grade.Grade_Level<>#ImportMaster.GradeNo 
							where ta_tbl_grade.isdeleted=0 and #ImportMaster.id=@Start) GradeTable
							declare @errMessage as nvarchar(4000)
							--Adding Condition for Enterprise and standard seperately by Manjula.P on 03-Oct-2013
							if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
								begin
									if(@GradeName<>'''')
									BEGIN
										set @ErrorCount=@ErrorCount+1
										set @Error=@Error + CAST(@ErrorCount as nvarchar(10)) + ''.Grade Name : '' + @GradeName +  '' has different GradeNo ('' + @ImportGradeLevel + '') in the Employee Import file. Change the GradeNo as '' + @GradeLevel + '' <br/>''
									END
								end
							select top 1 @Designation=TitleName,@Grade=grade_Name,@ImportGrade=Grade from
								(select  distinct ta_tbl_title.TitleName,ta_tbl_grade.grade_Name,#ImportMaster.Grade from #ImportMaster
								inner join ta_tbl_title on  ta_tbl_title.TitleName=#ImportMaster.Designation 
								inner join ta_tbl_grade on ta_tbl_grade.Grade_Id=ta_tbl_title.GradeId and ta_tbl_grade.grade_Name<>#ImportMaster.grade
								where ta_tbl_grade.isdeleted=0 and #ImportMaster.id=@Start) GradeTable 
								if not exists (select * from TA_Tbl_Grade where Grade_Name=''SEGrade'' and Isdeleted=0)
								begin
								if(@Designation<>'''')
									BEGIN
										set @ErrorCount=@ErrorCount+1
										set @Error=@Error +  CAST(@ErrorCount as nvarchar(10)) + ''.Designation : '' + @Designation +  '' has different Grade ('' + @ImportGrade + '') in the Employee Import file. Change the Grade as '' + @Grade + '' <br/>''
									END
								END				
						set @RowCount =0
					END
				--Check Employee_Type is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Type IS NULL OR Employee_Type = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Employee Type is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Category is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Employee_Category IS NULL OR Employee_Category = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Employee Category is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check Level1 is null or empty
				select @RowCount=COUNT(*) from #ImportMaster where (Level1 IS NULL OR Level1 = '''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Oraganization Level is missing<br/>''
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid Gender
				select @RowCount=COUNT(*) from #ImportMaster where Gender <> ''female'' AND Gender <> ''male'' and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Gender should be either Male or Female <br/>''
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid CompOff_Eligible
				select @RowCount=COUNT(*) from #ImportMaster where (CompOff_Eligible<>''0'' AND CompOff_Eligible<>''1'') AND (CompOff_Eligible<>'''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Comp Off Eligible should be either 0 or 1 <br/>''
					end
				--Reset all values
				set @RowCount =0
				--Enter the valid OT_Eligible
				select @RowCount=COUNT(*) from #ImportMaster where (OT_Eligible<>''0'' AND OT_Eligible<>''1'') AND (OT_Eligible<>'''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.OT Eligible should be either 0 or 1 <br/>''
					end				
				--Reset all values
				set @RowCount =0
				--Enter the valid Hostel
				select @RowCount=COUNT(*) from #ImportMaster where (Hostel<>''0'' AND Hostel<>''1'') AND (Hostel<>'''') and id=@Start
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Hostel should be either 0 or 1 <br/>''
					end
				--Reset all values
				set @RowCount =0
				--Check Employee_Code
				select @EmployeeCodeID=Employee_Code from #ImportMaster where id=@Start
				select @RowCount=COUNT(*) from TA_Tbl_Employee where Employee_Code_Id=@EmployeeCodeID
				if(isnull(@RowCount,0)>0)
					begin	
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Employee ID is already available.<br/>''
					end
				--Reset all values
				set @RowCount =0
				-- Check if DateOfBirth is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfBirth from #ImportMaster where (DateOfBirth IS Not NULL And DateOfBirth != '''') and id=@Start group by DateOfBirth
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Birth Format is(dd-MMM-yyyy) <br/>''
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Birth Format is(dd-MMM-yyyy) <br/>''
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''''
				set @DateLength=0
				-- Check if DateOfJoining is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfJoining from #ImportMaster where (DateOfJoining IS Not NULL And DateOfJoining != '''') and id=@Start group by DateOfJoining
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Joining Format is(dd-MMM-yyyy) <br/>''
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Joining Format is(dd-MMM-yyyy) <br/>''
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''''
				set @DateLength=0
				-- Check if DateOfBirth_Record is valid or invalid
				select @RowCount=COUNT(*),@isDate=DateOfBirth_Record from #ImportMaster where (DateOfBirth_Record IS Not NULL And DateOfBirth_Record != '''') and id=@Start group by DateOfBirth_Record
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Birth Record Format is (dd-MMM-yyyy) <br/>''
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Date Of Birth Record Format is(dd-MMM-yyyy) <br/>''
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''''
				set @DateLength=0
				-- Check if Passport_ExpiryDate is valid or invalid
				select @RowCount=COUNT(*),@isDate=Passport_ExpiryDate from #ImportMaster where (Passport_ExpiryDate IS Not NULL And Passport_ExpiryDate != '''') and id=@Start group by Passport_ExpiryDate
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate),@DateLength=LEN(@isDate)					
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Passport Expiry Date Format is (dd-MMM-yyyy) <br/>''
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Passport Expiry Date Format is(dd-MMM-yyyy) <br/>''
					End
				end
				--Reset all values
				set @isDateValid =0
				set @RowCount =0
				set @isDate=''''
				set @DateLength=0
				-- Check if Visa_ExpiryDate is valid or invalid
				select @RowCount=COUNT(*),@isDate=Visa_ExpiryDate from #ImportMaster where (Visa_ExpiryDate IS Not NULL And Visa_ExpiryDate != '''') and id=@Start group by Visa_ExpiryDate
				if(isnull(@RowCount,0)>0)
				begin
					select @isDateValid=ISDATE(@isDate)
					select @DateLength=LEN(@isDate)
					if(@DateLength=11)
					begin
						if(isnull(@isDateValid,0)=0)
						begin
							set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Visa Expiry Date Format is (dd-MMM-yyyy) <br/>''
						end
					end
					else
					Begin
						set @ErrorCount=@ErrorCount+1
						set @Error= @Error + CAST(@ErrorCount as nvarchar(10)) +''.Please check the Visa Expiry Date Format is (dd-MMM-yyyy) <br/>''
					End
				end
				--select @Error
				if(@Error!='''')
					begin
						--SELECT SUBSTRING(@Error,1, len(@Error)-2)
						update #ImportMaster set IsValid=2,Error=SUBSTRING(@Error,1, len(@Error)-2) where id=@Start
					end
					--adfadsf-
				--else
				--	begin
				--		update #ImportMaster set IsValid=1 where id=@Start
				--		INSERT INTO [Ta_Tbl_ImportMasterData]([Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],[OutDoorJob],[CompOff_Eligible],[OT_Eligible],[ESI_Eligible],[PF_Eligible],[Report_Exclude],[Employee_Status],[SwipeCardNo],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[EmployeeType],[EmployeeCategory],[BasicSalary],[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10])
				--		select [Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],0,[CompOff_Eligible],[OT_Eligible],0,0,[Report_Exclude],[Employee_Status],[Employee_Code],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[Employee_Type],[Employee_Category],case when ISNULL([BasicSalary],'''')='''' then 0  else [BasicSalary] end,[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10] from #ImportMaster where id=@Start
				--		exec Proc_TA_InsertMasterDataLevelsParent
				--		exec Proc_TA_UpdateMasterDataLevelsParent 
				--		exec Proc_TA_InsertMasterData @ApplnMode
				--		exec Proc_TA_CreateUpdateMasterDataLevelsChild @ApplnMode
				--		delete TA_Tbl_ImportMasterError where id=(select isnull(TableID,0) from  #ImportMaster  where id=@Start)
				--	end	
				set @Error=''''
				set @ErrorCount=0
				set @Start=@Start+1
			END
		--Insert invalid data from temp table to TA_Tbl_ImportMasterError table
		if exists(select * from #ImportMaster where IsValid=2)
		begin
			insert into TA_Tbl_ImportMasterError  
			select Emp_FirstName ,Emp_MiddleName  ,Emp_LastName ,Father_Name ,Mother_Name ,DateOfBirth ,DateOfBirth_Record ,Blood_Group ,Email_Id,Contact_Address ,Permanent_Address ,Phone_Number ,Mobile_Number ,Gender ,Marital_Status ,Nationality ,Religion ,Personal_EmailID ,Passport_No ,Passport_ExpiryDate ,Visa_No ,Visa_ExpiryDate ,Employee_Code ,DateOfJoining ,Qualification_joiningtime ,Qualification_Employement ,CompOff_Eligible ,OT_Eligible ,0 ,0,0,Hostel ,Designation ,Grade ,GradeNo ,Employee_Type ,Employee_Category ,BasicSalary ,Level1 ,Level2 ,Level3 ,Level4 ,Level5 ,Level6 ,Level7 ,Level8 ,Level9 ,Level10 ,IsValid ,Error,id from  #ImportMaster where IsValid=2
		end
		else if not exists(select * from #ImportMaster where IsValid=2)
		begin
			set @Start=1
			while @Start<=@Count
			begin
				update #ImportMaster set IsValid=1 where id=@Start
				INSERT INTO [Ta_Tbl_ImportMasterData]([Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],[OutDoorJob],[CompOff_Eligible],[OT_Eligible],[ESI_Eligible],[PF_Eligible],[Report_Exclude],[Employee_Status],[SwipeCardNo],[IsDeleted],[Hostel],[Designation],[Grade],[GradeNo],[EmployeeType],[EmployeeCategory],[BasicSalary],[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10])
				select [Emp_FirstName],[Emp_MiddleName],[Emp_LastName],[Father_Name],[Mother_Name],[DateOfBirth],[DateOfBirth_Record],[Blood_Group],[Email_Id],[Contact_Address],[Permanent_Address],[Phone_Number],[Mobile_Number],[Gender],[Marital_Status],[Nationality],[Religion],[Personal_EmailID],[Passport_No],[Passport_ExpiryDate],[Visa_No],[Visa_ExpiryDate],[Employee_Code],[DateOfJoining],[Qualification_joiningtime],[Qualification_Employement],0,[CompOff_Eligible],[OT_Eligible],0,0,0,0,[SwipeCardNo],0,[Hostel],[Designation],[Grade],[GradeNo],[Employee_Type],[Employee_Category],case when ISNULL([BasicSalary],'''')='''' then 0  else [BasicSalary] end,[Level1],[Level2],[Level3],[Level4],[Level5],[Level6],[Level7],[Level8],[Level9],[Level10] from #ImportMaster where id=@Start
				exec Proc_TA_InsertMasterDataLevelsParent
				exec Proc_TA_UpdateMasterDataLevelsParent 
				exec Proc_TA_InsertMasterData @ApplnMode
				exec Proc_TA_CreateUpdateMasterDataLevelsChild @ApplnMode
				delete TA_Tbl_ImportMasterError 
				set @Start=@Start+1
			end
			delete TA_Tbl_ImportMasterError 
		end
		drop table #ImportMaster		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptWeeklyWorkHours_Angler]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name : Proc_TA_RptMonthlyAttendance  
Created By		:	A.K.T.MOORTHI
Created on		:	05-Aprl-2013
Description		:	To Get the weekly work hours 
Updated By		:	A.K.T.MOORTHI
Updated on		:	26-Aug-2013
Description		:	To Get Daily ARMIS Work Hours 
exec [Proc_TA_RptWeeklyWorkHours_Angler] @FromDate=N''01/oct/2015'',@ToDate=N''26/oct/2015'',@EmployeeName=N'''',@LevelID=N''904'',@EmployeeID=N'''',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''1'',@EmpSwipeCard=N'''',@EmpAutoId=359,@ParentId=107,@shift=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptWeeklyWorkHours_Angler]  
@FromDate datetime,  
@ToDate datetime,  
@EmployeeName varchar(50),  
@LevelID varchar(8000),
@EmployeeId varchar(50),
@employeeCategory int,
@employeeType int,
--Changed usergroup datatype length is 200 from 20 for data not loading : Bug : 0023839 
@UserGroupName varchar(200),
@GradeLevel varchar(20),	   
@EmpSwipeCard varchar(20),
@EmpAutoId bigint,
@ParentId int,
@shift int = 0
AS  
BEGIN  
	set nocount on
	--Get current date time format 
		DECLARE @dateFormat as int
		DECLARE @date as nvarchar(25)			
		SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
		IF(@date=''dd/MM/yyyy'')
			BEGIN
				SET @dateFormat = 103
			END
		ELSE IF(@date=''MM/dd/yyyy'')
			BEGIN
				SET @dateFormat = 101
			END
		ELSE
			BEGIN
				SET @dateFormat = 106
			END	
	--end
	--Temporary table''s creation
	create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
	create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
	create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
	create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
	create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
	create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)
	create table #LevelRights(LevelId int)
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
	(
		[EffectiveDate],[PayId],[EmployeeId] ASC
	) ON [PRIMARY]
	insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
	select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
	inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) ELevel
	inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EL.LevelId is not null
	--Employee Designation insert in Temporary table
	insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
	select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
	inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EDesig
	inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
	AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and ED.DesignationId is not null
	--Employee Type insert in Temporary table
	insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
	select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
	inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpType
	inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
	AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)  and EType.TypeId is not null
	--Employee Category insert in Temporary table
	insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
	select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
	inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 
	AND ec.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102)
	group by EmployeeId) EmpCategory
	inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
	and ECategory.CategoryId is not null
	insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
	select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
	inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
	where emp.Isdeleted=0 group by EmployeeId) EmpBpay
	inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
	AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@ToDate as nvarchar(50)), 102) and EPay.PayId is not null
	DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
	create table #TempAttendanceDetails (FNAttendanceCode nvarchar(15),ANAttendanceCode nvarchar(15),Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),LevelName nvarchar(250),Designation nvarchar(250),Date VARCHAR(20),InTime varchar(20),OutTime varchar(20),HrsWork varchar(20),
	TotalMinsWorked varchar(20),Shift_ShortName varchar(100),ShiftId int,shift_TotalWorkingHours nvarchar(50),LunchHours varchar(50),DefinedWorkHours varchar(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId int, CategoryName NVARCHAR(50),thirdSat bit,DinnerHours varchar(50),
	ArmisMin BIGINT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10), MinWorkHours BIGINT, ToolTip VARCHAR(MAX))
	--Create table #TempLowergradeEmpDetails(id int identity(1,1),swipeCardNo varchar(50))
	--insert into #TempLowergradeEmpDetails 
	--select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0 and Employee_Id=@EmpAutoId
	--insert into #TempLowergradeEmpDetails
	--select Employee_Code_Id from TA_Tbl_Employee where Isdeleted=0 and(Reporting_To=@EmpAutoId or Leave_Sanc_Authority=@EmpAutoId)	
	--DECLARE @List VARCHAR(max)
	--SELECT @List = COALESCE(@List + '', '' + swipeCardNo, swipeCardNo)FROM #TempLowergradeEmpDetails
	--Declare @count int
	--Declare @Start int
	--set @Start=1
	--Declare @GetEmployeeid varchar(max)
	--if(@UserGroupName not in(''Superadmin'',''Dy. Manager - HR''))
	--	begin
	--		set @count=(select count(*) from #TempLowergradeEmpDetails)			
	--		while @count>=@Start
	--			begin
	--				set @GetEmployeeid=(select swipeCardNo from #TempLowergradeEmpDetails where id=@Start)
	--				INSERT INTO @ArmisData
	--				SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,''00:00'',REPLACE(CAST(ISNULL(TotalTask, ''0.0'') AS VARCHAR), ''.'', '':'')) AS BIGINT) END) 
	--				FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, @GetEmployeeid)		
	--				set @Start=@Start+1
	--			end
	--	end
	--else
	--	begin
	--		INSERT INTO @ArmisData
	--		SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,''00:00'',REPLACE(CAST(ISNULL(TotalTask, ''0.0'') AS VARCHAR), ''.'', '':'')) AS BIGINT) END) 
	--		FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, null)
	--	end
	INSERT INTO @ArmisData
	SELECT *, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,''00:00'',REPLACE(CAST(ISNULL(TotalTask, ''0.0'') AS VARCHAR), ''.'', '':'')) AS BIGINT) END) 
	FROM [ProjectManagementV3July16].[dbo].[Fn_GetDayWiseProgressReport](@FromDate, @ToDate, NULL)
	--select * from @ArmisData
    declare @sqlQuery_Detailed as varchar(MAX)  
  	set @sqlQuery_Detailed=''''  
  	set @sqlQuery_Detailed = ''select	pd.fnAttendanceCode + case  when Status is null then '''''''' else ''''(BL)'''' end as FirstSession,
  										pd.anAttendanceCode + case  when Status is null then '''''''' else ''''(BL)'''' end  as SecondSession, 
  										e.Employee_Code_Id as Employee_Id,
  										isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,case when ''+CONVERT(varchar,@dateFormat) +''=106 then
									REPLACE(CONVERT(VARCHAR, pd.Date,''+CONVERT(varchar,@dateFormat)+''),'''' '''',''''-'''') 
									else CONVERT(VARCHAR, pd.Date, ''+CONVERT(varchar,@dateFormat)+'') end as Date,ISNULL(pd.InTime, ''''-''''),ISNULL(pd.OutTime, ''''-''''),ISNULL(pd.HrsWork, ''''-''''), ((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))) as TotalMinsWorked''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' ,(shf.Shift_ShortName + '''' ('''' + shf.Shift_StartTime + '''' - ''''  + shf.Shift_EndTime + '''')'''') as Shift_ShortName,pd.shift_id as ShiftID,shf.shift_TotalWorkingHours,ISNULL(pd.BreakHours, ''''-'''') as LunchHours, TA_Tbl_Category.MonToSat_WorkHrs as DefinedWorkHours, DATENAME(DW,pd.date), (CASE WHEN ((DATENAME(DW,pd.date) != ''''Saturday'''') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''''Saturday'''') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END)''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' ,(CASE WHEN ISNULL(Pd.BreakIn, '''''''') <> '''''''' AND ISNULL(Pd.BreakOut, '''''''') <> '''''''' AND (DATEDIFF(MI, ISNULL(SS.MaxLunchHours, ''''00:40''''), ISNULL(REPLACE(pd.BreakHours, ''''-'''', ''''''''), ''''00:00'''')) > 0) THEN 1 ELSE 0 END),TA_Tbl_Category.CategoryId, TA_Tbl_Category.CategoryName,0,DinnerHours, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')), ''''00:00'''', TBH.TotalBreakmin, (CASE WHEN (DATENAME(DW,pd.date) != ''''Saturday'''') THEN DATEDIFF(MI, ''''00:00'''',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''''.5'''', ''''.3''''), 0.0)), ''''.'''', '''':'''')) ELSE DATEDIFF(MI, ''''00:00'''',REPLACE((ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''''.5'''', ''''.3''''), 0.0)), ''''.'''', '''':'''')) END), NULL ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' from Ta_Tbl_Employee e ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id''    	
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join ta_tbl_TotalBreakHours TBH on TBH.Employee_Code_Id=pd.Employee_Code_Id and TBH.Shiftdate=pd.date''  
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''	
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''   
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeeType ET on e.Employee_Id = ET.EmployeeId''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_Type on ET.TypeId = TA_Tbl_Type.TypeId''
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' inner join TA_Tbl_EmployeePay EP ON e.Employee_Id = EP.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id''
	Set @sqlQuery_Detailed = @sqlQuery_Detailed + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpType on #EmpType.EffectiveDate=ET.EffectiveDate and #EmpType.employeeid=ET.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #EmpPay on #EmpPay.EffectiveDate=EP.EffectiveDate and #EmpPay.employeeid=EP.EmployeeId ''
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' Inner join #LevelRights on #LevelRights.LevelId=#EmpLevel.LevelId ''		
  	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' where e.Isdeleted=0 and e.report_exclude=0 and e.employee_Status=1 and((pd.date >= CONVERT(DATETIME, '''''' + cast(@FromDate as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@ToDate as nvarchar(11)) + '''''', 102)))''  
	if(@UserGroupName<>''SuperAdmin'')
	begin
	SET @sqlQuery_Detailed = @sqlQuery_Detailed + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel  
	end	 
	if not(@EmployeeName='''')  
		begin  
			set @sqlQuery_Detailed = @sqlQuery_Detailed + ''and (e.Employee_FirstName + '''' '''' +isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end 
	if not(@EmployeeId='''')  
		begin  
			set @sqlQuery_Detailed = @sqlQuery_Detailed + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
		end 
	If Not (@EmpSwipeCard = '''')  
			 Begin  
			  Set @sqlQuery_Detailed = @sqlQuery_Detailed + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			 End
	if(@shift<>0) 
			begin
				set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And pd.Shift_Id='' + cast (@shift as nvarchar(50))  
			end 
	if(@employeeCategory<>0)
		begin
			set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And ET.TypeId = '' + cast(@employeeType as nvarchar(8)) 
		end
  --  if(@EmpAutoId = 0)
	 --   BEGIN
		--	if not(@LevelID='''' or @LevelID=''0'')  
		--	begin  
		--	   set @sqlQuery_Detailed = @sqlQuery_Detailed + '' And (#EmpLevel.levelId In ('' + @LevelID + ''))''  
		--	End
		--END
		--ELSE
		if(@EmpAutoId > 0)
			BEGIN
			   set @sqlQuery_Detailed = @sqlQuery_Detailed + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
	set @sqlQuery_Detailed = @sqlQuery_Detailed + '' order by e.Employee_FirstName,cast(pd.date as datetime)''   
	 insert into #TempAttendanceDetails exec(@sqlQuery_Detailed) 	
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins), 
			REPLACE(REPLACE((SELECT ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'' + (CASE WHEN LEN(ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'') < 160 THEN SPACE(160 - LEN(ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'')) ELSE '''' END) FROM TA_VW_FirstInPunchDifference TT WHERE TT.EmployeeCodeId = FIP.EmployeeCodeId AND TT.[Date] = FIP.[Date] FOR XML PATH('''')), ''&gt;'', ''>''), ''&lt;'', ''<'') ToolTip
		FROM TA_VW_FirstInPunchDifference FIP WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date] 
	 HAVING SUM(PunchDifferenceMins) > 0
	Update #TempAttendanceDetails SET
		HrsWork =Case when ISNULL(AD.BreakHours,0)>0 THEN CASE WHEN LEN(CAST(((AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25))) = 1 THEN ''0''+ CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- CAST(ISNULL(AD.BreakHours,0) as INT))%60) AS VARCHAR(25)) END Else HrsWork End,
	    TotalMinsWorked=Case When (ISNULL(AD.BreakHours,0)>0) Then AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT) Else TotalMinsWorked End	,
	    ValidWorkHrs = (CASE WHEN (ISNULL(AD.BreakHours,0)>0) THEN (CASE WHEN (ISNULL(MinWorkHours, 0)) > (AD.TotalMinsWorked-CAST(ISNULL(AD.BreakHours,0) as INT)) THEN 1 ELSE ValidWorkHrs END) ELSE ValidWorkHrs END),
		BreakHours=CASE WHEN LEN(CAST((BreakHours/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((BreakHours/60) AS VARCHAR(25)) ELSE  CAST((BreakHours/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((BreakHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((BreakHours%60) AS VARCHAR(25)) ELSE CAST((BreakHours%60) AS VARCHAR(25)) END
	From #TempAttendanceDetails AD
	UPDATE #TempAttendanceDetails SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
		ExceptionHours = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN LEN(CAST((EH.TotalHrs/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((EH.TotalHrs/60) AS VARCHAR(25)) ELSE  CAST((EH.TotalHrs/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((EH.TotalHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((EH.TotalHrs%60) AS VARCHAR(25)) ELSE CAST((EH.TotalHrs%60) AS VARCHAR(25)) END) ELSE ExceptionHours END),
		ValidWorkHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN (ISNULL(MinWorkHours, 0)) > (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) THEN 1 ELSE ValidWorkHrs END) ELSE ValidWorkHrs END),
		ToolTip = EH.ToolTip
	FROM #TempAttendanceDetails AD
		RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
	 UPDATE #TempAttendanceDetails SET ValidWorkHrs = 0 where ValidWorkHrs = 1 and 
	 ((FNAttendanceCode not in (''Present'',''Absent'',''Holiday'',''Weekly Off'') and ANAttendanceCode = ''Present'')
	 or (ANAttendanceCode not in (''Present'',''Absent'',''Holiday'',''Weekly Off'') and FNAttendanceCode = ''Present''))
	 and TotalMinsWorked >= 240
	 update #TempAttendanceDetails set ValidWorkHrs = 0 where HrsWork = ''-'' 
	 UPDATE #TempAttendanceDetails SET ArmisMin = ISNULL(AD.TotalMin, 0) FROM #TempAttendanceDetails TAD
		INNER JOIN @ArmisData AD ON AD.Employee_Code_Id = TAD.Employee_Code_Id AND CAST(AD.[Date] AS DATE) = CAST(TAD.[Date] AS DATE)
	 SELECT 
		FNAttendanceCode,
		ANAttendanceCode,
		Employee_Code_Id,
		EmployeeName,
		LevelName,
		Designation,
		[Date],
		InTime,
		OutTime,
		HrsWork,
		TotalMinsWorked,
		Shift_ShortName,
		ShiftID,
		shift_TotalWorkingHours,
		LunchHours,
		DefinedWorkHours,
		Day,
		ValidLunchHrs,
		ValidWorkHrs,
		ISNULL(DinnerHours,''-'') AS DinnerHours,
		CASE WHEN LEN(CAST((ArmisMin/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((ArmisMin/60) AS VARCHAR(25)) ELSE  CAST((ArmisMin/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((ArmisMin%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisMin%60) AS VARCHAR(25)) ELSE CAST((ArmisMin%60) AS VARCHAR(25)) END AS ArmisHrs,
		ISNULL(ExceptionHours, ''00:00'') ExceptionHours,
		ISNULL(BreakHours, ''-'') BreakHours,
		ToolTip
	FROM #TempAttendanceDetails 
		WHERE [Day] != ''Sunday''
	 /*
	 To find Third saturday.
	 */
	 Declare @firstsat date
	 Declare @ThirdSat date
	 Select  @firstsat= dateadd(dd,(datediff(dd,-53685,dateadd(mm,datediff(mm,0,@ToDate),6))/7)*7,-53685)
	 Select @ThirdSat=DATEADD(dd,14,@firstsat)
	 Update #TempAttendanceDetails set thirdSat=1 where  #TempAttendanceDetails.Day=''Saturday'' and #TempAttendanceDetails.Date=@ThirdSat
	 create table #TempAttendanceSummary (Employee_Code_Id nvarchar(10),EmployeeName nvarchar(250),DefinedWorkHours decimal(18,1),HoursToDeduct decimal(18,1),SupposedToWorkHours decimal(18,1),ActualWorkHours INT,LessHours INT, CategoryName NVARCHAR(50), MaxDate DATE, ArmisHrs BIGINT)
	 INSERT INTO #TempAttendanceSummary
		SELECT
			TA.Employee_Code_Id,
			TA.EmployeeName,
			TA.DefinedWorkHours,
			SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
			0,
			SUM(CAST(TA.totalMinsWorked AS INT)),
			0,
			TA.CategoryName,
			CAST(MAX(TA.[Date]) AS DATE),
			SUM(ArmisMin)
		FROM #TempAttendanceDetails TA
			INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
		WHERE [Day] != ''Sunday''
		GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
	 update #TempAttendanceSummary set SupposedToWorkHours = (DefinedWorkHours - (HoursToDeduct))
	 update #TempAttendanceSummary set LessHours = ((SupposedToWorkHours * 60) - ActualWorkHours)
	 update #TempAttendanceSummary set LessHours = 0 where LessHours<= cast(0 as decimal(18,2))
	 select 
		Employee_Code_Id,
		EmployeeName,
		DefinedWorkHours,		
		HoursToDeduct,
	    SupposedToWorkHours,
		CASE when LEN(cast((ActualWorkHours/60) as varchar(25)))=1 THEN ''0'' +  cast((ActualWorkHours/60) as varchar(25)) ELSE  cast((ActualWorkHours/60) as varchar(25)) END  + '':'' + CASE  WHEN LEN(cast((ActualWorkHours%60) as varchar(25))) = 1 THEN ''0'' + cast((ActualWorkHours%60) as varchar(25)) ELSE cast((ActualWorkHours%60) as varchar(25)) END as ActualWorkHours,
		CASE when LEN(cast((LessHours/60) as varchar(25)))=1 THEN ''0'' +  cast((LessHours/60) as varchar(25)) ELSE  cast((LessHours/60) as varchar(25)) END  + '':'' + CASE  WHEN LEN(cast((LessHours%60) as varchar(25))) = 1 THEN ''0'' + cast((LessHours%60) as varchar(25)) ELSE cast((LessHours%60) as varchar(25)) END as LessHours,
		CategoryName,
		(CASE WHEN ((DATEPART(DW, MaxDate) > 5 ) AND (MaxDate < GETDATE()) AND (CAST(CASE WHEN LEN(CAST((LessHours/60) AS VARCHAR(25))) = 1 THEN ''0'' +  CAST((LessHours/60) AS VARCHAR(25)) ELSE CAST((LessHours/60) AS VARCHAR(25)) END  + ''.'' + CASE WHEN LEN(CAST((LessHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((LessHours%60) AS VARCHAR(25)) ELSE CAST((LessHours%60) AS VARCHAR(25)) END AS DECIMAL(18,2)) > 12)) THEN 1 ELSE 0 END) DayValid,
		CASE WHEN LEN(CAST((ArmisHrs/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST((ArmisHrs/60) AS VARCHAR(25)) ELSE  CAST((ArmisHrs/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST((ArmisHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisHrs%60) AS VARCHAR(25)) ELSE CAST((ArmisHrs%60) AS VARCHAR(25)) END AS ArmisHrs
	 from #TempAttendanceSummary
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpPay 
	drop table #EmpProcessedData
	drop table #EmployeeIds
	drop table #TempAttendanceSummary
	drop table #TempAttendanceDetails
	drop table #LevelRights
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMyCalendar]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMyCalendar]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*    
Proc_TA_RptMyCalendar ''IndividualUsers'',6
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptMyCalendar]
(   @USERGROUPNAME VARCHAR(250), 
	@EmpAutoId bigint
)   
AS    
BEGIN    
	SET NOCOUNT ON;
	CREATE TABLE #TEMPEMPLOYEE(EMPAUTOID BIGINT,EMPSWIPECARDNO VARCHAR(20))
	DECLARE @SQLTEMPPROCESSEDDATA VARCHAR(8000)
	DECLARE @SQLTEMPPROCESSEDDATA1 VARCHAR(8000)
	DECLARE @FROMDAT DATETIME
	DECLARE @TODAT DATETIME
	Declare @yearEnd Datetime
	Declare @EmployeeCode_id nvarchar(50)	
	select @EmployeeCode_id =Employee_Code_Id from TA_Tbl_Employee where Employee_Id=@EmpAutoId and Isdeleted=0 and Employee_Status=1
	DECLARE @PARENTID INT
	SET @PARENTID = 0
	if( (select FromDate from ta_tbl_yearsetting where Isactive=1) is null)  
	begin  
		set @FROMDAT=''01/01/1900''  
		set @TODAT=''01/01/1900''      
	end  
	else  
	begin  
		select @TODAT= GETDATE(),@FROMDAT =FromDate from ta_tbl_yearsetting where Isactive=1  
		if (@ParentId =0 )  
		begin  
			select @TODAT= dateadd(day,(select max(NoofSuccessiveDaysinyear) from ta_tbl_shiftsettings) ,ToDate)   
			from ta_tbl_yearsetting where Isactive=1   
		end  
		else
		begin  
		 --if successive year is not defined means, leave application throws unwanted error message.To avoid that, we added below conditon  
			 if exists(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings where companyId=@ParentId)  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=@ParentId),ToDate) from ta_tbl_yearsetting where Isactive=1  
			 end  
			 else  
			 begin  
				select @TODAT= dateadd(day,(select NoofSuccessiveDaysinyear from ta_tbl_shiftsettings   
				where companyId=-1),ToDate) from ta_tbl_yearsetting where Isactive=1  
			end  
		end  
	end  
	--set @FROMDAT=''20180317''
	--set @TODAT=''2018031''
	--TEMPORARY TABLE''S CREATION  
	CREATE TABLE #EMPLEVEL
	(
		EMPLOYEEID INT,
		LEVELID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPDESIGNATION
	(
		EMPLOYEEID INT,
		DESIGNATIONID INT,
		EFFECTIVEDATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(50),
		SWIPECARD VARCHAR(50)
	)
	CREATE TABLE #EMPTYPE(EMPLOYEEID INT,TYPEID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPCATEGORY(EMPLOYEEID INT,CATEGORYID INT,EFFECTIVEDATE DATETIME,EMPLOYEE_CODE_ID VARCHAR(50),SWIPECARD VARCHAR(50))
	CREATE TABLE #EMPPROCESSEDDATA(SWIPECARDNO VARCHAR(50),PROCESSDATE DATETIME,TOTALWORKMINS VARCHAR(50))    
	CREATE TABLE #LEVELRIGHTS(LEVELID INT)
	CREATE TABLE #TEMPPROCESSEDDATA
	(
		EMPAUTOID BIGINT,
		DATE DATETIME,
		EMPLOYEE_CODE_ID VARCHAR(20),
		INTIME NVARCHAR(25),
		OUTTIME NVARCHAR(25),
		SHIFT_ID INT,
		HRSWORK NVARCHAR(10),
		SUPPOSEDWORKHOURS NVARCHAR(10),
		STATUS NVARCHAR(50),
		ATTENDANCE NVARCHAR(20),
		ANATTENDANCECODE NVARCHAR(max),
		FNATTENDANCECODE NVARCHAR(max),
		PREVSHIFT_ID INT,
		PROCESS_REC_ID BIGINT,
		EXACTSHIFT_STARTTIME NVARCHAR(25),
		SHIFT_SECONDHALF_STARTTIME DATETIME,
		LATEINMIN	NVARCHAR(10),
		EARLYOUT NVARCHAR(10),
		LATEIN NVARCHAR(10),
		NORMOT NVARCHAR(10),
		OFFOT NVARCHAR(10),
		HOLOT NVARCHAR(10),
		OTMINS FLOAT,
		EARLYOUTMIN INT,
		OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT
		,INNOTATION CHAR(1),
		OUTNOTATION CHAR(1),
		BREAKHOURS VARCHAR(20),
		LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,
		LUNCHHOURSMINS INT
	)
	INSERT INTO  #LEVELRIGHTS SELECT * FROM [DBO].[FN_TA_GETPARENTCHILD](@USERGROUPNAME,0) AS LEVELID  
	DECLARE @SQLEMPLEVEL NVARCHAR(4000)
	INSERT INTO #EMPDESIGNATION EXEC PROC_TA_EMPDESIGNATION @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPTYPE EXEC [PROC_TA_EMPTYPE] @TODAT,@EmployeeCode_id,0
	INSERT INTO #EMPCATEGORY EXEC [PROC_TA_EMPCATEGORY] @TODAT,@EmployeeCode_id,0
	SET @SQLEMPLEVEL=
	''INSERT INTO #EMPLEVEL SELECT ELEVEL.EMPLOYEEID,EL.LEVELID,ELEVEL.EFFECTIVEDATE,EMPLOYEE_CODE_ID,SWIPECARDNO  FROM (
	SELECT MAX(EL.EFFECTIVEDATE) AS EFFECTIVEDATE,EL.EMPLOYEEID AS EMPLOYEEID,EMP.EMPLOYEE_CODE_ID,EMP.SWIPECARDNO FROM TA_TBL_EMPLOYEELEVEL EL
	INNER JOIN TA_TBL_EMPLOYEE EMP ON EL.EMPLOYEEID = EMP.EMPLOYEE_ID 
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	WHERE EMP.ISDELETED=0 ''
	if(@EmpAutoId > 0)
	BEGIN
		set @SQLEMPLEVEL = @SQLEMPLEVEL + '' and (EMP.Employee_ID ='' + CAST(@EmpAutoId AS NVARCHAR(8)) + '') ''  
	END		
	SET @SQLEMPLEVEL=@SQLEMPLEVEL+'' GROUP BY EMPLOYEEID,EMPLOYEE_CODE_ID,EMP.SWIPECARDNO
	) ELEVEL
	INNER JOIN TA_TBL_EMPLOYEELEVEL EL ON EL.EFFECTIVEDATE=ELEVEL.EFFECTIVEDATE AND EL.EMPLOYEEID=ELEVEL.EMPLOYEEID
	INNER JOIN #LEVELRIGHTS ON #LEVELRIGHTS.LEVELID=EL.LEVELID
	AND EL.EFFECTIVEDATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102) AND EL.LEVELID IS NOT NULL''	
	EXECUTE(@SQLEMPLEVEL)	
	
	SET @SQLTEMPPROCESSEDDATA=	''INSERT INTO #TEMPEMPLOYEE SELECT EMPLOYEE_ID,SWIPECARDNO FROM TA_TBL_EMPLOYEE  
	INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID=TA_TBL_EMPLOYEE.EMPLOYEE_ID '' 
	SET @SQLTEMPPROCESSEDDATA = @SQLTEMPPROCESSEDDATA + '' WHERE SWIPECARDNO IS NOT NULL AND TA_TBL_EMPLOYEE.ISDELETED=0''		
	EXECUTE(@SQLTEMPPROCESSEDDATA)	
	
	SET @SQLTEMPPROCESSEDDATA1=
	''INSERT INTO #TEMPPROCESSEDDATA 
	SELECT	#TEMPEMPLOYEE.EMPAUTOID,
			TA_TBL_PROCESSEDDATA.DATE,
			TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID,
			TA_TBL_PROCESSEDDATA.INTIME,
			TA_TBL_PROCESSEDDATA.OUTTIME,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.HRSWORK,
			TA_TBL_PROCESSEDDATA.WORKHRS,
			TA_TBL_PROCESSEDDATA.STATUS,
			TA_TBL_PROCESSEDDATA.ATTENDANCE,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''''Holiday'''' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''''Holiday'''' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.ANATTENDANCECODE end,
			case when TA_TBL_PROCESSEDDATA.ANATTENDANCECODE=''''Holiday'''' and TA_TBL_PROCESSEDDATA.FNATTENDANCECODE=''''Holiday'''' then Holiday_Description
			else TA_TBL_PROCESSEDDATA.FNATTENDANCECODE end,
			TA_TBL_PROCESSEDDATA.SHIFT_ID,
			TA_TBL_PROCESSEDDATA.PROCESS_REC_ID,
			S.SHIFT_STARTTIME,
			CAST(S.SHIFT_SECONDHALF_STARTTIME AS DATETIME)
			,LATEINMINS,
			EARLYOUT,
			LATEIN,
			TA_TBL_PROCESSEDDATA.NORMOT,
			TA_TBL_PROCESSEDDATA.OFFOT,
			TA_TBL_PROCESSEDDATA.HOLOT,
			OTMINS,
			CASE WHEN CHARINDEX(''''.'''',CONVERT(VARCHAR(20),EARLYOUTMINS))!=0 THEN CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(20),EARLYOUTMINS),0,CHARINDEX(''''.'''',CONVERT(VARCHAR(20),EARLYOUTMINS))))
			ELSE EARLYOUTMINS END,
			OVERTIMESTATUS,
			0,
			INNOTATION,
			OUTNOTATION,
			BREAKHRS,
			LUNCHHRS,
			BREAKHRSINMINS,
			LUNCHHRSINMINS
	FROM TA_TBL_PROCESSEDDATA INNER JOIN #TEMPEMPLOYEE ON #TEMPEMPLOYEE.EMPSWIPECARDNO=TA_TBL_PROCESSEDDATA.EMPLOYEE_CODE_ID  
	LEFT OUTER JOIN TA_TBL_SHIFT S ON S.SHIFT_ID=TA_TBL_PROCESSEDDATA.SHIFT_ID	
	WHERE PROCESSFLAG=1 AND (DBO.TA_TBL_PROCESSEDDATA.DATE >= CONVERT(DATETIME,''''''+CAST( @FROMDAT AS NVARCHAR(50))+'''''', 102))    
	AND (DBO.TA_TBL_PROCESSEDDATA.DATE <= CONVERT(DATETIME,''''''+CAST(@TODAT AS NVARCHAR(50))+'''''', 102))'' 
	EXECUTE(@SQLTEMPPROCESSEDDATA1)
	
	UPDATE PD SET EXACTSHIFT_STARTTIME=CAST(CONVERT(VARCHAR(25),SHIFT_SECONDHALF_STARTTIME,108) AS DATETIME) FROM #TEMPPROCESSEDDATA PD
	INNER JOIN TA_TBL_PROCESSEDDATA OPD ON PD.PROCESS_REC_ID=OPD.PROCESS_REC_ID WHERE OPD.FNATTENDANCECODE=''CL'' 	
	
	CREATE TABLE #TEMPMONTHLYATTENDANCE
	(
		FIRSTSESSION VARCHAR(500),SECONDSESSION VARCHAR(500),
		EMPLOYEE_ID VARCHAR(25),EMPNAME VARCHAR(500),BRANCHNAME VARCHAR(500),DESIGNATION VARCHAR(250),
		DATE DATETIME,INTIME VARCHAR(30),OUTTIME VARCHAR(30),
		HRSWORK VARCHAR(30),SUPPOSEDWORKHOURS VARCHAR(30),STATUS VARCHAR(30),
		TOTALMINSWORKED VARCHAR(30),SHIFT_SHORTNAME VARCHAR(20),
		SHIFT_TOTALWORKINGHOURS VARCHAR(20),GENDER NVARCHAR(10),
		EARLYOUT NVARCHAR(10),LATEIN NVARCHAR(10),OVERTIME VARCHAR(20),
		NORMOTMIN INT,OFFOTMIN INT,HOLOTMIN INT,NORMOT NVARCHAR(20),
		OFFOT NVARCHAR(20),HOLOT NVARCHAR(20),LATEINMIN INT,EARLYOUTMIN INT,
		TOTDEFWORKHRS INT,TOTSUPWORKHRS INT,OVERTIMESTATUS VARCHAR(20),
		NIGHTORMORN INT,LUNCHINTIME NVARCHAR(20),LUNCHOUTTIME NVARCHAR(20)
		,INNOTATION CHAR(1),OUTNOTATION CHAR(1)
		,BREAKHOURS VARCHAR(20),LUNCHHOURS VARCHAR(20),
		BREAKHOURSMINS INT,LUNCHHOURSMINS INT,
		SHIFT_STARTTIME	NVARCHAR(10),
		SHIFT_ENDTIME	NVARCHAR(10),
		CategoryName 	NVARCHAR(100),
		WeekDay_WorkHrs NVARCHAR(100),
		WeekNumber int,ExceptionMins BIGINT
	)
	Declare @ExceptionMins bigint
	--due to this line, we got date time conversion error and calendar is not loading. So commented on 21-Apr-2020 08:20 Pm
	--Got this in abraj client place
	--select top 1 @ExceptionMins=DATEDIFF(MI, ''00:00'', ISNULL(MaxWorkPlaceInHours, ''00:10'')) from TA_Tbl_ShiftSettings 
	set @ExceptionMins=0
	DECLARE @SQLQUERY AS VARCHAR(MAX)    
	SET @SQLQUERY=''''    	
	SET @SQLQUERY = ''SELECT PD.FNATTENDANCECODE AS FIRSTSESSION, PD.ANATTENDANCECODE AS SECONDSESSION,E.EMPLOYEE_CODE_ID AS EMPLOYEE_ID,ISNULL
	(E.EMPLOYEE_FIRSTNAME,'''''''') +  SPACE(1) + ISNULL(E.EMPLOYEE_LASTNAME,'''''''') AS EMPNAME,REPLACE(DBO.TA_TBL_LEVELDETAILS.NAME,''''&AMP;'''',''''&'''') AS BRANCHNAME,REPLACE(T.TITLENAME,''''&AMP;'''',''''&'''') AS DESIGNATION,CONVERT(VARCHAR(20),PD.DATE,101) AS DATE,
	PD.INTIME,PD.OUTTIME,PD.HRSWORK,CASE WHEN PD.FNATTENDANCECODE=''''WEEKLY OFF'''' AND ANATTENDANCECODE=''''WEEKLY OFF'''' THEN	''''-'''' 
	WHEN PD.FNATTENDANCECODE=''''HOLIDAY''''OR ANATTENDANCECODE=''''HOLIDAY'''' THEN ''''-''''
	ELSE PD.SUPPOSEDWORKHOURS END ''''SUPPOSEDWORKHOURS'''',(PD.ATTENDANCE +  CASE PD.STATUS WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + ISNULL(PD.STATUS,'''''''')) AS STATUS,((SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),0,CHARINDEX('''':'''',PD.HRSWORK))*60) + (SUBSTRING(ISNULL(PD.HRSWORK,''''00:00''''),(LEN(PD.HRSWORK)-1),2))) AS TOTALMINSWORKED''  
	SET @SQLQUERY = @SQLQUERY + '' ,(CASE PD.SHIFT_ID WHEN ''''-1'''' THEN ''''WEEKLY OFF'''' ELSE SHF.SHIFT_SHORTNAME END) AS SHIFT_SHORTNAME ,
	ISNULL(
				(
					CASE WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN ''''-'''' 
						 WHEN PD.SHIFT_ID=-1 THEN ''''-''''
						 ELSE SHF.SHIFT_TOTALWORKINGHOURS END
				),''''00:00''''
			) AS SHIFT_TOTALWORKINGHOURS,
	E.GENDER,	
	PD.EARLYOUT,PD.LATEIN,
	CASE WHEN PD.NORMOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.OFFOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 WHEN PD.HOLOT IS NOT NULL THEN CAST(OTMINS AS VARCHAR(50))
		 ELSE ''''00:00'''' END OVERTIME,
	CASE ISNULL(NORMOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OTMINS END AS ''''NORMOTMINS'''',
	CASE ISNULL(OFFOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OTMINS END AS ''''WEEKOFFOTMINS'''',
	CASE ISNULL(HOLOT,''''00:00'''') WHEN ''''00:00'''' THEN 0 ELSE OTMINS END AS ''''HOLIDAYOTMINS'''',
	PD.NORMOT AS HRSOT,PD.OFFOT,PD.HOLOT,LATEINMIN,EARLYOUTMIN,	
	CASE WHEN PD.SHIFT_ID=-1 THEN 0
		 WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
		 ELSE SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,0,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0))*60+SUBSTRING(SHF.SHIFT_TOTALWORKINGHOURS,CHARINDEX('''':'''',SHF.SHIFT_TOTALWORKINGHOURS,0)+1,LEN(SHF.SHIFT_TOTALWORKINGHOURS))
		 END AS TOTDEFWORKHRS
	,CASE	WHEN PD.SHIFT_ID=-1 THEN 0
			WHEN ((PD.FNATTENDANCECODE = ''''HOLIDAY'''') OR (PD.ANATTENDANCECODE = ''''HOLIDAY'''')) THEN 0
			ELSE SUBSTRING(PD.SUPPOSEDWORKHOURS,0,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0))*60+SUBSTRING(PD.SUPPOSEDWORKHOURS,CHARINDEX('''':'''',PD.SUPPOSEDWORKHOURS,0)+1,LEN(PD.SUPPOSEDWORKHOURS))
	END AS TOTSUPWORKHRS,CASE WHEN OVERTIMESTATUS IS NULL THEN ''''-'''' ELSE OVERTIMESTATUS END,NIGHTORMORN,''''00:00'''',''''00:00'''',INNOTATION,OUTNOTATION,PD.BREAKHOURS,LUNCHHOURS,BREAKHOURSMINS,LUNCHHOURSMINS,
	SHIFT_STARTTIME,SHIFT_ENDTIME,CategoryName,WeekDay_WorkHrs,
	DATEPART(week,date),''''''+convert(varchar,@ExceptionMins)+''''''''
	SET @SQLQUERY = @SQLQUERY + '' FROM TA_TBL_EMPLOYEE E ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #TEMPPROCESSEDDATA PD ON E.EMPLOYEE_ID=PD.EMPAUTOID''   
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPLEVEL ON #EMPLEVEL.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_LEVELDETAILS ON #EMPLEVEL.LEVELID = TA_TBL_LEVELDETAILS.ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPDESIGNATION EDESIG ON EDESIG.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_TITLE T ON EDESIG.DESIGNATIONID = T.TITLEID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN TA_TBL_GRADE ON TA_TBL_GRADE.GRADE_ID = T.GRADEID''     
	SET @SQLQUERY = @SQLQUERY + '' LEFT JOIN TA_TBL_SHIFT SHF ON PD.PREVSHIFT_ID = SHF.SHIFT_ID''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPTYPE ON #EMPTYPE.EMPLOYEEID = E.EMPLOYEE_ID ''  
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN #EMPCATEGORY ON #EMPCATEGORY.EMPLOYEEID = E.EMPLOYEE_ID ''
	SET @SQLQUERY = @SQLQUERY + '' INNER JOIN Ta_tbl_Category cat ON #EMPCATEGORY.CATEGORYID = cat.CategoryId ''
		SET @SQLQUERY = @SQLQUERY + '' WHERE E.ISDELETED=0 AND E.REPORT_EXCLUDE=0 AND 
		((E.EMPLOYEE_STATUS=1)
		OR
		(E.EMPLOYEE_STATUS=0 AND CONVERT(NVARCHAR(11),E.INACTIVEDATE,102)>=CONVERT(NVARCHAR(11),PD.DATE,102)) )
		AND((PD.DATE >= CONVERT(DATETIME, '''''' + CAST(@FROMDAT AS NVARCHAR(11)) + '''''', 102) AND PD.DATE <= CONVERT(DATETIME, '''''' + CAST(@TODAT AS NVARCHAR(11)) + '''''', 102)))''    
		if(@EmpAutoId > 0)
		BEGIN
			set @sqlQuery = @sqlQuery + '' and (e.Employee_ID ='' + CAST(@EmpAutoId AS NVARCHAR(8)) + '') ''  
		END
	SET @SQLQUERY = @SQLQUERY + '' ORDER BY E.EMPLOYEE_FIRSTNAME,CAST(PD.DATE AS DATETIME)''     	
	INSERT INTO #TEMPMONTHLYATTENDANCE EXEC(@SQLQUERY)		
	UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=CASE WHEN (FIRSTSESSION=''PRESENT'' OR FIRSTSESSION=''*PRESENT'' OR FIRSTSESSION=''HOLIDAY'' OR FIRSTSESSION=''*HOLIDAY'' OR FIRSTSESSION=''WEEKLY OFF'' OR FIRSTSESSION=''*WEEKLY OFF'') AND INNOTATION=''M'' THEN  FIRSTSESSION	
	ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE
	WHEN (SECONDSESSION=''PRESENT'' OR SECONDSESSION = ''*PRESENT'' OR SECONDSESSION =''HOLIDAY'' OR SECONDSESSION =''*HOLIDAY'' OR SECONDSESSION =''WEEKLY OFF'' OR SECONDSESSION =''*WEEKLY OFF'')  AND OUTNOTATION=''M'' THEN  SECONDSESSION
	ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE	
	UPDATE #TEMPMONTHLYATTENDANCE SET FIRSTSESSION=CASE WHEN (FIRSTSESSION=''HOLIDAY'' OR FIRSTSESSION=''*HOLIDAY'') THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	ELSE #TEMPMONTHLYATTENDANCE.FIRSTSESSION END FROM #TEMPMONTHLYATTENDANCE
	UPDATE #TEMPMONTHLYATTENDANCE SET SECONDSESSION=CASE WHEN (SECONDSESSION=''HOLIDAY'' OR SECONDSESSION=''*HOLIDAY'') THEN (select Holiday_Description from TA_Tbl_Holiday where ((Holiday_FromDate >= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102) AND Holiday_ToDate <= CONVERT(DATETIME, CAST(#TEMPMONTHLYATTENDANCE.DATE AS NVARCHAR(11)) , 102)))) 
	ELSE #TEMPMONTHLYATTENDANCE.SECONDSESSION END FROM #TEMPMONTHLYATTENDANCE
	DECLARE @DATEFORMAT AS INT
	Declare @toConfrmAngler int
	select @toConfrmAngler =pageId from ta_tbl_page where pageid=185--payroll configuration page id
	SET @DATEFORMAT = 126
	CREATE TABLE #TEMPMYCALENDAR(SINO int identity(1,1) primary key,EMPLOYEE_ID nVarchar(100),DATE nvarchar(20),SHIFT_SHORTNAME nvarchar(20),HRSWORK nvarchar(25),STATUS nvarchar(max),STATUS2 nvarchar(max),EXPHRS nvarchar(25),TOTALMINSWORKED int,INTIME VARCHAR(30),OUTTIME VARCHAR(30),lateInmins int default(0),earlyOutmins int default(0),shiftTimings nvarchar(30))
	if(@toConfrmAngler>0)
	begin
		Create table #tempBreakHours(id int identity(1,1),ShiftDate datetime,Employee_code_id varchar(20),TotalBreakmin int)
		CREATE NONCLUSTERED INDEX [IDX_tempBreakHours] ON [DBO].#tempBreakHours(ShiftDate,Employee_code_id,TotalBreakmin) ON [PRIMARY] 
		Insert into #tempBreakHours
		select ShiftDate,Employee_Code_Id,TotalBreakmin from ta_tbl_TotalBreakHours 
		where (ShiftDate>=@FROMDAT and ShiftDate<=@TODAT) and TotalBreakmin is not null
		DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT, ToolTip VARCHAR(MAX))
		--select * from #TEMPMONTHLYATTENDANCE
		--select @FROMDAT,@TODAT
		INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, FIP.[Date] , SUM(PunchDifferenceMins), 
			REPLACE(REPLACE((SELECT ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'' + (CASE WHEN LEN(ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'') < 160 THEN SPACE(160 - LEN(ISNULL(EntranceName, '''') + '' '' + ISNULL(EntranceType, '''') + '' ('' + ISNULL(EntranceTime, '''') + '') <=: ['' + ISNULL(PunchDifference, '''') + ''] :=> '' + ISNULL(FloorName, '''') + '' '' + ISNULL(FloorType, '''') + '' ('' + ISNULL(FloorTime, '''') + '')'')) ELSE '''' END) FROM TA_VW_FirstInPunchDifference TT WHERE TT.EmployeeCodeId = FIP.EmployeeCodeId AND TT.[Date] = FIP.[Date] FOR XML PATH('''')), ''&gt;'', ''>''), ''&lt;'', ''<'') ToolTip
		FROM TA_VW_FirstInPunchDifference FIP 		
		inner join #TEMPMONTHLYATTENDANCE TM on (TM.EMPLOYEE_ID=FIP.EmployeeCodeId) and (FIP.[Date]=TM.DATE)
		WHERE (FIP.[Date] BETWEEN @FROMDAT AND @TODAT)
		GROUP BY EmployeeCodeId, FIP.[Date]  
		HAVING SUM(PunchDifferenceMins) > 0		
		update #TEMPMONTHLYATTENDANCE set HrsWork=Case when ISNULL(TotalBreakmin,0)>0 THEN CASE WHEN LEN(CAST(((TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) ELSE  CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25))) = 1 THEN ''0''+ CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) ELSE CAST(((TOTALMINSWORKED- CAST(ISNULL(TotalBreakmin,0) as INT))%60) AS VARCHAR(25)) END Else HrsWork End
		,TotalMinsWorked=Case When (ISNULL(TotalBreakmin,0)>0) Then TOTALMINSWORKED-CAST(ISNULL(TotalBreakmin,0) as INT) Else TotalMinsWorked End	
		FROM #TEMPMONTHLYATTENDANCE TM inner join #tempBreakHours TB on TM.EMPLOYEE_ID=TB.Employee_code_id and TM.DATE=TB.ShiftDate
		UPDATE #TEMPMONTHLYATTENDANCE SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE	WHEN EH.TotalHrs > TM.TotalMinsWorked THEN ''00:00'' 
																		ELSE (CASE	WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																					ELSE  CAST(((TM.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) 
																			  END  + '':'' + 
																			  CASE  WHEN LEN(CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																					ELSE CAST(((TM.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) 
																			  END
																		     ) 
																END) 
       ELSE HrsWork END),
        TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > TotalMinsWorked THEN 0 ELSE (TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TEMPMONTHLYATTENDANCE TM
		RIGHT JOIN @TempExecptionHrs EH ON TM.EMPLOYEE_ID=EH.Employee_code_id and TM.DATE=EH.Date
		insert into #TEMPMYCALENDAR SELECT EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
					REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS=''Holiday'' then ''Holiday'' else FIRSTSESSION end,
		case when STATUS=''Holiday'' then ''Holiday'' else SECONDSESSION end,
		case when @toConfrmAngler>0 then cast(dateadd(s,isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)) else
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0))	end,TOTALMINSWORKED,
		INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,
		--case when SHIFT_SHORTNAME=''WEEKLY OFF'' then ''OFF'' else SHIFT_STARTTIME+'' - ''+SHIFT_ENDTIME end
		''''
		FROM #TEMPMONTHLYATTENDANCE
		--Future Holiday details
		insert into #TEMPMYCALENDAR		
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), H.Holiday_FromDate, @DATEFORMAT),'''','''',H.Holiday_Description,H.Holiday_Description,'''','''','''','''','''','''','''' from TA_Tbl_Holiday H
		inner join TA_Tbl_HolidayChildTable HC on H.Holiday_Id=HC.Holiday_Id
		inner join #EMPLEVEL EL on HC.LevelId=EL.LEVELID
		WHERE H.Holiday_FromDate>=GETDATE() and H.Holiday_ToDate<=@TODAT
		--Future Leave details
		insert into #TEMPMYCALENDAR
		select EL.EMPLOYEE_CODE_ID,CONVERT(VARCHAR(10), LA.Leave_FromDate, @DATEFORMAT),'''','''',LT.LeaveType +''-'' + LA.Status,LT.LeaveType+''-'' + LA.Status,'''','''','''','''','''','''','''' from TA_Tbl_LeaveApplication LA
		--inner join TA_Tbl_LeaveApplicationExists LAE on LA.LeaveApplication_Id=LAE.LeaveApplicationId
		inner join TA_Tbl_Employee E on LA.Employee_Id=E.Employee_Id
		inner join #EMPLEVEL EL on E.Employee_Id=EL.EMPLOYEEID
		inner join TA_Tbl_LeaveType LT on LA.LeaveType_id=LT.LeaveType_Id
		where LA.IsDeleted=0 and (LA.Leave_FromDate>=GETDATE() and LA.Leave_ToDate<=@TODAT)
		--select * from #TEMPMYCALENDAR
		DECLARE @ArmisData TABLE(Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2), [Date] DATETIME, TotalMin BIGINT)
		INSERT INTO @ArmisData
		SELECT a.*, (CASE WHEN TotalTask < 24 THEN CAST(DATEDIFF(MI,''00:00'',REPLACE(CAST(ISNULL(TotalTask, ''0.0'') AS VARCHAR), ''.'', '':'')) AS BIGINT) END) 
		FROM [ProjectManagementV3].[dbo].[Fn_GetDayWiseProgressReport](@FROMDAT, @TODAT, @EmployeeCode_id)as a
		UPDATE #TEMPMYCALENDAR SET shiftTimings =
		convert(varchar,TotalTask)
		FROM #TEMPMYCALENDAR TAD
		INNER JOIN @ArmisData AD ON AD.Employee_Code_Id = TAD.EMPLOYEE_ID AND CAST(AD.[Date] AS DATE) = CAST(TAD.[Date] AS DATE)
	end
	else	
	begin
		insert into #TEMPMYCALENDAR
		 SELECT  EMPLOYEE_ID ,
		CASE	WHEN CAST(@DATEFORMAT AS VARCHAR(100))=106 THEN
					REPLACE(CONVERT(VARCHAR, DATE,@DATEFORMAT),'' '',''-'') 
				ELSE CONVERT(VARCHAR(10), DATE, @DATEFORMAT) END ,	
		CASE WHEN SHIFT_SHORTNAME=''WEEKLY OFF'' THEN ''OFF'' ELSE #TEMPMONTHLYATTENDANCE.SHIFT_SHORTNAME END [SHIFT SHORTNAME],
		HRSWORK,	
		case when STATUS=''Holiday'' then ''Holiday'' else FIRSTSESSION end,case when STATUS=''Holiday'' then ''Holiday'' else SECONDSESSION end,
		cast(dateadd(s, isnull(datediff(s, 0, EARLYOUT), 0) + isnull(datediff(s, 0, LATEIN), 0), 0) as time(0)),TOTALMINSWORKED,INTIME,OUTTIME,LATEINMIN,EARLYOUTMIN,''''
		FROM #TEMPMONTHLYATTENDANCE
	end	
	Declare @list nvarchar(max)
	--slno,EmployeeAutoId,Date,ShiftTimings,Hrswork,Status,status2,ExceptionHours,Intime,outtime,latein,earlyout
	select @list=coalesce(@list,'''')+CONVERT(varchar(max),isnull(SINO,''''))+'',''+CONVERT(varchar(max),isnull(EMPLOYEE_ID,''''))+'',''+CONVERT(varchar(max),isnull(DATE,''''))+'',''+
	CONVERT(varchar(max),isnull(shiftTimings,''-''))+'',''+CONVERT(varchar(max),isnull(HRSWORK,''''))+'',''+CONVERT(varchar(max),isnull(STATUS,''''))+'',''+CONVERT(varchar(max),isnull(STATUS2,''''))+'',''+CONVERT(varchar(max),isnull(EXPHRS,''''))+'',''+CONVERT(varchar(10),isnull(INTIME,''''))
	+'',''+CONVERT(varchar(10),isnull(OUTTIME,''''))+'',''+CONVERT(varchar(10),isnull(lateInmins,0))+'',''+CONVERT(varchar(10),isnull(earlyOutmins,0))+''%'' from #TEMPMYCALENDAR
	select substring(@list,0,LEN(@list)) as ''MyCalendarOutput''
	DROP TABLE #EMPLEVEL  
	DROP TABLE #EMPDESIGNATION  
	DROP TABLE #EMPTYPE  
	DROP TABLE #EMPCATEGORY  
	DROP TABLE #EMPPROCESSEDDATA  
	DROP TABLE #LEVELRIGHTS  
	DROP TABLE #TEMPPROCESSEDDATA  
	DROP TABLE #TEMPEMPLOYEE  
	DROP TABLE #TEMPMONTHLYATTENDANCE
	DROP TABLE #TEMPMYCALENDAR	 	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrsNew]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
exec [Proc_TA_RptMonthlyDeviationHrsNew] 
@FromDate=N''25/Apr/2016'',@ToDate=N''30/apr/2016'',@EmployeeName=N'''',@LevelID=N''107'',@EmployeeID=N''659'',@EmployeeCategory=0,
@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpSwipeCard=N'''',@EmpAutoId=0,@Deviation=1,@ParentId=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrsNew]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT,
    @ParentId INT
AS  
BEGIN  
	SET NOCOUNT ON
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '''', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != ''Sunday'' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = ''Week'' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + '', TargetWorkHours_'' + @WeekName + '' VARCHAR(10), ActualWorkHours_'' + @WeekName + '' VARCHAR(10), ArmisWorkHours_'' + @WeekName + '' VARCHAR(10), [Leave_Permision_'' + @WeekName + ''] VARCHAR(10), DeviationHours_'' + @WeekName + '' VARCHAR(30)'', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''FinalAttendanceSummary'')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC(''CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)'' + @TableColumns + '')'')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = ''Week'' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
		(
			[PayId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]		
--Employee Level insert in Temporary table
		INSERT INTO #EmpLevel 
			SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
				SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
					INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
			INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
			AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
		INSERT INTO #EmpDesignation
			SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
				SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
					INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
			INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
			AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
		INSERT INTO #EmpType 
			SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
				SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
					INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
					WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
			INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
			AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
		INSERT INTO #EmpCategory
			SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
				SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
					INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102)
				GROUP BY EmployeeId) EmpCategory
			INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
				AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
		INSERT INTO #EmpPay
			SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
				SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
					INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
			INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
				AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
			SET @SQLQuery = ''SELECT * FROM 
			[ProjectManagementV3].[dbo].[Fn_GetProgressReport]('''''' + CAST(@FromDate AS VARCHAR(20)) + '''''','''''' + CAST(@ToDate AS VARCHAR(20)) + '''''''' + (CASE WHEN @EmployeeId = '''' OR @EmployeeId IS NULL THEN '', NULL)'' ELSE '', '' + @EmployeeId + '')'' END)
			INSERT INTO @ArmisTable
			EXEC(@SQLQuery)			
			--select * from @ArmisTable
  		SET @SQLQuery = ''SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END,''
  		SET @SQLQuery = @SQLQuery + '' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''''''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''''''), REPLACE(LD.Name, ''''&amp;'''', ''''&''''),''
  		SET @SQLQuery = @SQLQuery + '' REPLACE(T.TitleName, ''''&amp;'''', ''''&''''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''''-''''), ISNULL(PD.OutTime, ''''-''''),''
  		SET @SQLQuery = @SQLQuery + '' ISNULL(PD.HrsWork, ''''-''''), ((SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 4, 2))),''
		SET @SQLQuery = @SQLQuery + '' (S.Shift_ShortName + '''' ('''' + S.Shift_StartTime + '''' - ''''  + S.Shift_EndTime + '''')''''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' (CASE WHEN (ISNULL(PD.BreakIn, '''''''') = '''''''' OR ISNULL(PD.BreakOut, '''''''') = '''''''') AND PD.BreakHours <> ''''00:00'''' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')),ISNULL(SS.MaxWorkPlaceInHours, ''''00:10''''), NULL FROM Ta_Tbl_Employee E''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id''    
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId''   
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId ''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId ''		
  		SET @SQLQuery = @SQLQuery + '' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, '''''' + CAST(@FromDate AS NVARCHAR(11)) + '''''', 102) AND PD.Date <= CONVERT(DATETIME, '''''' + CAST(@ToDate AS NVARCHAR(11)) + '''''', 102)))''
		IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel + ''''
		END
		IF NOT(@EmployeeName = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_FirstName + '''' '''' + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName +''%'' AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmployeeId='''')  
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmpSwipeCard = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND E.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		--IF(@EmpAutoId = 0)
		--BEGIN
		--	IF NOT(@LevelID = '''' OR @LevelID = ''0'')  
		--	BEGIN
		--		SET @SQLQuery = @SQLQuery + '' AND (TEL.levelId IN ('' + @LevelID + ''))''  
		--	END
		--END
		--ELSE
		--BEGIN
		--	SET @SQLQuery = @SQLQuery + '' AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds))''
		--END
		SET @SQLQuery = @SQLQuery + '' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)''   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = ''Saturday'' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != ''Sunday''
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			select * from #TempAttendanceDetails
			select * from #TempAttendanceSummary
			UPDATE #TempAttendanceSummary SET DeviationHours = case when actualworkHours=0 then 0 else (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60)) end
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = case when actualworkHours=0 then 0 else ISNULL(A.TotalTask, 0) end FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
			case when actualworkHours=0 then 0 else
			--select 
			--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
			CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
					 (ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
															(
																substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours)))*60
																+
																substring(convert(varchar(10),ArmisWorkHours),CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
																+ 
																[Leave_Permision] *60
																+ 
																(DefinedWorkHours - TargetWorkHours)*60
															)
														)
					ELSE 0 
			END
			End
			FROM #TempAttendanceSummary TAS
			INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
			INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  		INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
  		--where E.Employee_Code_Id=''787''
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), ''.'', '':'') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + '':'' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, ''.'', '':'') AS ArmisWorkHours,
			REPLACE([Leave_Permision], ''.'', '':'') AS [Leave_Permision],
			''T:''+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			''A:''+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END 
			AS DeviationHours
		 INTO #TempFinalResult 
		 FROM #TempAttendanceSummary	
		 WHERE 		 
		 (@Deviation = 1 AND DeviationHours != 0) 
		 OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = ''UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_'' + @WeekName + '' = TR.TargetWorkHours,
							ActualWorkHours_'' + @WeekName + '' = TR.ActualWorkHours,
							ArmisWorkHours_'' + @WeekName + '' = TR.ArmisWorkHours,
							[Leave_Permision_'' + @WeekName + ''] = TR.[Leave_Permision],
							DeviationHours_'' + @WeekName + '' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName''
		EXEC(@SQLQuery)
		SET @SQLQuery = ''INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_'' + @WeekName + '', ActualWorkHours_'' + @WeekName + '', ArmisWorkHours_'' + @WeekName + '', [Leave_Permision_'' + @WeekName + ''], DeviationHours_'' + @WeekName + '')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL''
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory
		DROP TABLE #EmpPay		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE #LevelRights
	DROP TABLE FinalAttendanceSummary
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrs_New]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs_New
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
Updated By		:	A.K.T.MOORTHI
Updated on		:	20-Jun-2013
Description		:	Subtract The Exception Hours From Work Hours
EXEC [Proc_TA_RptMonthlyDeviationHrs_New] ''28/Oct/2013'',''02/Nov/2013'','''',''107,108,109,110,111,112,113,114,115,123'','''',0,0,''SuperAdmin'',0,''804'',0,0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs_New]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT
AS  
BEGIN  
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '''', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id BIGINT, [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != ''Sunday'' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = ''Week'' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + '', TargetWorkHours_'' + @WeekName + '' VARCHAR(10), ActualWorkHours_'' + @WeekName + '' VARCHAR(10), ArmisWorkHours_'' + @WeekName + '' VARCHAR(10), [Leave_Permision_'' + @WeekName + ''] VARCHAR(10), DeviationHours_'' + @WeekName + '' VARCHAR(10)'', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''FinalAttendanceSummary'')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC(''CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)'' + @TableColumns + '')'')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = ''Week'' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
		CREATE TABLE #EmpPay(EmployeeId INT, PayId INT, EffectiveDate DATETIME)	
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs BIT)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_PayId] Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_PayId] ON [dbo].[#EmpPay] 
		(
			[PayId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpPay] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Level insert in Temporary table
		INSERT INTO #EmpLevel 
			SELECT Elevel.EmployeeId, EL.levelId, Elevel.EffectiveDate FROM(
				SELECT MAX(EL.EffectiveDate) EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel EL
					INNER JOIN TA_Tbl_Employee E ON EL.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) ELevel
			INNER JOIN TA_Tbl_EmployeeLevel EL on EL.EffectiveDate = ELevel.EffectiveDate AND EL.EmployeeId = ELevel.EmployeeId
			AND EL.EffectiveDate <= CONVERT(DATETIME,CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
		INSERT INTO #EmpDesignation
			SELECT EDesig.EmployeeId, ED.DesignationId, EDesig.EffectiveDate FROM(
				SELECT MAX(ED.EffectiveDate) AS EffectiveDate, ED.EmployeeId FROM TA_Tbl_EmployeeDesignation ED
					INNER JOIN TA_Tbl_Employee E ON ED.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EDesig
			INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND  ED.employeeid = EDesig.EmployeeId
			AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
		INSERT INTO #EmpType 
			SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
				SELECT MAX(ET.EffectiveDate) AS EffectiveDate, ET.EmployeeId FROM TA_Tbl_EmployeeType ET
					INNER JOIN TA_Tbl_Employee E ON ET.EmployeeId = E.Employee_Id 
					WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpType
			INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId
			AND EType.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
		INSERT INTO #EmpCategory
			SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
				SELECT MAX(EC.EffectiveDate) AS EffectiveDate, EC.EmployeeId FROM TA_Tbl_EmployeeCategory EC
					INNER JOIN TA_Tbl_Employee E ON EC.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted=0 AND EC.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102)
				GROUP BY EmployeeId) EmpCategory
			INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate
				AND ECategory.employeeid = EmpCategory.EmployeeId AND ECategory.CategoryId IS NOT NULL
	--Employee Pay insert in Temporary table
		INSERT INTO #EmpPay
			SELECT EmpBpay.EmployeeId, EPay.PayId, EmpBpay.EffectiveDate FROM(
				SELECT MAX(EP.EffectiveDate) AS EffectiveDate, EP.EmployeeId FROM TA_Tbl_EmployeePay EP
					INNER JOIN TA_Tbl_Employee E ON EP.EmployeeId = E.Employee_Id 
				WHERE E.Isdeleted = 0 GROUP BY EmployeeId) EmpBpay
			INNER JOIN TA_Tbl_EmployeePay EPay ON EPay.EffectiveDate = EmpBpay.EffectiveDate AND EPay.employeeid = EmpBpay.EmployeeId
				AND EPay.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EPay.PayId IS NOT NULL
			SET @SQLQuery = ''SELECT * FROM [ProjectManagementV3].[dbo].[Fn_GetProgressReport]('''''' + CAST(@FromDate AS VARCHAR(20)) + '''''','''''' + CAST(@ToDate AS VARCHAR(20)) + '''''''' + (CASE WHEN @EmployeeId = '''' OR @EmployeeId IS NULL THEN '', NULL)'' ELSE '', '' + @EmployeeId + '')'' END)
			INSERT INTO @ArmisTable
				EXEC(@SQLQuery)
  		SET @SQLQuery = ''SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END,''
  		SET @SQLQuery = @SQLQuery + '' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''''''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''''''), REPLACE(LD.Name, ''''&amp;'''', ''''&''''),''
  		SET @SQLQuery = @SQLQuery + '' REPLACE(T.TitleName, ''''&amp;'''', ''''&''''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''''-''''), ISNULL(PD.OutTime, ''''-''''),''
  		SET @SQLQuery = @SQLQuery + '' ISNULL(PD.HrsWork, ''''-''''), ((SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 4, 2))),''
		SET @SQLQuery = @SQLQuery + '' (S.Shift_ShortName + '''' ('''' + S.Shift_StartTime + '''' - ''''  + S.Shift_EndTime + '''')''''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' (CASE WHEN (ISNULL(PD.BreakIn, '''''''') = '''''''' OR ISNULL(PD.BreakOut, '''''''') = '''''''') AND PD.BreakHours <> ''''00:00'''' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(''''00:05'''', ''''00:05'''')),ISNULL(''''00:05'''', ''''00:05''''), NULL FROM Ta_Tbl_Employee E''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id''    
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId''   
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId ''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpPay TEP ON TEP.EffectiveDate = EP.EffectiveDate AND TEP.EmployeeId = EP.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, '''''' + CAST(@FromDate AS NVARCHAR(11)) + '''''', 102) AND PD.Date <= CONVERT(DATETIME, '''''' + CAST(@ToDate AS NVARCHAR(11)) + '''''', 102)))''
		IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel + ''''
		END
		IF NOT(@EmployeeName = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_FirstName + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName +''%'' AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmployeeId='''')  
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''')''
		END
		IF NOT(@EmpSwipeCard = '''')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND E.SwipeCardNo = '''''' + @EmpSwipeCard + ''''''''
		END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		IF(@EmpAutoId = 0)
		BEGIN
			IF NOT(@LevelID = '''' OR @LevelID = ''0'')  
			BEGIN
				SET @SQLQuery = @SQLQuery + '' AND (TEL.levelId IN ('' + @LevelID + ''))''  
			END
		END
		ELSE
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds))''
		END
		SET @SQLQuery = @SQLQuery + '' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)''   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = ''Saturday'' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != ''Sunday''
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = CASE WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 1 ELSE 0 END FROM #TempAttendanceSummary TAS
				INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
				INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  				INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), ''.'', '':'') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + '':'' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, ''.'', '':'') AS ArmisWorkHours,
			REPLACE([Leave_Permision], ''.'', '':'') AS [Leave_Permision],
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((DeviationHours/60) AS VARCHAR(25)) ELSE CAST((DeviationHours/60) AS VARCHAR(25)) END + '':'' + CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((DeviationHours%60) AS VARCHAR(25)) ELSE CAST((DeviationHours%60) AS VARCHAR(25)) END AS DeviationHours
		 INTO #TempFinalResult FROM #TempAttendanceSummary	WHERE (@Deviation = 1 AND DeviationHours != 0) OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		SET @SQLQuery = ''UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_'' + @WeekName + '' = TR.TargetWorkHours,
							ActualWorkHours_'' + @WeekName + '' = TR.ActualWorkHours,
							ArmisWorkHours_'' + @WeekName + '' = TR.ArmisWorkHours,
							[Leave_Permision_'' + @WeekName + ''] = TR.[Leave_Permision],
							DeviationHours_'' + @WeekName + '' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName''
		EXEC(@SQLQuery)
		SET @SQLQuery = ''INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_'' + @WeekName + '', ActualWorkHours_'' + @WeekName + '', ArmisWorkHours_'' + @WeekName + '', [Leave_Permision_'' + @WeekName + ''], DeviationHours_'' + @WeekName + '')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL''
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory
		DROP TABLE #EmpPay		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE FinalAttendanceSummary
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptMonthlyDeviationHrs]    Script Date: 03/25/2021 10:22:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptMonthlyDeviationHrs]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name	:	Proc_TA_RptMonthlyDeviationHrs
Created By			:	A.K.T.MOORTHI
Created On			:	17-May-2013
Description		:	Get Monthly Deviation Work Hrs
exec [Proc_TA_RptMonthlyDeviationHrs] 
@FromDate=N''06/jun/2016'',@ToDate=N''02/jul/2016'',@EmployeeName=N'''',@LevelID=N''0'',@EmployeeID=N''787,956,916,926,801'',@EmployeeCategory=0,
@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpSwipeCard=N'''',@EmpAutoId=0,@Deviation=0,@ParentId=0
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptMonthlyDeviationHrs]
	@FromDate DATETIME,
	@ToDate DATETIME,
	@EmployeeName VARCHAR(50),
	@LevelID VARCHAR(8000),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(250),
	@GradeLevel VARCHAR(20),
	@EmpSwipeCard VARCHAR(20),
	@EmpAutoId BIGINT,
	@Deviation BIT,
    @ParentId INT
AS  
BEGIN  
	SET NOCOUNT ON
	DECLARE @SQLQuery VARCHAR(MAX), @Count INT, @WeekName VARCHAR(10);
	DECLARE @WeekCount INT, @TableColumns VARCHAR(MAX) = '''', @Query VARCHAR(MAX), @I INT = 1;
	DECLARE @WeekDays TABLE(Id INT IDENTITY(1,1), WeekDates DATETIME);
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)
	CREATE TABLE #LevelRights(LevelId INT)		
	CREATE TABLE #EmployeeIds(EmpAutoId INT);
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId);
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId);
	INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
			--To split up the comma separated values			
	if(@EmployeeId is not null and @EmployeeId <> '''')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from dbo.SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDate AND @ToDate
	GROUP BY EmployeeCodeId, [Date];
	WITH WeekDays AS(
		SELECT CI = 0
		UNION ALL
		SELECT CI+1 FROM WeekDays WHERE CI < DATEDIFF(D, @FromDate, @ToDate)
	)
	INSERT INTO @WeekDays
		SELECT DATEADD(D, (CI), @FromDate) FROM WeekDays WHERE DATENAME(DW, DATEADD(D, (CI), @FromDate)) != ''Sunday'' ORDER BY CI;
	SELECT @WeekCount = COUNT(WeekDates)/ 6 FROM @WeekDays;
	WITH WeekName AS(
		SELECT WNI = 1
		UNION ALL
		SELECT WNI+1 FROM WeekName WHERE WNI < @WeekCount
	)
	SELECT @WeekName = ''Week'' + CAST(@I AS VARCHAR(10)), @TableColumns = @TableColumns + '', TargetWorkHours_'' + @WeekName + '' VARCHAR(10), ActualWorkHours_'' + @WeekName + '' VARCHAR(10), ArmisWorkHours_'' + @WeekName + '' VARCHAR(10), [Leave_Permision_'' + @WeekName + ''] VARCHAR(10), DeviationHours_'' + @WeekName + '' VARCHAR(30)'', @I = @I + 1 FROM WeekName
	IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''FinalAttendanceSummary'')
	BEGIN
		DROP TABLE [dbo].[FinalAttendanceSummary]
	END
	EXEC(''CREATE TABLE FinalAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50)'' + @TableColumns + '')'')
	SET @I = 1
	WHILE @I <= @WeekCount
	BEGIN
		SET @WeekName = ''Week'' + CAST(@I AS VARCHAR(10))
		SELECT 
			@FromDate = Tbl1.WeekDates,
			@ToDate = Tbl2.WeekDates FROM (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 1) Tbl1
					INNER JOIN (
				SELECT ROW_NUMBER()OVER(ORDER BY WeekDates) Id, WeekDates FROM @WeekDays WHERE Id %6 = 0) Tbl2 ON Tbl2.Id = Tbl1.Id
			WHERE Tbl1.Id = @I		
		CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
		CREATE TABLE #TempAttendanceDetails (FNAttendanceCode NVARCHAR(15), ANAttendanceCode NVARCHAR(15), Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), LevelName NVARCHAR(250), Designation NVARCHAR(250), [Date] VARCHAR(20), InTime VARCHAR(20), OutTime VARCHAR(20), HrsWork VARCHAR(20), TotalMinsWorked VARCHAR(20), Shift_ShortName VARCHAR(100), shift_TotalWorkingHours VARCHAR(50), LunchHours VARCHAR(50), DefinedWorkHours VARCHAR(20), [Day] VARCHAR(20), ValidWorkHrs BIT, ValidLunchHrs BIT, CategoryId INT, CategoryName NVARCHAR(50), ThirdSat BIT, ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10))
		CREATE TABLE #TempAttendanceSummary (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), CategoryName NVARCHAR(50), 
		DefinedWorkHours DECIMAL(18,2), TargetWorkHours DECIMAL(18,2), ActualWorkHours INT, 
		ArmisWorkHours DECIMAL(18,2), [Leave_Permision] DECIMAL(18,2), DeviationHours INT, MaxDate DATE, ArmisDeviationHrs int)
		DECLARE @ArmisTable TABLE (Employee_Code_Id NVARCHAR(10), EmployeeName NVARCHAR(250), ProjTask DECIMAL(18,2), OrgTask DECIMAL(18,2), TotalTask DECIMAL(18,2) )
		DECLARE @FirstSat DATE, @ThirdSat DATE
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
		(
			[LevelId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
		(
			[DesignationId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
		(
			[EffectiveDate] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
		(
			[TypeId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
		(
			[EmployeeId] ASC
		)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
		CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
		(
			[EffectiveDate] ASC
		)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
		CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
		(
			[CategoryId] ASC
		) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
		CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
		(
			[EmployeeId] ASC
		) ON [PRIMARY]
--Employee Level insert in Temporary table
		Declare @sqlCommon nvarchar(4000)
	set @sqlCommon=''''
	If Not (@EmployeeId = '''')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id ''
			End
	If Not (@EmployeeName = '''')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id ''
			End		
	DECLARE @sqlEmpLevel nVARCHAR(4000)	
	SET @sqlEmpLevel=
	''INSERT INTO #EmpLevel 	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from	(
	SELECT	max(el.EffectiveDate) as EffectiveDate,	el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId ''
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +'' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@ToDate as nVARCHAR(50))+'''''', 102) and EL.LevelId is not null''			
	EXECUTE(@sqlEmpLevel)	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @ToDate,@EmployeeId,''''	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @ToDate,@EmployeeId,@employeeType	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @ToDate,@EmployeeId,@employeeCategory
			--SET @SQLQuery = ''SELECT * FROM 
			--[ProjectManagementV3].[dbo].[Fn_GetProgressReport]('''''' + CAST(@FromDate AS VARCHAR(20)) + '''''','''''' + CAST(@ToDate AS VARCHAR(20)) + '''''''' + (CASE WHEN @EmployeeId = '''' OR @EmployeeId IS NULL THEN '', NULL)'' ELSE '', '' + @EmployeeId + '')'' END)
			--INSERT INTO @ArmisTable
			--EXEC(@SQLQuery)			
			--select * from @ArmisTable
  		SET @SQLQuery = ''SELECT PD.FNAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END, PD.ANAttendanceCode + CASE WHEN Status IS NULL THEN '''''''' ELSE ''''(BL)'''' END,''
  		SET @SQLQuery = @SQLQuery + '' E.Employee_Code_Id, ISNULL(E.Employee_FirstName, '''''''') +  SPACE(1) + ISNULL(E.Employee_LastName, ''''''''), REPLACE(LD.Name, ''''&amp;'''', ''''&''''),''
  		SET @SQLQuery = @SQLQuery + '' REPLACE(T.TitleName, ''''&amp;'''', ''''&''''), CONVERT(VARCHAR(11), PD.Date, 101), ISNULL(PD.InTime, ''''-''''), ISNULL(PD.OutTime, ''''-''''),''
  		SET @SQLQuery = @SQLQuery + '' ISNULL(PD.HrsWork, ''''-''''), ((SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 0, 3)*60) + (SUBSTRING(ISNULL(PD.HrsWork, ''''00:00''''), 4, 2))),''
		SET @SQLQuery = @SQLQuery + '' (S.Shift_ShortName + '''' ('''' + S.Shift_StartTime + '''' - ''''  + S.Shift_EndTime + '''')''''), S.shift_TotalWorkingHours, ISNULL(PD.BreakHours, ''''-''''),''
		SET @SQLQuery = @SQLQuery + '' C.MonToSat_WorkHrs, DATENAME(DW, PD.Date), (CASE WHEN ISNULL(C.WeekDay_WorkHrs, 0.0) > CAST(REPLACE(ISNULL(PD.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)) THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' (CASE WHEN (ISNULL(PD.BreakIn, '''''''') = '''''''' OR ISNULL(PD.BreakOut, '''''''') = '''''''') AND PD.BreakHours <> ''''00:00'''' AND PD.BreakHours IS NOT NULL THEN 1 ELSE 0 END),''
		SET @SQLQuery = @SQLQuery + '' C.CategoryId, C.CategoryName, 0, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')),ISNULL(SS.MaxWorkPlaceInHours, ''''00:10''''), NULL FROM Ta_Tbl_Employee E''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_ProcessedData PD ON E.SwipeCardNo = PD.Employee_Code_Id''    
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeLevel EL ON E.Employee_Id = EL.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN Ta_Tbl_levelDetails LD ON EL.LevelId = LD.Id''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeDesignation ED ON E.Employee_Id = ED.EmployeeID''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Title T ON ED.DesignationId = T.TitleId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId''   
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeeType ET ON E.Employee_Id = ET.EmployeeId''
  		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_Type Ty ON ET.TypeId = Ty.TypeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN TA_Tbl_EmployeePay EP ON E.Employee_Id = EP.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN Ta_tbl_Shift S ON PD.Shift_ID = S.Shift_Id''
		SET @SQLQuery = @SQLQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON S.Level_Id = SS.CompanyId ''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpLevel TEL ON TEL.EffectiveDate = EL.EffectiveDate AND TEL.Employeeid = EL.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpDesignation TED ON TED.EffectiveDate = ED.EffectiveDate AND TED.Employeeid = ED.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpType TET ON TET.EffectiveDate = ET.EffectiveDate AND TET.Employeeid = ET.EmployeeId''
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #EmpCategory TEC ON TEC.EffectiveDate = EC.EffectiveDate AND TEC.Employeeid = EC.EmployeeId''		
		SET @SQLQuery = @SQLQuery + '' INNER JOIN #LevelRights LR ON LR.LevelId = TEL.LevelId ''		
		If Not (@EmployeeId = '''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End	
  		SET @SQLQuery = @SQLQuery + '' WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 AND ((PD.date >= CONVERT(DATETIME, '''''' + CAST(@FromDate AS NVARCHAR(11)) + '''''', 102) AND PD.Date <= CONVERT(DATETIME, '''''' + CAST(@ToDate AS NVARCHAR(11)) + '''''', 102)))''
		IF(@UserGroupName <> ''SuperAdmin'')
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND G.Grade_Level >= '' + @GradeLevel + ''''
		END	 
		if(@isReportingto > 0)
            BEGIN
               set @SQLQuery = @SQLQuery + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
		IF(@employeeCategory <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND EC.CategoryId = '' + CAST(@employeeCategory AS NVARCHAR(8)) 
		END
		IF(@employeeType <> 0)
		BEGIN
			SET @SQLQuery = @SQLQuery + '' AND ET.TypeId = '' + CAST(@employeeType AS NVARCHAR(8)) 
		END
		SET @SQLQuery = @SQLQuery + '' ORDER BY E.Employee_FirstName, CAST(PD.Date AS DATETIME)''   
		INSERT INTO #TempAttendanceDetails EXEC(@SQLQuery) 
		UPDATE #TempAttendanceDetails SET
			HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
			TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END)
		FROM #TempAttendanceDetails AD
			RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Code_Id AND EH.[Date] = AD.[Date] 
		SELECT @Count = COUNT(DISTINCT [DAY]) FROM #TempAttendanceDetails  
		SELECT @FirstSat = DATEADD(dd, (DATEDIFF(dd, -53685,DATEADD(mm, DATEDIFF(mm, 0, @ToDate) ,6))/7)*7,-53685), @ThirdSat = DATEADD(dd, 14, @FirstSat)
		UPDATE #TempAttendanceDetails SET ThirdSat = 1 	 
			WHERE #TempAttendanceDetails.Day = ''Saturday'' AND #TempAttendanceDetails.Date = @ThirdSat
		 INSERT INTO #TempAttendanceSummary
			SELECT
				TA.Employee_Code_Id,
				TA.EmployeeName,
				TA.CategoryName,
				TA.DefinedWorkHours,
				TA.DefinedWorkHours - SUM(
					(((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					  (CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
					CASE WHEN C.Sat_WorkHrs > 4 THEN 
						((CASE WHEN (TA.FNAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
						(CASE WHEN (TA.ANAttendanceCode IN(''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
						ELSE 
							0.0
						END
					) * 8,
				SUM(CAST(TA.TotalMinsWorked AS INT)),
				0,
				SUM(
				(((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
				  (CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] != ''Saturday'')) THEN 0.5 ELSE 0.0 END))) +
				CASE WHEN C.Sat_WorkHrs > 4 THEN 
					((CASE WHEN (TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END) + 
					(CASE WHEN (TA.ANAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'') AND (TA.[Day] = ''Saturday'')) THEN 0.5 ELSE 0.0 END))
					WHEN C.Sat_WorkHrs = 2 THEN 
						(CASE 
						WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'' ,''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' AND TA.thirdSat<>1) THEN C.Sat_WorkHrs/8.0
						WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
						 0.0 END)
					ELSE 
						(CASE
							WHEN (((TA.FNAttendanceCode NOT IN(''Present'', ''Absent'', ''Weekly Off'', ''Holiday'')) OR (TA.ANAttendanceCode NOT IN (''Present'', ''Absent'', ''Weekly Off'',''Holiday''))) AND TA.[Day] = ''Saturday'' ) THEN C.Sat_WorkHrs/8.0 
							WHEN TA.FNAttendanceCode = ''Holiday'' AND TA.ANAttendanceCode = ''Holiday'' AND TA.[Day] = ''Saturday'' THEN 1.0 ELSE
							0.0 END
						)
					END
				) * 8,
				0,
				CAST(MAX(TA.[Date]) AS DATE),
				0
			FROM #TempAttendanceDetails TA
				INNER JOIN TA_Tbl_Category C ON C.CategoryId = TA.CategoryId
			WHERE [Day] != ''Sunday''
			GROUP BY TA.Employee_Code_Id, TA.EmployeeName, TA.DefinedWorkHours, TA.CategoryName
			UPDATE #TempAttendanceSummary SET DeviationHours = (((TargetWorkHours * 60) - ActualWorkHours) - ([Leave_Permision] * 60))
			UPDATE #TempAttendanceSummary SET DeviationHours = 0 WHERE DeviationHours <= CAST(0 AS DECIMAL(18,2))
			UPDATE #TempAttendanceSummary SET ArmisWorkHours = ISNULL(A.TotalTask, 0)FROM #TempAttendanceSummary TAS
				INNER JOIN @ArmisTable A ON A.Employee_Code_Id = TAS.Employee_Code_Id
			UPDATE #TempAttendanceSummary SET ArmisDeviationHrs = 
			--select 
			--ArmisWorkHours , [Leave_Permision], ((DefinedWorkHours - TargetWorkHours)) , ISNULL(C.ARMIS_WorkHrs, 0.0),
			CASE	WHEN (ArmisWorkHours + [Leave_Permision] + (DefinedWorkHours - TargetWorkHours)) < ISNULL(C.ARMIS_WorkHrs, 0.0) THEN 
					 (ISNULL(C.ARMIS_WorkHrs, 0.0)*60)-	(
															(
																substring(convert(varchar(10),ArmisWorkHours),0,CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours)))*60
																+
																substring(convert(varchar(10),ArmisWorkHours),CHARINDEX(''.'',convert(varchar(10),ArmisWorkHours))+1,LEN(convert(varchar(10),ArmisWorkHours)))
																+ 
																[Leave_Permision] *60
																+ 
																(DefinedWorkHours - TargetWorkHours)*60
															)
														)
					ELSE 0 
			END 
			FROM #TempAttendanceSummary TAS
			INNER JOIN Ta_Tbl_Employee E ON E.Employee_Code_Id = TAS.Employee_Code_Id
			INNER JOIN TA_Tbl_EmployeeCategory EC ON E.Employee_Id = EC.EmployeeId
  			INNER JOIN TA_Tbl_Category C ON EC.CategoryId = C.CategoryId
  			--where E.Employee_Code_Id=''787''
		 SELECT 
			@WeekName AS WeekName,
			Employee_Code_Id,
			EmployeeName,
			CategoryName,
			REPLACE((TargetWorkHours - [Leave_Permision]), ''.'', '':'') AS TargetWorkHours,
			CASE WHEN LEN(CAST((ActualWorkHours/60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours/60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours/60) AS VARCHAR(25)) END + '':'' + CASE  WHEN LEN(CAST((ActualWorkHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ActualWorkHours%60) AS VARCHAR(25)) ELSE CAST((ActualWorkHours%60) AS VARCHAR(25)) END AS ActualWorkHours,
			REPLACE(ArmisWorkHours, ''.'', '':'') AS ArmisWorkHours,
			REPLACE([Leave_Permision], ''.'', '':'') AS [Leave_Permision],
			''T:''+
			CASE WHEN LEN(CAST((DeviationHours/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((DeviationHours/60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((DeviationHours%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((DeviationHours%60) AS VARCHAR(25)) 
				 ELSE CAST((DeviationHours%60) AS VARCHAR(25)) 
			END +SPACE(1.5)+
			''A:''+
			CASE WHEN LEN(CAST((ArmisDeviationHrs/60) AS VARCHAR(25)))=1 THEN ''0'' + CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs/60) AS VARCHAR(25)) 
			END + '':'' + 
			CASE WHEN LEN(CAST((ArmisDeviationHrs%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
				 ELSE CAST((ArmisDeviationHrs%60) AS VARCHAR(25)) 
			END 
			AS DeviationHours
		 INTO #TempFinalResult 
		 FROM #TempAttendanceSummary	
		 WHERE 		 
		 (@Deviation = 1 AND DeviationHours != 0) 
		 OR (@Deviation = 1 AND ArmisDeviationHrs != 0) OR (@Deviation = 0 AND 1=1) 
		--select * from #TempFinalResult
		SET @SQLQuery = ''UPDATE FinalAttendanceSummary SET 
							Employee_Code_Id = TR.Employee_Code_Id,
							EmployeeName = TR.EmployeeName,
							CategoryName = TR.CategoryName,
							TargetWorkHours_'' + @WeekName + '' = TR.TargetWorkHours,
							ActualWorkHours_'' + @WeekName + '' = TR.ActualWorkHours,
							ArmisWorkHours_'' + @WeekName + '' = TR.ArmisWorkHours,
							[Leave_Permision_'' + @WeekName + ''] = TR.[Leave_Permision],
							DeviationHours_'' + @WeekName + '' = TR.DeviationHours FROM FinalAttendanceSummary FAS
						INNER JOIN #TempFinalResult TR ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName''
		EXEC(@SQLQuery)
		SET @SQLQuery = ''INSERT INTO FinalAttendanceSummary(Employee_Code_Id, EmployeeName, CategoryName, TargetWorkHours_'' + @WeekName + '', ActualWorkHours_'' + @WeekName + '', ArmisWorkHours_'' + @WeekName + '', [Leave_Permision_'' + @WeekName + ''], DeviationHours_'' + @WeekName + '')
							SELECT TR.Employee_Code_Id, TR.EmployeeName, TR.CategoryName, TR.TargetWorkHours, TR.ActualWorkHours, TR.ArmisWorkHours, TR.[Leave_Permision], TR.DeviationHours FROM #TempFinalResult TR
								LEFT JOIN FinalAttendanceSummary FAS ON TR.Employee_Code_Id = FAS.Employee_Code_Id AND TR.CategoryName = FAS.CategoryName
							WHERE FAS.Employee_Code_Id IS NULL AND FAS.CategoryName IS NULL''
		EXEC(@SQLQuery)
		DROP TABLE #EmpLevel
		DROP TABLE #EmpDesignation
		DROP TABLE #EmpType
		DROP TABLE #EmpCategory		
		DROP TABLE #TempAttendanceDetails
		DROP TABLE #TempAttendanceSummary
		DROP TABLE #TempFinalResult
		DELETE FROM @ArmisTable
		SET @I = @I + 1
	END
	SELECT * FROM FinalAttendanceSummary
	DROP TABLE #EmployeeIds
	DROP TABLE #LevelRights
	DROP TABLE FinalAttendanceSummary
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference_email]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptFirstInPunchDifference_email]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference_email]
	@FromDate DATETIME,  
	@ToDate DATETIME,  
	@EmployeeName VARCHAR(250),  
	@LevelID VARCHAR(MAX),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(20),
	@GradeLevel VARCHAR(20),
	@EmpAutoId BIGINT,
	@MaxWorkPlaceIn NVARCHAR(5),
	@PunchType VARCHAR(40)
AS  
BEGIN  
Set @LevelID=''107,108,109,110,111,112,113,114,115,123'';
--Temporary table''s creation
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #ExceptionEmployeeIds(EmployeeId INT, ExceptionDate DATETIME, ExceptionHours BIGINT)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId)
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel
		SELECT Elevel.EmployeeId, EL.levelId,Elevel.EffectiveDate FROM(
			SELECT MAX(el.EffectiveDate) AS EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel el
				INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) ELevel
		INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate = ELevel.EffectiveDate AND EL.employeeid = ELevel.EmployeeId AND
		EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
		SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate FROM(
			SELECT MAX(ed.EffectiveDate) AS EffectiveDate, ed.EmployeeId FROM TA_Tbl_EmployeeDesignation ed
				INNER JOIN ta_tbl_employee emp ON ed.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EDesig
		INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND ED.employeeid = EDesig.EmployeeId AND
		ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType
		SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
			SELECT MAX(et.EffectiveDate) AS EffectiveDate, et.EmployeeId FROM TA_Tbl_EmployeeType et
				INNER JOIN ta_tbl_employee emp ON et.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpType
		INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId AND
		EType.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
		SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
			SELECT MAX(ec.EffectiveDate) AS EffectiveDate, ec.EmployeeId FROM TA_Tbl_EmployeeCategory ec
				INNER JOIN ta_tbl_employee emp ON ec.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpCategory
		INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate AND ECategory.employeeid = EmpCategory.EmployeeId AND
		ECategory.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ECategory.CategoryId IS NOT NULL
	INSERT INTO #ExceptionEmployeeIds
		SELECT IPD.EmployeeCodeId, IPD.[Date], SUM(IPD.PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference IPD
			WHERE IPD.[Date] BETWEEN CONVERT(DATETIME, CAST(@FromDate AS VARCHAR(11)), 102) AND CONVERT(DATETIME, CAST(@ToDate AS VARCHAR(11)), 102) 
		GROUP BY IPD.[Date], IPD.EmployeeCodeId HAVING SUM(IPD.PunchDifferenceMins) > DATEDIFF(MI, ''00:00'', ISNULL(@MaxWorkPlaceIn, ''00:03''))
	DECLARE @Query VARCHAR(MAX)
	SET @Query = ''SELECT IPD.[Date], IPD.EmployeeCodeId, ISNULL(E.Employee_FirstName, '''''''') + SPACE(1) + ISNULL(E.Employee_LastName, '''''''') AS EmployeeName, IPD.EntranceName, ''
	SET @Query = @Query + ''IPD.EntranceType, IPD.EntranceTime, ISNULL(IPD.FloorName, ''''?'''') FloorName, ISNULL(IPD.FloorType, ''''?'''') FloorType, ISNULL(IPD.FloorTime, ''''?'''') FloorTime, (CASE WHEN IPD.PunchDifference = ''''23:59'''' THEN ''''?'''' ELSE IPD.PunchDifference END) PunchDifference, IPD.PunchDifferenceMins FROM TA_VW_FirstInPunchDifference IPD ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = IPD.EmployeeCodeId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Title T ON T.TitleId = ED.DesignationId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeCategory EC ON EC.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeType ET ON ET.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN #EmpLevel TL ON TL.EffectiveDate = EL.EffectiveDate AND TL.EmployeeId = EL.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpType TT ON TT.EffectiveDate = ET.EffectiveDate AND TT.EmployeeId = ET.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpDesignation TD ON TD.EffectiveDate = ED.EffectiveDate AND TD.EmployeeId = ED.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpCategory TC ON TC.EffectiveDate = EC.EffectiveDate AND TC.EmployeeId = EC.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #ExceptionEmployeeIds ExEmp ON ExEmp.ExceptionDate = IPD.[Date] AND ExEmp.EmployeeId = IPD.EmployeeCodeId ''
	--SET @Query = @Query + ''WHERE IPD.PunchDifference > '''''' + ISNULL(@MaxWorkPlaceIn, ''00:03'') + '''''' AND E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 ''
	SET @Query = @Query + ''WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 ''
	SET @Query = @Query + ''AND IPD.[Date] BETWEEN CONVERT(DATETIME, '''''' + CAST(@FromDate AS VARCHAR(11)) + '''''', 102) AND CONVERT(DATETIME, '''''' + CAST(@ToDate AS VARCHAR(11)) + '''''', 102) ''
	IF(@UserGroupName <> ''SuperAdmin'')
	BEGIN
		SET @Query = @Query + CASE WHEN @EmpAutoId != 0 THEN ''AND G.Grade_Level >= '' + @GradeLevel + '' AND (E.Reporting_To = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''' OR E.Leave_Sanc_Authority = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''' OR E.Employee_Id = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''') ''
													ELSE ''AND (G.Grade_Level >= '' + @GradeLevel + '' OR E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''') '' END 
	END 
	IF NOT(@EmployeeName = '''')  
	BEGIN
		SET @Query = @Query + ''AND (E.Employee_FirstName + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName + ''%'' AS NVARCHAR(100)) + '''''') ''
	END
	IF NOT(@EmployeeId = '''')
	BEGIN
		SET @Query = @Query + ''AND (E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''') ''
	END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @Query = @Query + ''AND EC.CategoryId = '' + CAST(@EmployeeCategory AS NVARCHAR(8)) + '' ''
	END
	IF(@EmployeeType <> 0)
	BEGIN
		SET @Query = @Query + ''AND ET.TypeId = '' + CAST(@EmployeeType AS NVARCHAR(8)) + '' ''
	END
	IF(@PunchType <> '''')
	BEGIN
		SET @Query = @Query + ''AND IPD.EntranceType IN('' + @PunchType + '') ''
	END	
    IF((@EmpAutoId = 0) AND (NOT(@LevelID = '''' OR @LevelID = ''0'')))
	BEGIN
		SET @Query = @Query + ''AND (TL.levelId IN ('' + @LevelID + '')) ''
	END
	ELSE
	BEGIN
		SET @Query = @Query + ''AND (E.Employee_ID IN (SELECT * FROM #EmployeeIds)) ''  
	END	
	SET @Query = @Query + ''ORDER BY IPD.[Date], IPD.EmployeeCodeId''
	EXEC(@Query)
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory	
	DROP TABLE #EmployeeIds		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptFirstInPunchDifference]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptFirstInPunchDifference]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Procedure Name		:	Proc_TA_RptFirstInPunchDifference
Created By				:	A.K.T.MOORTHI
Created on				:	11-Jun-2014
Description			:	To Get the Employee Shift-In, Break-In, Lunch-In Punch With Work Place In Punch Difference
EXEC Proc_TA_RptFirstInPunchDifference 
	@EmployeeID=N'''',@LevelID=N''0'',@FromDate=N''02/Jun/2014'',@ToDate=N''07/Jun/2014'',@EmployeeName=N''Karthi'',
	@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',@EmpAutoId=0,@MaxWorkPlaceIn=N''00:00'',
	@PunchType = N'''', @ParentId = 0
	exec Proc_TA_RptFirstInPunchDifference @FromDate=N''01/Jan/2015'',@ToDate=N''30/Jan/2015'',@EmployeeName=N'''',
	@LevelID=N''107'',@EmployeeID=N'''',@EmployeeCategory=0,@EmployeeType=0,@UserGroupName=N''SuperAdmin'',@GradeLevel=N''0'',
	@EmpAutoId=0,@MaxWorkPlaceIn=N'''',@PunchType=N''''''Shift In'''',''''Lunch In'''''',@ParentId=107
*/ 
CREATE PROCEDURE [dbo].[Proc_TA_RptFirstInPunchDifference]
	@FromDate DATETIME,  
	@ToDate DATETIME,  
	@EmployeeName VARCHAR(250),  
	@LevelID VARCHAR(MAX),
	@EmployeeId VARCHAR(50),
	@EmployeeCategory INT,
	@EmployeeType INT,
	@UserGroupName VARCHAR(20),
	@GradeLevel VARCHAR(20),
	@EmpAutoId BIGINT,
	@MaxWorkPlaceIn NVARCHAR(5),
	@PunchType VARCHAR(40)
AS  
BEGIN  
Set @LevelID=''107,108,109,110,111,112,113,114,115,123'';
--Temporary table''s creation
	CREATE TABLE #EmpLevel(EmployeeId INT, LevelId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpDesignation(EmployeeId INT, DesignationId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpType(EmployeeId INT, TypeId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmpCategory(EmployeeId INT, CategoryId INT, EffectiveDate DATETIME)
	CREATE TABLE #EmployeeIds(EmpAutoId INT)
	CREATE TABLE #ExceptionEmployeeIds(EmployeeId VARCHAR(100), ExceptionDate DATETIME, ExceptionHours BIGINT)
	--CREATE TABLE #LevelRights(LevelId INT)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId)
	INSERT INTO #EmployeeIds SELECT * FROM [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId)
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	--INSERT INTO #LevelRights SELECT * FROM [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID)
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_LevelId] ON [dbo].[#EmpLevel] 
	(
		[LevelId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpLevel] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_LevelId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_DesignationId] ON [dbo].[#EmpDesignation] 
	(
		[DesignationId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpDesignation] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_TypeId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_TypeId] ON [dbo].[#EmpType] 
	(
		[TypeId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpType] 
	(
		[EmployeeId] ASC
	)ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate] ASC
	)ON [PRIMARY]
/****** Object:  Index [IDX_CategoryId]    Script Date: 05/27/2009 16:28:18 ******/
	CREATE NONCLUSTERED INDEX [IDX_CategoryId] ON [dbo].[#EmpCategory] 
	(
		[CategoryId] ASC
	) ON [PRIMARY]
/****** Object:  Index [IDX_EmployeeId]    Script Date: 05/27/2009 16:27:55 ******/
	CREATE NONCLUSTERED INDEX [IDX_EmployeeId] ON [dbo].[#EmpCategory] 
	(
		[EmployeeId] ASC
	) ON [PRIMARY]
--Employee Level insert in Temporary table
	INSERT INTO #EmpLevel
		SELECT Elevel.EmployeeId, EL.levelId,Elevel.EffectiveDate FROM(
			SELECT MAX(el.EffectiveDate) AS EffectiveDate, EmployeeId FROM TA_Tbl_EmployeeLevel el
				INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) ELevel
		INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate = ELevel.EffectiveDate AND EL.employeeid = ELevel.EmployeeId AND
		EL.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EL.LevelId IS NOT NULL
	--Employee Designation insert in Temporary table
	INSERT INTO #EmpDesignation
		SELECT EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate FROM(
			SELECT MAX(ed.EffectiveDate) AS EffectiveDate, ed.EmployeeId FROM TA_Tbl_EmployeeDesignation ed
				INNER JOIN ta_tbl_employee emp ON ed.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EDesig
		INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EffectiveDate = EDesig.EffectiveDate AND ED.employeeid = EDesig.EmployeeId AND
		ED.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ED.DesignationId IS NOT NULL
	--Employee Type insert in Temporary table
	INSERT INTO #EmpType
		SELECT EmpType.EmployeeId, EType.TypeId, EmpType.EffectiveDate FROM(
			SELECT MAX(et.EffectiveDate) AS EffectiveDate, et.EmployeeId FROM TA_Tbl_EmployeeType et
				INNER JOIN ta_tbl_employee emp ON et.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpType
		INNER JOIN TA_Tbl_EmployeeType EType ON EType.EffectiveDate = EmpType.EffectiveDate AND EType.employeeid = EmpType.EmployeeId AND
		EType.EffectiveDate <=CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND EType.TypeId IS NOT NULL
	--Employee Category insert in Temporary table
	INSERT INTO #EmpCategory
		SELECT EmpCategory.EmployeeId, ECategory.CategoryId, EmpCategory.EffectiveDate FROM(
			SELECT MAX(ec.EffectiveDate) AS EffectiveDate, ec.EmployeeId FROM TA_Tbl_EmployeeCategory ec
				INNER JOIN ta_tbl_employee emp ON ec.EmployeeId = emp.Employee_Id 
			WHERE emp.Isdeleted = 0 GROUP BY EmployeeId) EmpCategory
		INNER JOIN TA_Tbl_EmployeeCategory ECategory ON ECategory.EffectiveDate = EmpCategory.EffectiveDate AND ECategory.employeeid = EmpCategory.EmployeeId AND
		ECategory.EffectiveDate <= CONVERT(DATETIME, CAST(@ToDate AS NVARCHAR(50)), 102) AND ECategory.CategoryId IS NOT NULL
	INSERT INTO #ExceptionEmployeeIds
		SELECT IPD.EmployeeCodeId, IPD.[Date], SUM(IPD.PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference IPD
			WHERE IPD.[Date] BETWEEN CONVERT(DATETIME, CAST(@FromDate AS VARCHAR(11)), 102) AND CONVERT(DATETIME, CAST(@ToDate AS VARCHAR(11)), 102) 
		GROUP BY IPD.[Date], IPD.EmployeeCodeId HAVING SUM(IPD.PunchDifferenceMins) > DATEDIFF(MI, ''00:00'', ISNULL(@MaxWorkPlaceIn, ''00:03''))
	DECLARE @Query VARCHAR(MAX)
	SET @Query = ''SELECT IPD.[Date], IPD.EmployeeCodeId, ISNULL(E.Employee_FirstName, '''''''') + SPACE(1) + ISNULL(E.Employee_LastName, '''''''') AS EmployeeName, IPD.EntranceName, ''
	SET @Query = @Query + ''IPD.EntranceType, IPD.EntranceTime, ISNULL(IPD.FloorName, ''''?'''') FloorName, ISNULL(IPD.FloorType, ''''?'''') FloorType, ISNULL(IPD.FloorTime, ''''?'''') FloorTime, (CASE WHEN IPD.PunchDifference = ''''23:59'''' THEN ''''?'''' ELSE IPD.PunchDifference END) PunchDifference, IPD.PunchDifferenceMins FROM TA_VW_FirstInPunchDifference IPD ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Employee E ON E.Employee_Code_Id = IPD.EmployeeCodeId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeDesignation ED ON ED.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Title T ON T.TitleId = ED.DesignationId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_Grade G ON G.Grade_ID = T.GradeId ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeCategory EC ON EC.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN TA_Tbl_EmployeeType ET ON ET.EmployeeId = E.Employee_Id ''
	SET @Query = @Query + ''INNER JOIN #EmpLevel TL ON TL.EffectiveDate = EL.EffectiveDate AND TL.EmployeeId = EL.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpType TT ON TT.EffectiveDate = ET.EffectiveDate AND TT.EmployeeId = ET.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpDesignation TD ON TD.EffectiveDate = ED.EffectiveDate AND TD.EmployeeId = ED.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #EmpCategory TC ON TC.EffectiveDate = EC.EffectiveDate AND TC.EmployeeId = EC.EmployeeId ''
	SET @Query = @Query + ''INNER JOIN #ExceptionEmployeeIds ExEmp ON ExEmp.ExceptionDate = IPD.[Date] AND ExEmp.EmployeeId = IPD.EmployeeCodeId ''
	--SET @Query = @Query + ''INNER JOIN #LevelRights LR ON LR.LevelId = TL.LevelId ''		
	--SET @Query = @Query + ''WHERE IPD.PunchDifference > '''''' + ISNULL(@MaxWorkPlaceIn, ''00:03'') + '''''' AND E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 ''
	SET @Query = @Query + ''WHERE E.Isdeleted = 0 AND E.Report_Exclude = 0 AND E.Employee_Status = 1 ''
	SET @Query = @Query + ''AND IPD.[Date] BETWEEN CONVERT(DATETIME, '''''' + CAST(@FromDate AS VARCHAR(11)) + '''''', 102) AND CONVERT(DATETIME, '''''' + CAST(@ToDate AS VARCHAR(11)) + '''''', 102) ''
	IF(@UserGroupName <> ''SuperAdmin'')
	BEGIN
		SET @Query = @Query + CASE WHEN @EmpAutoId != 0 THEN ''AND G.Grade_Level >= '' + @GradeLevel + '' AND (E.Reporting_To = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''' OR E.Leave_Sanc_Authority = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''' OR E.Employee_Id = '''''' + CAST(@EmpAutoId AS VARCHAR(30)) + '''''') ''
													ELSE ''AND (G.Grade_Level >= '' + @GradeLevel + '' OR E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''') '' END 
	END 
	IF NOT(@EmployeeName = '''')  
	BEGIN
		SET @Query = @Query + ''AND (E.Employee_FirstName + '''' '''' + ISNULL(E.Employee_LastName, '''''''') LIKE '''''' + CAST(@EmployeeName + ''%'' AS NVARCHAR(100)) + '''''') ''
	END
	IF NOT(@EmployeeId = '''')
	BEGIN
		SET @Query = @Query + ''AND (E.Employee_Code_Id = '''''' + CAST(@EmployeeId AS NVARCHAR(100)) + '''''') ''
	END
	IF(@EmployeeCategory <> 0)
	BEGIN
		SET @Query = @Query + ''AND EC.CategoryId = '' + CAST(@EmployeeCategory AS NVARCHAR(8)) + '' ''
	END
	IF(@EmployeeType <> 0)
	BEGIN
		SET @Query = @Query + ''AND ET.TypeId = '' + CAST(@EmployeeType AS NVARCHAR(8)) + '' ''
	END
	IF(@PunchType <> '''')
	BEGIN
		SET @Query = @Query + ''AND IPD.EntranceType IN('' + @PunchType + '') ''
	END	
	IF(NOT(@LevelID = '''' OR @LevelID = ''0''))
		BEGIN
			SET @Query = @Query + '' AND (TL.levelId IN ('' + @LevelID + '')) ''
		END
	if(@isReportingto > 0)
            BEGIN
               set @Query = @Query + '' and (E.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	SET @Query = @Query + ''ORDER BY IPD.[Date], IPD.EmployeeCodeId''
	EXEC(@Query)
	--Remove the temporary tables here   
	DROP TABLE #EmpLevel
	DROP TABLE #EmpDesignation
	DROP TABLE #EmpType
	DROP TABLE #EmpCategory	
	DROP TABLE #EmployeeIds		
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation_New]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyDeviation_New]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
--select * from TA_Tbl_ProcessedData where Employee_Code_Id=''ang1'' and Date=''2013-05-03''
/*  
Procedure Name : Proc_TA_RptDailyDeviation_New 
Proc_TA_RptDailyDeviation_New ''06/01/2014'',''06/20/2014'','''',''0'','''',0,0,''SuperAdmin'',0,'''',''''
Tables  : TA_Tbl_Employee and TA_Tbl_ProcessedData  
Created By : Manjula .P     
Created on : 17-May-2013
Descriptions	: creating daily deviation report procedure based on monthly attendance report.
				: Kindly update this procedure when you update rptMonthlyAttendance procedure.
*/  
CREATE  PROCEDURE [dbo].[Proc_TA_RptDailyDeviation_New]  
 --@MinWorkHours as varchar(10), 
 @fromDat datetime,  
 @ToDat datetime,  
 @EmployeeName varchar(50),  
 @LevelID varchar(8000),
 @EmployeeId varchar(50),
 @employeeCategory int,
 @employeeType int,
 @UserGroupName varchar(20),
 @GradeLevel varchar(20),	   
 @EmpSwipeCard varchar(20),
 @EmpAutoId bigint
AS  
BEGIN  
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--Temporary table''s creation
create table #EmpLevel(EmployeeId int,LevelId int,EffectiveDate datetime)
create table #EmpDesignation(EmployeeId int,DesignationId int,EffectiveDate datetime)
create table #EmpType(EmployeeId int,TypeId int,EffectiveDate datetime)
create table #EmpCategory(EmployeeId int,CategoryId int,EffectiveDate datetime)
create table #EmpPay(EmployeeId int,PayId int,EffectiveDate datetime)
DECLARE @TempExecptionHrs TABLE(Employee_Code_Id BIGINT, [Date] DATETIME, TotalHrs BIGINT)
create table #EmpProcessedData(SwipeCardNo varchar(50),ProcessDate datetime,TotalWorkMins float)
--Temporary table to store the Employee Ids who are all mapped under the reproting to or sanctioning authority.
create table #EmployeeIds(EmpAutoId int)
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
--Employee Level Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
(
	[EffectiveDate],[LevelId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Designation Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
(
	[EffectiveDate],[DesignationId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Type Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
(
	[EffectiveDate],[TypeId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Category Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
(
	[EffectiveDate],[CategoryId],[EmployeeId] ASC
)ON [PRIMARY]
--Employee Basic Pay Indexes
/****** Object:  Index [IDX_Effective]    Script Date: 05/27/2009 16:28:22 ******/
CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpPay] 
(
	[EffectiveDate],[PayId],[EmployeeId] ASC
) ON [PRIMARY]
--Employee Level insert in Temporary table
insert into #EmpLevel select Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate from (
select max(el.EffectiveDate) as EffectiveDate,EmployeeId from TA_Tbl_EmployeeLevel el
inner join ta_tbl_employee emp on el.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) ELevel
inner join TA_Tbl_EmployeeLevel EL on EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
AND EL.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EL.LevelId is not null
--Employee Designation insert in Temporary table
insert into #EmpDesignation select EDesig.EmployeeId,ed.DesignationId,EDesig.EffectiveDate from (
select max(ed.EffectiveDate) as EffectiveDate,ed.EmployeeId as EmployeeId from TA_Tbl_EmployeeDesignation ed
inner join ta_tbl_employee emp on ed.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EDesig
inner join TA_Tbl_EmployeeDesignation ED on ED.EffectiveDate=EDesig.EffectiveDate and ED.employeeid=EDesig.EmployeeId
AND ED.EffectiveDate <= CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and ED.DesignationId is not null
--Employee Type insert in Temporary table
insert into #EmpType select EmpType.EmployeeId,EType.TypeId,EmpType.EffectiveDate from (
select max(et.EffectiveDate) as EffectiveDate,et.EmployeeId as EmployeeId from TA_Tbl_EmployeeType et
inner join ta_tbl_employee emp on et.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpType
inner join TA_Tbl_EmployeeType EType on EType.EffectiveDate=EmpType.EffectiveDate and EType.employeeid=EmpType.EmployeeId
AND EType.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)  and EType.TypeId is not null
--Employee Category insert in Temporary table
insert into #EmpCategory select EmpCategory.EmployeeId,ECategory.CategoryId,EmpCategory.EffectiveDate from (
select max(ec.EffectiveDate) as EffectiveDate,ec.EmployeeId as EmployeeId from TA_Tbl_EmployeeCategory ec
inner join ta_tbl_employee emp on ec.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpCategory
inner join TA_Tbl_EmployeeCategory ECategory on ECategory.EffectiveDate=EmpCategory.EffectiveDate and ECategory.employeeid=EmpCategory.EmployeeId
AND ECategory.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)   and ECategory.CategoryId is not null
--Employee Pay insert in Temporary table
insert into #EmpPay select EmpBpay.EmployeeId,EPay.PayId,EmpBpay.EffectiveDate from (
select max(ep.EffectiveDate) as EffectiveDate,ep.EmployeeId as EmployeeId from TA_Tbl_EmployeePay ep
inner join ta_tbl_employee emp on ep.EmployeeId = emp.Employee_Id 
where emp.Isdeleted=0 group by EmployeeId) EmpBpay
inner join TA_Tbl_EmployeePay EPay on EPay.EffectiveDate=EmpBpay.EffectiveDate and EPay.employeeid=EmpBpay.EmployeeId
AND EPay.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102) and EPay.PayId is not null
create table #Leave
(
EmpId int,
Leave_FromDate datetime,
Hrs varchar(20)
)
insert into #Leave
select E.Employee_Id ,Leave_FromDate,
case when LA.Status=''Approved'' then 	
 case when substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''.'',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))!=0
		then substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''.'',isnull(LA.NumberOfDays,0)))*8*60 + 
		4*60
	else
		substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''.'',isnull(LA.NumberOfDays,0)))*8*60 + 
 substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''.'',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))*4*60
 end
else
0 end
as [Leave Hrs] 
from TA_Tbl_Employee E 
left join TA_Tbl_LeaveApplication LA on LA.Employee_Id=E.Employee_Id 
left join TA_Tbl_ProcessedData pd on (pd.Date=LA.Leave_FromDate )
--inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id and EC.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)
where 
 convert(varchar(12),LA.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)  and
 LA.IsDeleted=0
and pd.Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--and (Permission_Status=''Approved'' or LA.Status=''Approved'')
group by E.Employee_Id ,E.Employee_Code_Id,NumberOfDays,Leave_FromDate,LA.Status
create table #Permission
(
EmpId int,
Permission_Date datetime,
Hrs  varchar(20)
)
insert into #Permission
select E.Employee_Id ,Permission_Date,
case when C.Sat_WorkHrs<8 then 0 else
case when P.Permission_Status=''Approved'' then 
 substring(Permission_Hours,0,charindex('':'',Permission_Hours))*60 + 
 substring(Permission_Hours,charindex('':'',Permission_Hours)+1,LEN(Permission_Hours))
else
0 
end
end
as [Permission Hrs] 
from TA_Tbl_Employee E 
inner join #EmpCategory on #EmpCategory.EmployeeId=E.Employee_Id
inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
left join  TA_Tbl_Permission P on P.Employee_Id=E.Employee_Id
left join TA_Tbl_ProcessedData pd on ( pd.Date=P.Permission_Date)
--inner join TA_Tbl_EmployeeCategory EC on EC.EmployeeId=E.Employee_Id and EC.EffectiveDate <=CONVERT(DATETIME,cast(@todat as nvarchar(50)), 102)
where 
 convert(varchar(12),P.Permission_Date,111)=convert(varchar(12), pd.Date,111)  and
 P.IsDeleted=0
and pd.Date between CONVERT(DATETIME,cast(@fromDat as nvarchar(50)), 102) and CONVERT(DATETIME,cast(@ToDat as nvarchar(50)), 102)
--and (Permission_Status=''Approved'' or LA.Status=''Approved'')
group by E.Employee_Id ,E.Employee_Code_Id,Permission_Date,P.Permission_Status,Permission_Hours,C.Sat_WorkHrs
--select * from #Leave
--select * from #Permission where EmpId=52
	CREATE TABLE #TempAttendanceDetails (FirstSession NVARCHAR(15), SecondSession NVARCHAR(15), Employee_Id NVARCHAR(10), empName NVARCHAR(250),
		BranchName NVARCHAR(250), Designation NVARCHAR(250), Date VARCHAR(20), InTime NVARCHAR(25), OutTime NVARCHAR(25), HrsWork NVARCHAR(10),
		Status NVARCHAR(50), TotalMinsWorked INT, Shift_ShortName VARCHAR(100), shift_TotalWorkingHours NVARCHAR(50), ValidWorkHrs BIT,
		WeekDayWrkHrs decimal(18,2),LeavePermissionHrs varchar(20),
		TargetWorkedHrs varchar(20),
		DeviationWorkedHrs varchar(20),
		EmployeeCategory nvarchar(50),
		TotaldeviationHrs varchar(20), ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10)
		)	
    declare @sqlQuery as varchar(max)  
  	set @sqlQuery=''''  
  	set @sqlQuery = ''select  pd.fnAttendanceCode + case  when pd.Status is null then '''''''' else ''''(BL)'''' end as FirstSession,pd.anAttendanceCode + case  when pd.Status is null then '''''''' else ''''(BL)'''' end  as SecondSession, e.Employee_Code_Id as Employee_Id,isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,convert(varchar(20),pd.date,101) as Date,pd.InTime,pd.OutTime,ISNULL(pd.HrsWork, ''''-''''),(pd.Attendance +  CASE pd.Status WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + isnull(pd.Status,'''''''')) as Status,((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))) as TotalMinsWorked''
	set @sqlQuery = @sqlQuery + '' ,(shf.Shift_ShortName + '''' ('''' + shf.Shift_StartTime + '''' - ''''  + shf.Shift_EndTime + '''')'''') as Shift_ShortName,shf.shift_TotalWorkingHours, (CASE WHEN ((DATENAME(DW,pd.date) != ''''Saturday'''') AND (ISNULL(REPLACE(TA_Tbl_Category.WeekDay_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''''Saturday'''') AND (ISNULL(REPLACE(TA_Tbl_Category.Sat_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END) as ValidWorkHrs '' 
	set @sqlQuery = @sqlQuery + '' ,case when DATENAME(DW, pd.date)<>''''Saturday'''' then  cat.WeekDay_WorkHrs else cat.Sat_WorkHrs end as [WeekDay_WorkHrs] ,
	convert(int,isnull(#Permission.Hrs,0))+convert(int,isnull(#Leave.Hrs,0)) as [Leave/Permission Hrs], 
	case when (pd.ANAttendanceCode=''''Weekly Off'''' or pd.ANAttendanceCode=''''Holiday'''') and (pd.FNAttendanceCode=''''Holiday'''' 
	          or pd.FNAttendanceCode=''''Weekly Off'''') then 0 
		 else  case when  DATENAME(DW, pd.date)<>''''Saturday'''' then  
						 (convert(int,cat.WeekDay_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
				    else (convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	           end   
		 end as TargetWorkHrs ,
	case when (pd.ANAttendanceCode=''''Weekly Off'''' or pd.ANAttendanceCode=''''Holiday'''') 
	          and (pd.FNAttendanceCode=''''Holiday'''' or pd.FNAttendanceCode=''''Weekly Off'''')  then 0 
	     else  case when  DATENAME(DW, pd.date)<>''''Saturday'''' then   
	                      case  when ((cat.WeekDay_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))
									- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) 
									+ (substring(isnull(pd.HrsWork,''''00:00''''),4,2))))/60, ''''0'''')))>0  
									then ((convert(int,cat.WeekDay_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
convert(int,substring(pd.HrsWork,0,charindex('''':'''',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('''':'''',pd.HrsWork)+1,LEN(pd.HrsWork))))
								else 0 
							end 
			   else  case  when ((cat.Sat_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))))/60, ''''0'''')))>0  
			                    then ((convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
convert(int,substring(pd.HrsWork,0,charindex('''':'''',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('''':'''',pd.HrsWork)+1,LEN(pd.HrsWork))))
							else 0 
					 end  
				end  
	end  as [DeviationWorkedHrs],
	                               cat.CategoryName,0, DATEDIFF(MI, ''''00:00'''', ISNULL(''''00:05'''', ''''00:05'''')),ISNULL(''''00:05'''', ''''00:05''''), NULL  from Ta_Tbl_Employee e ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id''    
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
  	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''	
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''   
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Category on TA_Tbl_EmployeeCategory.CategoryId = TA_Tbl_Category.CategoryId''
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
  	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay ON e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id''
    set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Category cat on cat.CategoryId = TA_Tbl_EmployeeCategory.CategoryId ''
    set @sqlQuery = @sqlQuery + '' left join #Leave on #Leave.Leave_FromDate=Pd.Date and  #Leave.EmpId=e.Employee_Id left join #Permission on #Permission.Permission_Date=Pd.Date and #Permission.EmpId=e.Employee_Id ''
    --'' left join #LeavePermission  on #LeavePermission.EmpId = e.Employee_Id and  (convert(varchar(12),#LeavePermission.Permission_Date,111)=convert(varchar(12), pd.Date,111) or  convert(varchar(12),#LeavePermission.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)) ''
    --set @sqlQuery = @sqlQuery + '' left join TA_Tbl_LeaveApplication  on TA_Tbl_LeaveApplication.Employee_Id = e.Employee_Id and  convert(varchar(12),TA_Tbl_LeaveApplication.Leave_FromDate,111)=convert(varchar(12), pd.Date,111) ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpPay on #EmpPay.EffectiveDate=TA_Tbl_EmployeePay.EffectiveDate and #EmpPay.employeeid=TA_Tbl_EmployeePay.EmployeeId ''
	if(@UserGroupName<>''SuperAdmin'')
		begin
			SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
		end
	if not(@EmployeeName='''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and (e.Employee_FirstName + isnull(e.Employee_LastName,'''''''') like '''''' + cast(@EmployeeName+''%'' as nvarchar(100)) + '''''')''
		end 
	if not(@EmployeeId='''')  
		begin  
			set @sqlQuery = @sqlQuery + ''and (e.Employee_Code_Id = '''''' + cast(@EmployeeId as nvarchar(100)) + '''''')''  
		end 
	If Not (@EmpSwipeCard = '''')  
			 Begin  
			  Set @sqlQuery = @sqlQuery + ''And e.SwipeCardNo = '''''' + @EmpSwipeCard + '''''' ''  
			 End
	if(@employeeCategory<>0)
		begin
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeCategory.CategoryId = '' + cast(@employeeCategory as nvarchar(8)) 
		end
	if(@employeeType<>0)
		begin
			set @sqlQuery = @sqlQuery + '' And TA_Tbl_EmployeeType.TypeId = '' + cast(@employeeType as nvarchar(8)) 
		end
    if(@EmpAutoId = 0)
	    BEGIN
			if not(@LevelID='''' or @LevelID=''0'')  
			begin  
			   set @sqlQuery = @sqlQuery + '' And (#EmpLevel.levelId In ('' + @LevelID + ''))''  
			End
		END
		ELSE
			BEGIN
			   set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
			END
    if(@fromDat!='''' and @ToDat!='''')
		begin
			set @sqlQuery = @sqlQuery + '' and((pd.date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''   
		end
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''   
	INSERT INTO #TempAttendanceDetails exec(@sqlQuery) 
	INSERT INTO @TempExecptionHrs
		SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
		WHERE [Date] BETWEEN @FromDat AND @ToDat
	GROUP BY EmployeeCodeId, [Date];
	UPDATE #TempAttendanceDetails SET
		HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
		TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
		DeviationWorkedHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN EH.TotalHrs ELSE (AD.DeviationWorkedHrs + EH.TotalHrs) END) ELSE DeviationWorkedHrs END)
	FROM #TempAttendanceDetails AD
		RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Id AND EH.[Date] = AD.[Date] 
	--select * from #TempAttendanceDetails where DeviationWorkedHrs>0
	----WHERE ValidWorkHrs = 1 AND
	---- ((FirstSession NOT IN (''Present'', ''Absent'', ''Holiday'', ''Weekly Off'') AND SecondSession = ''Present'')
	----	OR (SecondSession NOT IN (''Present'', ''Absent'', ''Holiday'', ''Weekly Off'') AND FirstSession = ''Present''))
	---- AND TotalMinsWorked >= 240
	----UPDATE #TempAttendanceDetails SET ValidWorkHrs = 0 WHERE HrsWork = ''-'' 
	---- SELECT FirstSession,SecondSession,Employee_Id,empName,BranchName,Designation,Date,InTime,OutTime,HrsWork,Status,TotalMinsWorked,Shift_ShortName,shift_TotalWorkingHours,ValidWorkHrs,replace (WeekDayWrkHrs,''.'','':'') as WeekDayWrkHrs,replace (LeavePermissionHrs,''.'','':'') as LeavePermissionHrs,REPLACE(TargetWorkedHrs,''.'','':'') as TargetWorkedHrs , 
	--case when len(DeviationWorkedHrs)=4 then  RIGHT(0,DeviationWorkedHrs) else DeviationWorkedHrs end as DeviationWorkedHrs,EmployeeCategory FROM #TempAttendanceDetails where Date between @fromDat and @ToDat and DeviationWorkedHrs>0
	create table #TotalDeviation(Id int identity(1,1),Employee_Code varchar(50),totalDeviation varchar(20))
	if not(@EmployeeId='''')  
		begin  
		insert into #TotalDeviation
			select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 and Employee_Id in (select value from split('','',@EmployeeId))
	group by Employee_Id
		end 
		else
			insert into #TotalDeviation
	select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
	group by Employee_Id
	--select * from #TotalDeviation 
	declare @count int;
	set @count=(select COUNT(*) from #TotalDeviation)
	while(@count>0)
	begin 
	update #TempAttendanceDetails set TotaldeviationHrs=(select convert(int,totalDeviation) from #TotalDeviation where Employee_Code = (select top 1 Employee_Id from #TotalDeviation where Id=@count))
	set @count=@count-1;
	end
	SELECT FirstSession , SecondSession, Employee_Id , empName ,
		BranchName , Designation , Date , InTime , OutTime , HrsWork ,
		Status , TotalMinsWorked , Shift_ShortName , shift_TotalWorkingHours , ValidWorkHrs ,
		--case when len(WeekDayWrkHrs/60)=1 and len(WeekDayWrkHrs%60)=1 then 
		--''0''+ convert(varchar(20),WeekDayWrkHrs/60) +'':0''+convert(varchar(20),WeekDayWrkHrs%60) 
		--when len(WeekDayWrkHrs/60)=1 and len(WeekDayWrkHrs%60)!=1 then 
		--''0''+ convert(varchar(20),WeekDayWrkHrs/60)+'':''+convert(varchar(20),WeekDayWrkHrs%60) 
		--when len(WeekDayWrkHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		--convert(varchar(20),WeekDayWrkHrs/60) +'':0''+convert(varchar(20),WeekDayWrkHrs%60) 
		--else
		--convert(varchar(20),WeekDayWrkHrs/60) +'':''+convert(varchar(20),WeekDayWrkHrs%60) 
		--end 
		--  as
		WeekDayWrkHrs ,
		case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
		''0''+ convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
		''0''+ convert(varchar(20),LeavePermissionHrs/60)+'':''+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
		else
		convert(varchar(20),LeavePermissionHrs/60) +'':''+convert(varchar(20),LeavePermissionHrs%60) 
		end 
		  as
		  LeavePermissionHrs,
		case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
		''0''+ convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
		''0''+ convert(varchar(20),TargetWorkedHrs/60)+'':''+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
		convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
		else
		convert(varchar(20),TargetWorkedHrs/60) +'':''+convert(varchar(20),TargetWorkedHrs%60) 
		end 
		  as TargetWorkedHrs ,
		case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
		''0''+ convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
		''0''+ convert(varchar(20),DeviationWorkedHrs/60)+'':''+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
		convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
		else
		convert(varchar(20),DeviationWorkedHrs/60)+'':'' +convert(varchar(20),DeviationWorkedHrs%60) 
		end 
		as 
		DeviationWorkedHrs,
		EmployeeCategory,
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60)+'':''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +'':''+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs FROM #TempAttendanceDetails 
	where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
	--Remove the temporary tables here   
	drop table #EmpLevel
	drop table #EmpDesignation
	drop table #EmpType
	drop table #EmpCategory
	drop table #EmpPay 
	drop table #EmpProcessedData
	drop table #EmployeeIds
	DROP TABLE #TempAttendanceDetails
	--drop table #LeavePermission
	drop table #leave
drop table #permission
	--drop table #TotalDeviation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_RptDailyDeviation]    Script Date: 03/25/2021 10:22:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_RptDailyDeviation]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'/*  
Created By : Manjula .P     
Created on : 11-Apr-2014
Descriptions	: creating daily deviation report procedure based on monthly attendance report.
				: Kindly update this procedure when you update rptMonthlyAttendance procedure.
				[Proc_TA_RptDailyDeviation] ''2016-07-01'',''2016-07-20'','''',0,'''',''0'',''0'',''Superadmin'',0,'''',0,0,0,''Both'',0
*/
CREATE PROCEDURE [dbo].[Proc_TA_RptDailyDeviation]  
	@fromDat datetime,  
	@ToDat datetime,  
	@EmployeeName varchar(50),  
	@LevelID varchar(8000),
	@EmployeeId varchar(50),
	@employeeCategory int,
	@employeeType int,
	@UserGroupName varchar(250),
	@GradeLevel varchar(20),	   
	@EmpSwipeCard varchar(20),
	@EmpAutoId bigint,
	@ParentID INT,
	@DesignationID int,
	@Gender varchar(10),
	@Export int
AS  
BEGIN
	SET NOCOUNT ON;
	--Temporary table''s creation
	CREATE TABLE #EmpLevel(EmployeeId INT,LevelId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpDesignation(EmployeeId INT,DesignationId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpType(EmployeeId INT,TypeId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	CREATE TABLE #EmpCategory(EmployeeId INT,CategoryId INT,EffectiveDate DATETIME,Employee_Code_Id NVARCHAR(50),SwipeCard NVARCHAR(50))
	DECLARE @TempExecptionHrs TABLE(Employee_Code_Id VARCHAR(100), [Date] DATETIME, TotalHrs BIGINT)	
	create table #EmployeeIds(EmpAutoId int)
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_ReportingTo](@EmpAutoId) as EmpAutoId  
	insert into  #EmployeeIds select * from [dbo].[fn_TA_GetMappedEmployees_SancAuthority](@EmpAutoId) as EmpAutoId
	declare @isReportingto as int
	select @isReportingto=ReportsBasedOn from TA_Tbl_Usergroup where groupName=@UserGroupName
	create table #LevelRights(LevelId int)
	insert into  #LevelRights select * from [dbo].[fn_TA_GetParentChild](@UserGroupName,@ParentID) as LevelId 
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpLevel] 
	(
		[EffectiveDate],[LevelId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpDesignation] 
	(
		[EffectiveDate],[DesignationId],[EmployeeId] ASC
	)ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpType] 
	(
		[EffectiveDate],[TypeId],[EmployeeId] ASC
	) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX [IDX_Effective] ON [dbo].[#EmpCategory] 
	(
		[EffectiveDate],[CategoryId],[EmployeeId] ASC
	)ON [PRIMARY]
	--insert in Temporary table	
	Declare @sqlCommon nvarchar(4000)
		--To split up the comma separated values
	if(@EmployeeId is not null and @EmployeeId <> '''')
		BEGIN
			CREATE TABLE #EmployeeID(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeID
			SELECT * from SplitupEmployeeCode(@EmployeeId)
		end
	if(@EmployeeName is not null and @EmployeeName <> '''')
		BEGIN
			CREATE TABLE #EmployeeName(EmployeeID NVARCHAR(25))
			INSERT INTO #EmployeeName
			SELECT [Value] from dbo.[SplitUpEmployeeName](@EmployeeName,'','')
		end
	set @sqlCommon=''''
	If Not (@EmployeeId = '''')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=Employee_Code_Id ''
			End
	If Not (@EmployeeName = '''')  
			BEGIN  
				SET @sqlCommon = @sqlCommon + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=Employee_Code_Id ''
			End		
	DECLARE @sqlEmpLevel nVARCHAR(4000)	
	SET @sqlEmpLevel=
	''INSERT INTO #EmpLevel 	SELECT Elevel.EmployeeId,EL.levelId,Elevel.EffectiveDate,ELevel.Employee_Code_Id,ELevel.SwipeCardNo 
	from	(
	SELECT	max(el.EffectiveDate) as EffectiveDate,	el.EmployeeId as EmployeeId,emp.Employee_Code_Id,emp.SwipeCardNo 
	from TA_Tbl_EmployeeLevel el
	INNER JOIN ta_tbl_employee emp ON el.EmployeeId = emp.Employee_Id 
	INNER JOIN #LevelRights ON #LevelRights.LevelId=el.LevelId ''
	set @sqlEmpLevel= @sqlEmpLevel+@sqlCommon	
	set @sqlEmpLevel= @sqlEmpLevel +'' WHERE emp.Isdeleted=0 group by el.EmployeeId,Employee_Code_Id,emp.SwipeCardNo) ELevel
	INNER JOIN TA_Tbl_EmployeeLevel EL ON EL.EffectiveDate=ELevel.EffectiveDate and EL.employeeid=ELevel.EmployeeId
	INNER JOIN #LevelRights ON #LevelRights.LevelId=EL.LevelId
	AND EL.EffectiveDate <= CONVERT(DATETIME,''''''+cast(@todat as nVARCHAR(50))+'''''', 102) and EL.LevelId is not null''			
	EXECUTE(@sqlEmpLevel)	
	INSERT INTO #EmpDesignation exec Proc_TA_EmpDesignation @todat,@EmployeeId,@DesignationID	
	INSERT INTO #EmpType exec [Proc_TA_EmpType] @todat,@EmployeeId,@employeeType	
	INSERT INTO #EmpCategory exec [Proc_TA_EmpCategory] @todat,@EmployeeId,@employeeCategory
	create table #Leave
	(
		EmpId int,
		Leave_FromDate datetime,
		Hrs varchar(20)
	)
	Declare @sqlLeave varchar(max)
	set @sqlLeave=''
	insert into #Leave select E.Employee_Id ,Leave_FromDate,
	case when LA.Status=''''Approved'''' then
	case when substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''''.'''',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))!=0
	then substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''''.'''',isnull(LA.NumberOfDays,0)))*8*60 + 
	4*60
	else
	substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),0,charindex(''''.'''',isnull(LA.NumberOfDays,0)))*8*60 + 
	substring(convert(varchar(20),isnull(LA.NumberOfDays,0)),charindex(''''.'''',isnull(LA.NumberOfDays,0))+1,LEN(isnull(LA.NumberOfDays,0)))*4*60
	end
	else
	0 end
	as [Leave Hrs] 
	from TA_Tbl_Employee E 
	left join TA_Tbl_LeaveApplication LA on LA.Employee_Id=E.Employee_Id 
	left join TA_Tbl_ProcessedData pd on (pd.Date=LA.Leave_FromDate )''
	If Not (@EmployeeId = '''')  
			BEGIN  
				SET @sqlLeave = @sqlLeave + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id ''
			End
	If Not (@EmployeeName = '''')  
			BEGIN  
				SET @sqlLeave = @sqlLeave + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id ''
			End		
	set @sqlLeave= @sqlLeave+''
	where 
	convert(varchar(12),LA.Leave_FromDate,111)=convert(varchar(12), pd.Date,111)  and
	LA.IsDeleted=0
	and pd.Date between CONVERT(DATETIME,''''''+convert(varchar(50),@fromDat)+'''''', 102) and CONVERT(DATETIME,''''''+convert(varchar(20),@ToDat)+'''''', 102)
	group by E.Employee_Id ,E.Employee_Code_Id,NumberOfDays,Leave_FromDate,LA.Status''
	Execute(@sqlLeave)
	create table #Permission
	(
	EmpId int,
	Permission_Date datetime,
	Hrs  varchar(20)
	)
	Declare @SQLPermission varchar(max)
	set @SQLPermission =''insert into #Permission
	select E.Employee_Id ,Permission_Date,
	case when C.Sat_WorkHrs<8 then 0 else
	case when P.Permission_Status=''''Approved'''' then 
	substring(Permission_Hours,0,charindex('''':'''',Permission_Hours))*60 + 
	substring(Permission_Hours,charindex('''':'''',Permission_Hours)+1,LEN(Permission_Hours))
	else
	0 
	end
	end
	as [Permission Hrs] 
	from TA_Tbl_Employee E 
	inner join #EmpCategory on #EmpCategory.EmployeeId=E.Employee_Id
	inner join TA_Tbl_Category C on C.CategoryId=#EmpCategory.CategoryId
	left join  TA_Tbl_Permission P on P.Employee_Id=E.Employee_Id
	left join TA_Tbl_ProcessedData pd on ( pd.Date=P.Permission_Date)	''
	If Not (@EmployeeId = '''')  
			BEGIN  
				SET @SQLPermission = @SQLPermission + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id ''
			End
	If Not (@EmployeeName = '''')  
			BEGIN  
				SET @SQLPermission = @SQLPermission + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id ''
			End		
	set @SQLPermission= @SQLPermission+
	'' where 
	convert(varchar(12),P.Permission_Date,111)=convert(varchar(12), pd.Date,111)  and
	P.IsDeleted=0
	and pd.Date between CONVERT(DATETIME,''''''+cast(@fromDat as nvarchar(50))+'''''', 102) and CONVERT(DATETIME,''''''+cast(@ToDat as nvarchar(50))+'''''', 102)	
	group by E.Employee_Id ,E.Employee_Code_Id,Permission_Date,P.Permission_Status,Permission_Hours,C.Sat_WorkHrs''
	Execute(@SQLPermission)
	CREATE TABLE #TempAttendanceDetails (Employee_Id NVARCHAR(10), empName NVARCHAR(250),
	BranchName NVARCHAR(250), Designation NVARCHAR(250), Date datetime, InTime NVARCHAR(25), OutTime NVARCHAR(25), HrsWork NVARCHAR(10),
	Status NVARCHAR(50), TotalMinsWorked INT, Shift_ShortName VARCHAR(100), shift_TotalWorkingHours NVARCHAR(50), ValidWorkHrs BIT,
	WeekDayWrkHrs decimal(18,2),LeavePermissionHrs varchar(20),
	TargetWorkedHrs varchar(20),
	DeviationWorkedHrs varchar(20),
	EmployeeCategory nvarchar(50),
	TotaldeviationHrs varchar(20),
	Gender varchar(10), ExceptionMins BIGINT,ExceptionHours VARCHAR(10), BreakHours VARCHAR(10)
	)	
	declare @sqlQuery as varchar(max)  
	set @sqlQuery=''''  
	set @sqlQuery = ''select e.Employee_Code_Id as Employee_Id,
													isnull(e.Employee_FirstName,'''''''') +  space(1) + isnull(e.Employee_LastName,'''''''') as empName,
													replace(dbo.Ta_Tbl_levelDetails.name,''''&amp;'''',''''&'''') as BranchName,
													replace(T.TitleName,''''&amp;'''',''''&'''') as Designation,
													convert(varchar(20),pd.date,101) as Date,
													pd.InTime,
													pd.OutTime,
													ISNULL(pd.HrsWork, ''''-''''),
													(pd.Attendance +  CASE pd.Status WHEN ''''BL'''' THEN '''' - '''' ELSE '''''''' END + isnull(pd.Status,'''''''')) as Status,
													((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))) as TotalMinsWorked''
	set @sqlQuery = @sqlQuery + '' ,(shf.Shift_ShortName + '''' ('''' + shf.Shift_StartTime + '''' - ''''  + shf.Shift_EndTime + '''')'''') as Shift_ShortName,
													shf.shift_TotalWorkingHours, 
	(CASE WHEN ((DATENAME(DW,pd.date) != ''''Saturday'''') AND (ISNULL(REPLACE(cat.WeekDay_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 WHEN ((DATENAME(DW,pd.date) = ''''Saturday'''') AND (ISNULL(REPLACE(cat.Sat_WorkHrs,''''.5'''', ''''.3''''), 0.0) > CAST(REPLACE(ISNULL(pd.HrsWork, 0.0), '''':'''', ''''.'''') AS DECIMAL(18,1)))) THEN 1 ELSE 0 END) as ValidWorkHrs '' 
	set @sqlQuery = @sqlQuery + '' ,case when DATENAME(DW, pd.date)<>''''Saturday'''' then  REPLACE(cat.WeekDay_WorkHrs, ''''.5'''', ''''.3'''') else cat.Sat_WorkHrs end as [WeekDay_WorkHrs] ,
	convert(int,isnull(#Permission.Hrs,0))+convert(int,isnull(#Leave.Hrs,0)) as [Leave/Permission Hrs], 
	case when (pd.ANAttendanceCode=''''Weekly Off'''' or pd.ANAttendanceCode=''''Holiday'''') and (pd.FNAttendanceCode=''''Holiday'''' 
	or pd.FNAttendanceCode=''''Weekly Off'''') then 0 
	else  case when  DATENAME(DW, pd.date)<>''''Saturday'''' then  
	(convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''''.'''',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''''.'''',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	else (convert(int,cat.Sat_WorkHrs)*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0)) 
	end   
	end as TargetWorkHrs ,
	case when (pd.ANAttendanceCode=''''Weekly Off'''' or pd.ANAttendanceCode=''''Holiday'''') 
	and (pd.FNAttendanceCode=''''Holiday'''' or pd.FNAttendanceCode=''''Weekly Off'''')  then 0 
	else  case when  DATENAME(DW, pd.date)<>''''Saturday'''' then   
	case  when ((convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''''.'''',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''''.'''',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))
			- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) 
			+ (substring(isnull(pd.HrsWork,''''00:00''''),4,2))))/60, ''''0'''')))>0  
			then ((convert(int,SUBSTRING(cat.WeekDay_WorkHrs,0,charindex(''''.'''',cat.WeekDay_WorkHrs)))*60 +convert(int,SUBSTRING(cat.WeekDay_WorkHrs,charindex(''''.'''',cat.WeekDay_WorkHrs)+1,LEN(cat.WeekDay_WorkHrs)))*6-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
	convert(int,substring(pd.HrsWork,0,charindex('''':'''',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('''':'''',pd.HrsWork)+1,LEN(pd.HrsWork))))
		else 0 
	end 
	else  case  when ((cat.Sat_WorkHrs*60-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))- convert(decimal(18,2), ISNULL(convert(decimal(18,2),((substring(isnull(pd.HrsWork,''''00:00''''),0,3)*60) + (substring(isnull(pd.HrsWork,''''00:00''''),4,2))))/60, ''''0'''')))>0  
		then ((convert(int,cat.Sat_WorkHrs*60)-isnull( ISNULL(#Leave.Hrs,0)+ISNULL(#Permission.Hrs,0),0))-
	convert(int,substring(pd.HrsWork,0,charindex('''':'''',pd.HrsWork))*60 + substring(pd.HrsWork,charindex('''':'''',pd.HrsWork)+1,LEN(pd.HrsWork))))
	else 0 
	end  
	end  
	end  as [DeviationWorkedHrs],
			cat.CategoryName,0,e.Gender, DATEDIFF(MI, ''''00:00'''', ISNULL(SS.MaxWorkPlaceInHours, ''''00:10'''')),
			ISNULL(SS.MaxWorkPlaceInHours, ''''00:10''''), NULL from Ta_Tbl_Employee e ''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_ProcessedData pd on e.SwipeCardNo=pd.Employee_Code_Id''    
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeLevel on e.Employee_Id = TA_Tbl_EmployeeLevel.EmployeeId''
	set @sqlQuery = @sqlQuery + '' inner join Ta_Tbl_levelDetails on TA_Tbl_EmployeeLevel.LevelId = Ta_Tbl_levelDetails.id''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeDesignation EDesig ON e.Employee_Id=EDesig.EmployeeID ''	
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Title T ON EDesig.DesignationId = T.TitleId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Grade ON TA_Tbl_Grade.Grade_ID = T.GradeId''   
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeCategory  on e.Employee_Id = TA_Tbl_EmployeeCategory.EmployeeId''	
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeeType  on e.Employee_Id = TA_Tbl_EmployeeType.EmployeeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_Type on TA_Tbl_EmployeeType.TypeId = TA_Tbl_Type.TypeId''
	set @sqlQuery = @sqlQuery + '' inner join TA_Tbl_EmployeePay ON e.Employee_Id = TA_Tbl_EmployeePay.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' left join Ta_tbl_Shift shf on pd.Shift_ID = shf.Shift_Id''
	SET @sqlQuery = @sqlQuery + '' LEFT JOIN TA_Tbl_ShiftSettings SS ON shf.Level_Id = SS.CompanyId ''
	set @sqlQuery = @sqlQuery + '' left join TA_Tbl_Category cat on cat.CategoryId = TA_Tbl_EmployeeCategory.CategoryId ''
	set @sqlQuery = @sqlQuery + '' left join #Leave on #Leave.Leave_FromDate=Pd.Date and  #Leave.EmpId=e.Employee_Id left join #Permission on #Permission.Permission_Date=Pd.Date and #Permission.EmpId=e.Employee_Id ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpLevel on #EmpLevel.EffectiveDate=TA_Tbl_EmployeeLevel.EffectiveDate and #EmpLevel.employeeid=TA_Tbl_EmployeeLevel.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpDesignation on #EmpDesignation.EffectiveDate=EDesig.EffectiveDate and #EmpDesignation.employeeid=EDesig.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpType on #EmpType.EffectiveDate=TA_Tbl_EmployeeType.EffectiveDate and #EmpType.employeeid=TA_Tbl_EmployeeType.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' Inner join #EmpCategory on #EmpCategory.EffectiveDate=TA_Tbl_EmployeeCategory.EffectiveDate and #EmpCategory.employeeid=TA_Tbl_EmployeeCategory.EmployeeId ''
	set @sqlQuery = @sqlQuery + '' inner join #LevelRights ON #LevelRights.LevelId = #EmpLevel.LevelId ''		
		if(@UserGroupName<>''SuperAdmin'')
	begin
		SET @sqlQuery = @sqlQuery + '' AND TA_Tbl_Grade.Grade_Level>='' + @GradeLevel + ''''
	end	  
	If Not (@EmployeeId = '''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeID ON #EmployeeID.EmployeeID=e.Employee_Code_Id ''
		End
	If Not (@EmployeeName = '''')  
		BEGIN  
			SET @sqlQuery = @sqlQuery + '' INNER JOIN #EmployeeName ON #EmployeeName.EmployeeID=e.Employee_Code_Id ''
		End	
	if(isnull(@Gender,''Both'')<>''Both'')
	begin
	set @sqlQuery = @sqlQuery + '' and e.Gender = '''''' + cast(@Gender as nvarchar(8)) + '''''' ''
	end
	if(@isReportingto > 0)
            BEGIN
               set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
            END
	--if(@EmpAutoId > 0)
	--BEGIN
	--	set @sqlQuery = @sqlQuery + '' and (e.Employee_ID IN (select * from #EmployeeIds)) ''  
	--END
	if(@fromDat!='''' and @ToDat!='''')
	begin
	set @sqlQuery = @sqlQuery + '' and((pd.date >= CONVERT(DATETIME, '''''' + cast(@fromDat as nvarchar(11)) + '''''', 102) and pd.date <= CONVERT(DATETIME, '''''' + cast(@toDat as nvarchar(11)) + '''''', 102)))''   
	end
	set @sqlQuery = @sqlQuery + '' order by e.Employee_FirstName,cast(pd.date as datetime)''   
	INSERT INTO #TempAttendanceDetails 
	exec(@sqlQuery) 
	--select * from #TempAttendanceDetails 
	INSERT INTO @TempExecptionHrs
	SELECT EmployeeCodeId, [Date], SUM(PunchDifferenceMins) FROM TA_VW_FirstInPunchDifference
	WHERE [Date] BETWEEN @FromDat AND @ToDat
	GROUP BY EmployeeCodeId, [Date];
	UPDATE #TempAttendanceDetails SET
	HrsWork = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN ''00:00'' ELSE (CASE WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)))=1 THEN ''0'' +  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) ELSE  CAST(((AD.TotalMinsWorked- EH.TotalHrs)/60) AS VARCHAR(25)) END  + '':'' + CASE  WHEN LEN(CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25))) = 1 THEN ''0'' + CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) ELSE CAST(((AD.TotalMinsWorked- EH.TotalHrs)%60) AS VARCHAR(25)) END) END) ELSE HrsWork END),
	TotalMinsWorked = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN 0 ELSE (AD.TotalMinsWorked- EH.TotalHrs) END) ELSE TotalMinsWorked END),
	DeviationWorkedHrs = (CASE WHEN (ExceptionMins < EH.TotalHrs) THEN (CASE WHEN EH.TotalHrs > AD.TotalMinsWorked THEN EH.TotalHrs ELSE (AD.DeviationWorkedHrs + EH.TotalHrs) END) ELSE DeviationWorkedHrs END)
	FROM #TempAttendanceDetails AD
	RIGHT JOIN @TempExecptionHrs EH ON EH.Employee_Code_Id = AD.Employee_Id AND EH.[Date] = AD.[Date] 
	--select * from #TempAttendanceDetails where DeviationWorkedHrs>0
	create table #TotalDeviation(Id int identity(1,1),Employee_Code varchar(50),totalDeviation varchar(20))
	if not(@EmployeeId='''')  
	begin  
		insert into #TotalDeviation
		select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 and Employee_Id in (select value from split(@EmployeeId,'',''))
		group by Employee_Id
	end 		
	else
	begin
		insert into #TotalDeviation
		select Employee_Id,sum(convert(int,DeviationWorkedHrs)) as totalDeviation from #TempAttendanceDetails
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
		group by Employee_Id
	end
		--select * from #TotalDeviation 
		--Get current date time format.
		DECLARE @dateFormat as int
		DECLARE @date as nvarchar(25)			
		SET @date = (SELECT DateFormat FROM TA_Tbl_DateandTimeFormat)	
		IF(@date=''dd/MM/yyyy'')
			BEGIN
				SET @dateFormat = 103
			END
		ELSE IF(@date=''MM/dd/yyyy'')
			BEGIN
				SET @dateFormat = 101
			END
		ELSE
			BEGIN
				SET @dateFormat = 106
			END	
		declare @count int;
		set @count=(select COUNT(*) from #TotalDeviation)
		while(@count>0)
		begin 
			update #TempAttendanceDetails set TotaldeviationHrs=(select convert(int,totalDeviation) from #TotalDeviation where Employee_Code = (select top 1 Employee_Id from #TotalDeviation where Id=@count))
			set @count=@count-1;
		end
		if(@Export=0)
		begin
			SELECT  Employee_Id , empName ,
		BranchName , Designation , 
		case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
				else CONVERT(VARCHAR, Date, @dateFormat) 
		end AS Date
		, InTime , OutTime , HrsWork ,
		Status , TotalMinsWorked , Shift_ShortName , shift_TotalWorkingHours , ValidWorkHrs ,	
		''0'' + REPLACE(WeekDayWrkHrs, ''.'', '':'') WeekDayWrkHrs ,
		case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
		''0''+ convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
		''0''+ convert(varchar(20),LeavePermissionHrs/60)+'':''+convert(varchar(20),LeavePermissionHrs%60) 
		when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
		convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
		else
		convert(varchar(20),LeavePermissionHrs/60) +'':''+convert(varchar(20),LeavePermissionHrs%60) 
		end 
		as
		LeavePermissionHrs,
		case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
		''0''+ convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
		''0''+ convert(varchar(20),TargetWorkedHrs/60)+'':''+convert(varchar(20),TargetWorkedHrs%60) 
		when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
		convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
		else
		convert(varchar(20),TargetWorkedHrs/60) +'':''+convert(varchar(20),TargetWorkedHrs%60) 
		end 
		as TargetWorkedHrs ,
		case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
		''0''+ convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
		''0''+ convert(varchar(20),DeviationWorkedHrs/60)+'':''+convert(varchar(20),DeviationWorkedHrs%60) 
		when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
		convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
		else
		convert(varchar(20),DeviationWorkedHrs/60)+'':'' +convert(varchar(20),DeviationWorkedHrs%60) 
		end 
		as 
		DeviationWorkedHrs,
		EmployeeCategory,
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60)+'':''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +'':''+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs,Gender FROM #TempAttendanceDetails 
		where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 
		end
		else
		begin
			SELECT 
			dense_rank()over(order by BranchName,EMPLOYEE_ID) as [Sl.No],
			BranchName as level,Employee_Id as [Emp. No], empName as [Employee Name],
			Designation ,Gender ,EmployeeCategory as [Employee Category], 
			case	when cast(@dateFormat as varchar(100))=106 then REPLACE(CONVERT(VARCHAR, Date,@dateFormat),'' '',''-'') 
					else CONVERT(VARCHAR, Date, @dateFormat) 
			end AS Date
			,		
			''0'' + REPLACE(WeekDayWrkHrs, ''.'', '':'') as [Daily Minimum Working Hrs],
			case when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)=1 then 
			''0''+ convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
			when len(LeavePermissionHrs/60)=1 and len(LeavePermissionHrs%60)!=1 then 
			''0''+ convert(varchar(20),LeavePermissionHrs/60)+'':''+convert(varchar(20),LeavePermissionHrs%60) 
			when len(LeavePermissionHrs/60)!=1 and len(LeavePermissionHrs%60)=1 then 
			convert(varchar(20),LeavePermissionHrs/60) +'':0''+convert(varchar(20),LeavePermissionHrs%60) 
			else
			convert(varchar(20),LeavePermissionHrs/60) +'':''+convert(varchar(20),LeavePermissionHrs%60) 
			end 
			as
			[Leave/Permission Hrs],
			case when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)=1 then 
			''0''+ convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
			when len(TargetWorkedHrs/60)=1 and len(TargetWorkedHrs%60)!=1 then 
			''0''+ convert(varchar(20),TargetWorkedHrs/60)+'':''+convert(varchar(20),TargetWorkedHrs%60) 
			when len(TargetWorkedHrs/60)!=1 and len(TargetWorkedHrs%60)=1 then 
			convert(varchar(20),TargetWorkedHrs/60) +'':0''+convert(varchar(20),TargetWorkedHrs%60) 
			else
			convert(varchar(20),TargetWorkedHrs/60) +'':''+convert(varchar(20),TargetWorkedHrs%60) 
			end 
			as [Target Worked Hrs],
			HrsWork as [Actual Worked Hrs],
			case when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)=1 then 
			''0''+ convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
			when len(DeviationWorkedHrs/60)=1 and len(DeviationWorkedHrs%60)!=1 then 
			''0''+ convert(varchar(20),DeviationWorkedHrs/60)+'':''+convert(varchar(20),DeviationWorkedHrs%60) 
			when len(DeviationWorkedHrs/60)!=1 and len(DeviationWorkedHrs%60)=1 then 
			convert(varchar(20),DeviationWorkedHrs/60) +'':0''+convert(varchar(20),DeviationWorkedHrs%60) 
			else
			convert(varchar(20),DeviationWorkedHrs/60)+'':'' +convert(varchar(20),DeviationWorkedHrs%60) 
			end 
			as 
			[Deviated Hrs],
		case when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)=1 and len(TotaldeviationHrs%60)!=1 then 
		''0''+ convert(varchar(20),TotaldeviationHrs/60)+'':''+convert(varchar(20),TotaldeviationHrs%60) 
		when len(TotaldeviationHrs/60)!=1 and len(TotaldeviationHrs%60)=1 then 
		convert(varchar(20),TotaldeviationHrs/60) +'':0''+convert(varchar(20),TotaldeviationHrs%60) 
		else
		convert(varchar(20),TotaldeviationHrs/60) +'':''+ convert(varchar(20),TotaldeviationHrs%60) 
		end 
		as TotaldeviationHrs FROM #TempAttendanceDetails 
			where Date between @fromDat and @ToDat and DeviationWorkedHrs>0 order by BranchName,Employee_Id 
		end
		--select * from #EmployeeIds
		--Remove the temporary tables here   
		drop table #EmpLevel
		drop table #EmpDesignation
		drop table #EmpType
		drop table #EmpCategory	
		drop table #EmployeeIds
		DROP TABLE #TempAttendanceDetails
		drop table #leave
		drop table #permission
		drop table #LevelRights
		drop table #TotalDeviation
END
' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetEmailIdsByUserGroup]    Script Date: 03/25/2021 10:22:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetEmailIdsByUserGroup]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the email ids based on the user group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetEmailIdsByUserGroup] 
(
@LevelId int,
@DesignationId int,
@Parameter varchar(5)
)
AS
BEGIN
	SET NOCOUNT ON;
if(@Parameter=''P'')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_Planned CCP on CCP.CC_Planned=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCP.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END
if(@Parameter=''U'')
	BEGIN
	    select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_UnPlanned CCU on CCU.CC_UnPlanned=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCU.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END
if(@Parameter=''O'')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_Others CCO on CCO.CC_Others=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCO.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END  
-- Add by GOpinath for adding CCMail group users for OD Approval table 
if(@Parameter=''OD'')
	BEGIN
		select EmailId from TA_tbl_Employee E
		inner join TA_Tbl_CCGroup_ODApproval CCOD on CCOD.CC_ODApproval=E.UserGroup_Id
		inner join TA_tbl_CcMailGroup CC on CC.CCGroupId=CCOD.CCGroupID
		where CC.LevelId=@LevelId and CC.DEsignationID=@DesignationID
		and E.IsDeleted=0 and E.Employee_Status=1
		select MailTo_SecondLevel_Planned,MailTo_SecondLevel_UnPlanned from TA_tbl_CcMailGroup
		where LevelId=@LevelId and DEsignationID=@DesignationID
	END    
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[Proc_TA_GetCCGroupById]    Script Date: 03/25/2021 10:22:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Proc_TA_GetCCGroupById]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:		Sashma 
-- Create date: 12-Oct-2010
-- Description:	Fetches the Designation based on the organization for CC mail group.
-- =============================================
CREATE PROCEDURE [dbo].[Proc_TA_GetCCGroupById] 
@CCGroupID int
AS
BEGIN
	 SET NOCOUNT ON;
    select * from TA_tbl_CcMailGroup where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_Planned where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_UnPlanned where CcGroupId=@CCGroupID
    select * from TA_Tbl_CCGroup_Others where CcGroupId=@CCGroupID
	select * from TA_Tbl_CCGroup_ODApproval where CcGroupId=@CCGroupID
END
' 
END
GO





/****** Default values Script Date: 08/27/2019 15:39:33 ******/
SET IDENTITY_INSERT [dbo].[TA_Tbl_TerminalBrand] ON
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (1, CONVERT(TEXT, N'Hanvon Face Recognition'), CONVERT(TEXT, N'Hanvon'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (2, CONVERT(TEXT, N'Others'), CONVERT(TEXT, N'Others'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (3, CONVERT(TEXT, N'Suprema'), CONVERT(TEXT, N'Suprema'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (4, CONVERT(TEXT, N'Suprema-Biostar 2'), CONVERT(TEXT, N'Suprema-Biostar 2'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (5, CONVERT(TEXT, N'ESSL'), CONVERT(TEXT, N'ESSL'))
INSERT [dbo].[TA_Tbl_TerminalBrand] ([BrandID], [DisplayName], [KeyValue]) VALUES (6, CONVERT(TEXT, N'ZK Teco'), CONVERT(TEXT, N'ZK Teco'))
SET IDENTITY_INSERT [dbo].[TA_Tbl_TerminalBrand] OFF
Go
--Page Table
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (194, N'Menu_Configuration', N'', 0, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (189, N'Organization_Settings', N'', 0, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (187, N'Device_Management', N'', 0, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (204, N'Menu_EMp_Master', N'', 188, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (190, N'Privilege_Management', N'', 0, 13, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (188, N'Employee_Management', N'', 0, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (235, N'Shift_Management', N'', 0, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (236, N'Leave_Permission_Management', N'', 0, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (237, N'ManualTimeEntry', N'', 0, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (192, N'Menu_Reports', N'', 0, 11, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (193, N'Other_useful_features', N'', 0, 14, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (230, N'Menu_Vehicle', N'Masters/TA_UI_MasterTransportationVehicleList.aspx', 12, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (195, N'Menu_LeaveType', N'Masters/TA_UI_MasterLeaveTypeList.aspx', 209, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (177, N'Masters_EmailConfiguration', N'Masters/TA_UI_EmailScheduleList.aspx', 0, 12, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (209, N'Menu_Leave_Master', N'', 236, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (196, N'Menu_LeavePolicy', N'Masters/TA_UI_MasterLeavePolicyList.aspx', 209, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (205, N'Menu_EMp_Report', N'', 188, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (197, N'Menu_LicenseRequistion', N'System Settings/SystemSetting_LicenseRequest.aspx', 107, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (198, N'Menu_Licenseupdater', N'System Settings/SystemSetting_LicenseUpdater.aspx', 107, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (199, N'Menu_LicenseInfo', N'System Settings/SystemSetting_ViewLicenseInfo.aspx', 107, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (231, N'Menu_Route', N'Masters/TA_UI_MasterTransportationRouteList.aspx', 12, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (202, N'ShiftAllocationExport', N'Transactions/TA_UI_Transaction_ShiftExport.aspx', 207, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (203, N'DataReprocessing', N'Transactions/TA_UI_Transaction_DataReprocessing.aspx', 207, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (206, N'Menu_Shift_Master', N'', 235, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (207, N'Menu_Shift_Transaction', N'', 235, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (208, N'Menu_Shift_Reports', N'', 235, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (210, N'Menu_Leave_Transaction', N'', 236, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (211, N'Menu_Leave_Reports', N'', 236, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (212, N'Menu_ME_Transaction', N'', 237, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (213, N'Menu_ME_Reports', N'', 237, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (214, N'Menu_OTCOMPOff', N'', 0, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (215, N'Menu_OnDuty', N'', 0, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (216, N'Menu_Permission_Transaction', N'', 236, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (218, N'Menu_ED_Transaction', N'', 217, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (217, N'Menu_ExportData', N'', 0, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (219, N'Menu_ED_Reports', N'', 217, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (220, N'Menu_ME_Import', N'Transactions/TA_UI_Transactions_ManualEntryImport.aspx', 212, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (221, N'Menu_ME_Export', N'Transactions/TA_UI_Transactions_ManualEntryExport.aspx', 212, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (222, N'Menu_ME_Discrepancy', N'Transactions/TA_UI_Transactions_DiscrepancyList.aspx', 212, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (223, N'Menu_TerminalDB', N'Masters/TA_UI_Master_TerminalDatatype.aspx', 10, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (224, N'Menu_TerminalMaster', N'Masters/TA_UI_Master_Terminal.aspx', 10, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (225, N'Menu_Country', N'Masters/TA_UI_Master_CountryList.aspx', 204, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (226, N'Menu_State', N'Masters/TA_UI_Master_StateList.aspx', 204, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (227, N'Menu_City', N'Masters/TA_UI_Master_CityList.aspx', 204, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (228, N'Menu_Grade', N'Masters/TA_UI_Master_GradeList.aspx', 204, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (229, N'Menu_Region', N'Masters/TA_UI_Master_ReligionList.aspx', 204, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (232, N'Menu_Dev_EmpDetails', N'Reports/TA_UI_XGReportEmployeeDetail.aspx', 147, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (233, N'Menu_Dev_Attendance', N'Reports/TA_UI_XGReportAttendance.aspx', 147, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (234, N'Menu_Dev_AllSwipes', N'Reports/TA_UI_XGReportMovementsEntry.aspx', 147, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (179, N'Menu_Master_Dashboard', N'DashBoard.aspx', 0, 0, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (6, N'Master_Organization', N'Masters/TA_UI_Master_OrganisationLevels.aspx', 189, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (10, N'Master_Terminal', N'', 187, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (15, N'Master_Entrance', N'Masters/TA_UI_Master_Entrance.aspx', 187, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (68, N'Master_Punch', N'Masters/TA_UI_Master_PunchTypes_List.aspx', 187, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (17, N'Master_Designation', N'Masters/TA_UI_Master_TitleFirstList.aspx', 204, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (94, N'Master_Category', N'Masters/TA_UI_Master_EmployeeCategoryList.aspx', 204, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (95, N'Master_Type', N'Masters/TA_UI_Master_EmployeeTypeList.aspx', 204, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (18, N'Master_Employee', N'Masters/TA_UI_Master_Employee.aspx', 204, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (19, N'Master_Shift', N'Masters/TA_UI_Master_ShiftDetails.aspx', 206, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (20, N'Master_Shift_Pattern', N'Masters/TA_UI_Master_ShiftPattern.aspx', 206, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (69, N'Master_Shift_Roster', N'Masters/TA_UI_Master_ShiftRoaster.aspx', 206, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (16, N'Master_Holidays', N'Masters/TA_UI_Master_Holiday.aspx', 194, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (99, N'Master_AttandanceCode', N'Masters/TA_UI_Master_AttandanceCode.aspx', 193, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (100, N'Master_OverTimeType', N'Masters/TA_UI_Master_OverTimeType.aspx', 193, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (12, N'Master_Transportation', N'', 193, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (21, N'Master_User_Groups', N'Masters/TA_UI_Master_groupView.aspx', 190, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (26, N'Transcation_Manual_Time', N'Transactions/TA_UI_Transactions_ManualTimeEntry.aspx', 212, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (98, N'Transcation_ManualTimeEntry_Approval', N'Transactions/TA_UI_Transactions_ManualTimeEntrySanction.aspx', 212, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (22, N'Transaction_Leave_Application', N'Transactions/TA_UI_Transactions_LeaveApplication.aspx', 210, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (173, N'Transaction_OnDuty', N'Transactions/TA_UI_Transactions_OnDutyList.aspx', 215, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (108, N'Transaction_LeavePolicyAllocation', N'Transactions/TA_UI_Transactions_GroupLeavePolicy.aspx', 210, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (96, N'Transaction_BonusLeave', N'Transactions/TA_UI_Transactions_BonusLeaveAllocation.aspx', 210, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (23, N'Transaction_Permission', N'Transactions/TA_UI_Transactions_LeavePermission.aspx', 216, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (248, N'Transaction_Approvals', N'Transactions/TA_UI_Transaction_Sanctions.aspx', 236, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (28, N'Transaction_Shift_Allocation', N'Transactions/TA_UI_Transaction_ShiftAllocation.aspx', 207, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (29, N'Tranaction_Temporary_Shift', N'Transactions/TA_UI_Transaction_TemporaryShiftAllocationadd.aspx', 207, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (60, N'Transaction_Shift_Exchange', N'Transactions/TA_UI_Transaction_ShiftExchangeList.aspx', 207, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (116, N'Caption_ShiftReAllocation', N'Transactions/TA_UI_Transactions_ShiftReAllocation.aspx', 207, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (97, N'Transaction_OverTime_Sanction', N'Transactions/TA_UI_Transactions_OverTimeSanction.aspx', 214, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (102, N'Transaction_SwipesHandling', N'Transactions/TA_UI_Transactions_SwipesHandlingList.aspx', 212, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (27, N'Transcation_Payroll', N'Transactions/TA_UI_Transactions_MonthClosure.aspx', 218, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (62, N'Transaction_Year_Closure', N'Transactions/TA_UI_Transactions_YearClosureAdd.aspx', 218, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (76, N'Transaction_Encashment', N'Transactions/TA_UI_Transaction_Encashment.aspx', 210, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (144, N'Menu_Report_Attendace', N'', 192, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (180, N'Report_GeneralMonthly_Attendance', N'Reports/TA_UI_Report_GeneralMonthlyAttendance.aspx', 144, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (41, N'Report_All_Swipes', N'Reports/TA_UI_Report_MovementsEntry.aspx', 144, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (40, N'Report_Monthly_Attendance', N'Reports/TA_UI_Report_MonthlyAttendance.aspx', 144, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (30, N'Report_Detailed_Attendance', N'Reports/TA_UI_Report_DetailAttendance.aspx', 144, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (105, N'MustoRollReport', N'Reports/TA_UI_report_EmployeeInOut.aspx', 144, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (118, N'Report_SummaryReport', N'Reports/TA_UI_Report_Summary.aspx', 144, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (45, N'Report_Total_Days', N'Reports/TA_UI_Report_TotalDays.aspx', 144, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (39, N'Report_Punctuality', N'Reports/TA_UI_Report_Punctuality.aspx', 144, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (92, N'Report_ManualTimeEntry', N'Reports/TA_UI_Report_ManualTimeEntry.aspx', 213, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (175, N'Report_OnDutyEntry', N'Reports/TA_UI_Report_OnDutyEntry.aspx', 215, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (145, N'Menu_Reports_Entries', N'', 192, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (34, N'Report_Absent', N'Reports/TA_UI_Report_Absentes.aspx', 145, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (33, N'Report_Discrepancy', N'Reports/TA_UI_Report_Discrepancy.aspx', 213, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (37, N'Report_Late_Entry', N'Reports/TA_UI_Report_LateInstance.aspx', 145, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (127, N'Report_LessHoursWorked', N'Reports/TA_UI_Report_LessHoursWorked.aspx', 145, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (147, N'Menu_Reports_Shifts', N'', 192, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (44, N'Report_Shift', N'Reports/TA_UI_Report_Shift.aspx', 208, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (32, N'Report_Employee_Shift_Allocation', N'Reports/TA_UI_Report_EmployeeShiftAllocation.aspx', 208, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (36, N'Report_Overtime', N'Reports/TA_UI_Report_OverTime.aspx', 214, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (35, N'Report_Leave', N'Reports/TA_UI_Report_LeaveApplication.aspx', 211, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (117, N'Report_LeavePolicyNotAllocated', N'Reports/TA_UI_Report_LeavePolicyNotAllocated.aspx', 211, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (183, N'Report_RawData', N'Reports/TA_UI_Report_RawData.aspx', 144, 9, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (89, N'Report_Permission', N'Reports/TA_UI_Report_Permission.aspx', 236, 5, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (42, N'Report_Employee_Details', N'Reports/TA_UI_Report_Employee.aspx', 205, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (84, N'Report_EmployeeHistory', N'Reports/TA_UI_Report_EmployeeHistory.aspx', 205, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (71, N'Report_Payroll', N'Reports/TA_UI_Report_PayRoll.aspx', 219, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (70, N'Report_Year_Closure', N'Reports/TA_UI_Report_YearClosure.aspx', 219, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (79, N'Report_Audit_Trail', N'Reports/TA_UI_Report_AuditTrail.aspx', 147, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (43, N'Report_Document_Expiry', N'Reports/TA_UI_Report_DocumentExpiry.aspx', 147, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (160, N'Report_WeeklyWorkHours', N'Reports/TA_UI_Report_WeeklyWorkHours.aspx', 147, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (171, N'Report_CountFactor_WorkingDays', N'Reports/TA_UI_Report_TotalWorkingDays.aspx', 147, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (47, N'Org_Level_Settings', N'Organization Settings/Organization_levels.aspx', 189, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (51, N'Org_Shift_Settings', N'Organization Settings/Organization_shiftSetting.aspx', 194, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (52, N'Org_Holiday_Setting', N'Organization Settings/Organization_HolidaySetting.aspx', 194, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (50, N'Org_Year_Setting', N'Organization Settings/Organization_YearSetting.aspx', 194, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (103, N'Flexi_Settings_Menu', N'Organization Settings/Organization_EmployeeFlexiEligible.aspx', 204, 6, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (48, N'Org_Temporary_Weekday', N'Organization Settings/Organization_Tempweekdaylist.aspx', 193, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (49, N'Org_Additional_Weeklyoff', N'Organization Settings/Organization_AddlWeekoff.aspx', 193, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (72, N'Org_Login_List', N'Organization Settings/LoginList.aspx', 193, 7, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (53, N'Org_News', N'Organization Settings/Organization_NewsView.aspx', 193, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (54, N'System_Change_Password', N'System Settings/System_ChangePassword.aspx', 190, 2, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (55, N'System_Reset_Password', N'System Settings/System_ResetPassword.aspx', 190, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (104, N'Import_Data', N'System Settings/importEmployee.aspx', 204, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (66, N'System_Export_Data', N'System Settings/ExportData.aspx', 218, 3, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (78, N'System_Audit_Trail', N'System Settings/System_AuditTrail.aspx', 193, 4, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (75, N'System_MultiLingual', N'System Settings/System_Multilingual.aspx', 194, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (107, N'System_LicenseManager', N'', 193, 8, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (109, N'System_DatabaseInformation', N'System Settings/SystemSetting_DatabaseInformation.aspx', 193, 10, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu])  VALUES (246, N'Menu_Master_MyCalendar', N'MyCalendar.aspx', 0, 0.1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu])  VALUES (254, N'Menu_CompOffCreditEntry', N'Transactions/TA_UI_Transactions_ManualCompensationEntry.aspx', 214, 1, NULL)
INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (255, N'NearestShiftAllocation', N'Transactions/TA_UI_Transaction_NearestShiftAllocation.aspx', 207, 3, NULL)

INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (249, N'Menu_help', N'Help/Help.aspx', 0, 15, NULL)

--User Group Table
INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N'SuperAdmin', 0, NULL, GETDATE(), 0, NULL)
INSERT  INTO [dbo].[TA_Tbl_Usergroup] ([groupName], [IndividualUsers], [hasSpecialRights], [timeStamp], [isDeleted], [Emp_Id]) VALUES (N'IndividualUsers', 1, 0, GETDATE(), 0, N'1')
--User Rights Table
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 144, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 145, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 147, 192, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 19, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 20, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 69, 206, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 28, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 29, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 60, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 76, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 116, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 44, 208, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 32, 208, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 22, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 23, 216, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 248, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 27, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 62, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 96, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 108, 210, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 35, 211, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 89, 236, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 117, 211, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 26, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 97, 214, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 98, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 102, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 92, 213, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 173, 215, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 175, 215, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 10, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 15, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 68, 187, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 17, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 18, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 94, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 95, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 42, 205, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 84, 205, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 103, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 6, 189, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 12, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 99, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 100, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 197, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 47, 189, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 48, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 49, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 50, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 51, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 53, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 72, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 21, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 30, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 36, 214, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 39, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 41, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 40, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 45, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 105, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 118, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 43, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 79, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 71, 219, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 70, 219, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 16, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 52, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 37, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 34, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 33, 213, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 127, 145, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 198, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 66, 218, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 75, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 67, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 77, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 106, 194, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 109, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 54, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 55, 190, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 104, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 107, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 78, 193, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 160, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 171, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 216, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 180, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 183, 144, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 199, 107, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 195, 209, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 196, 209, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 232, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 204, 188, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 205, 188, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 206, 235, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 207, 235, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 208, 235, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 209, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 210, 236, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 211, 236, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 212, 237, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 213, 237, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 218, 217, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 219, 217, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 201, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 202, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 203, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 220, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 221, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 222, 212, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 223, 10, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 224, 10, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 225, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 226, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 227, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 228, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 229, 204, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 230, 12, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 231, 12, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 233, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 234, 147, 0, 0, 0, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 179, 179, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'Superadmin', 1, 177, 177, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 243, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 244, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 245, 194, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 246, 246, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 254, 214, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin', 1, 255, 207, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'SuperAdmin',1,249,249,1,1,1,1,1,GETDATE(),1)
--Employee Table
INSERT  INTO [dbo].[TA_Tbl_Employee] ([UserGroup_Id], [ShiftPattern_Id], [Bus_Id], [Employee_FirstName], [Employee_MiddleName], [Employee_LastName], [Father_name], [Mother_name], [DateofBirth], [DateofBirth_Record], [Blood_Group], [EmailId], [Contact_Address], [Permanent_Address], [Phone_Number], [Mobile_Number], [Gender], [Marital_status], [Nationality], [Religion], [Photo], [Personal_mailid], [Passport_No], [Passport_expirydate], [Visa_No], [Visa_expirydate], [Vehicle_Type], [Vehicle_No], [Anniversary_Date], [Native_Place], [District], [State], [Country], [Spouse_No], [Children_No], [Employee_Code_Id], [DateOfJoining], [Reporting_To], [Leave_Sanc_Authority], [Prev_Experience], [UserName], [Emp_password], [Qual_JoiningTime], [Qual_Employment], [OutDoorJob], [CompOff_Eligible], [OT_Eligible], [ESI_Eligible], [PF_Eligible], [Report_Exclude], [Employee_Status], [SwipeCardNo], [Time_Stamp], [Emp_ID], [Isdeleted], [Hostel], [IsComplete], [IsFlexible], [InActiveDate], [CustomField1], [CustomField2], [CustomField3], [CustomField4], [CustomField5], [Isdeleted_Status], [InActive_Status], [IsImported]) VALUES (1, NULL, NULL, N'Administrator', N'', N'', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, N'18000000', NULL, NULL, NULL, NULL, N'Admin', N'QL5OWbmiorXf+5GMDoaz1w==', NULL, NULL, 0, 1, 1, 0, 0, 1, 1, N'18000000', GETDATE(), NULL, 0, NULL, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0)
--Language Table
INSERT  INTO [dbo].[TA_Tbl_MultiLingual] ([Language_Name], [Resource_File_Name], [IsActive]) VALUES ( N'English', N'Resource_EN', 1)
INSERT  INTO [dbo].[TA_Tbl_MultiLingual] ([Language_Name], [Resource_File_Name], [IsActive]) VALUES ( N'Arabic', N'Resource_AR', 0)
INSERT  INTO [dbo].[TA_Tbl_DateandTimeFormat] ([DateFormat], [TimeFormat], [Time_Stamp], [Emp_Id],[isDomain]) VALUES (N'MM/dd/yyyy', N'hh:mm tt', GETDATE(), 1,1)
INSERT  INTO [dbo].[TA_Tbl_Version] ([DatabaseVersionNo], [DatabaseVersionName], [ApplicationVersionNo], [ApplicationVersionName], [DatabaseVersionDate], [ApplicationVersionDate]) VALUES (1, N'TimeCheck_DB_V2.9', 1, N'TimeCheck_AP_V2.9', GETDATE(), GETDATE())
INSERT  INTO [dbo].[TA_Tbl_Shift] ([Level_Id], [Shift_Name], [Shift_ShortName], [Shift_Description], [Shift_StartTime], [Shift_EndTime], [Shift_FirstHalf_StartTime], [Shift_FirstHalf_EndTime], [Shift_SecondHalf_StartTime], [Shift_SecondHalf_EndTime], [Shift_GraceInTime], [Shift_GraceOutTime], [Shift_BreakStartTime1], [Shift_BreakEndTime1], [Shift_BreakStartTime2], [Shift_BreakEndTime2], [Shift_BreakStartTime3], [Shift_BreakEndTime3], [Shift_MinTimeOT], [Shift_MaxTimeOT], [Shift_WorkingDay_OverTime], [Shift_TotalWorkingHours], [Isdeleted], [Emp_ID], [Shift_FirstHalfWorkingHours], [Shift_SecondHalfWorkingHours], [IsBreakDeducted], [DefaultShift], [ShiftType], [CreatedDate], [ModifiedDate], [24HrsShift]) VALUES (0, N'No Shift', N'NOS', N'No Shift', N'07:00 AM', N'07:00 PM', N'07:00 AM', N'01:00 PM', N'01:00 PM', N'07:00 PM', N'00:05', N'00:05', NULL, NULL, NULL, NULL, NULL, NULL, N'01:00', N'07:30', 1, N'12:00', 0, N'1', N'06:00', N'06:00', 1, 0, 0, NULL, NULL, 0)
INSERT  INTO [dbo].[TA_Tbl_ShiftSettings] ([CompanyId], [MaxHoursBeforeShift], [MaxHoursAfterShift], [ShiftBreak], [ShiftMaxBreakHours], 
[MonthlyWorkingHours], [WeeklyWorkingHours], [EmpID], [HolidayOT], [WeekOffOT], [otOption], [DefaultMonthClosureDate], [IsFlexible], 
[FlexibleFlag], [OTRoundoffEnable], [FullDayAttendanceHrs], [HalfDayAttendanceHrs], [HalfDayAttendance], [FullDayAttendance],
[WeeklyOffStartHours], [IgnoreDuplicatePunch], [PunchInterval], [AfterShiftTime], [BeforeShiftTime], [DefinedWorkhrs], [NoOfSuccessiveDaysInYear],
[CompensationValitityDays], [VaildityCompOffDays], [HalfDayCompOff], [FullDayCompOff], [LateEntry], [EarlyEntry], [EarlyExit], [LateExit], [TimeStamp],
[TimeStamp1], [IsLunchDeduction], [LunchDeductionHours], [Flexi_AfterShiftTime], [Flexi_BeforeShiftTime], [Flexi_DefinedWorkhrs], 
[MaxHoursBeforeShift_24HrsShift], [WeeklyOffStartHours_24HrsShift], [CumulativeWeekStartDay], [CumulativeWeekEndDay], [MonthStartDay], [MonthEndDay],
[Carry_Forward_COff_Year], [isRequestingforCompOff], [LateMinsPerDay] ,[LateDaysPerMonth], [EarlyExitMinsPerDay],[EarlyExitDaysPerMonth],[EnableAbsent] ) 

VALUES (-1, N'02:00', N'02:00', N'', N'', N'', N'', N'1', CAST(1.0 AS Decimal(18, 1)),    CAST(1.0 AS Decimal(18, 1)),    N'WeeklyOff', DATEADD(MONTH,DATEDIFF(MONTH,0,dateadd(month,-1,GETDATE())),-1), 0, 0, 0, N'', N'', 1, 1,
N'16:00', 1, N'00:10', 1, 1, 1, 30,	 0, 90, N'11:00', N'12:00', 1, 1, 1, 1,	 NULL, NULL, 0, N'00:00', 0, 0, 0, N'00:02', N'23:00', N'1', N'7',N'1',N'31',1,0,30,3,20,5,1)


insert into Ta_tbl_EmailScripts (ScriptId,ScriptText,ScriptType) values ('1','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%" height="25"><b><span class="Header">&nbsp;<<lblleaveapplicationform>></span></b>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td height="19" width="30%">  <b><font face="Arial" size="2"><<lblemployeeid>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<employeeid>></font></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblemployeename>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<employeename>></font></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblapplicationdate>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<applicationdate>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblleavetype>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<leavetype>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblnumberdaysapplied>></font></b></td>  <td height="19"><font face="Arial" size="2">&nbsp;<<numberdaysapplied>></font></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblleavedate>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblfromdate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<fromdate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lbltodate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<todate>></font></td></tr></table></td></tr>  <tr><td height="19"><b><font face="Arial" size="2"><<lblsession>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="Table1">  <tr><td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblfromsession>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<fromsession>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lbltosession>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<tosession>></font></td></tr></table></td></tr><tr>  <td height="19"><b><font face="Arial" size="2"><<lblreason>></font></b></td><td height="19">  <font face="Arial" size="2">&nbsp;<<reason>></font></td></tr></table>  <br/><a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>  </body></html>','New Leave Application Form')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('3','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span class="Header">&nbsp;<<PermissionForm>></span>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>> </font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">      <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> :</font></b></td>  <td width="36%">      <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">      <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">      <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr>  </table>  <br/>   <a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>  </body>  </html>','New Permission Form')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('4','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span class="Header">&nbsp;<<PermissionForm>></span>  </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>> </font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">  <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> : </font></b>  </td>  <td width="36%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td height="19">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td height="19">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr>  </table>  <br/>   <a href=<<LinkData>>>      <font face="Arial" size="2">Click here for approval</font></a>   </body>  </html>','Permission Modify Form')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('5','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%"> <b> <span class="Header">&nbsp;<<lblPermissionSanction>></span> </b> </td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1" height="122">  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td width="70%" height="16">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="14%">  <b><font face="Arial" size="2">&nbsp;<<lblFromTime>> :</font></b></td>  <td width="36%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="10%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr> <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblReason>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Reason>></font></td>  </tr> <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table>  <br />      <a href=<<LinkData>>><font face="Arial" size="2">Click here for approval</font></a>   </body>  </html>','Permission Application Sanction By Reporting to Person')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('6','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%">  <span>&nbsp;<<lblPermissionSanction>></span></td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1" height="122">  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeId>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermissionDate>></font></b>  </td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<PermissionDate>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblNumberOfHoursApplied>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<NumberOfHoursApplied>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblPermission>></font></b></td>  <td width="70%" height="16">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="10%">  <b><font face="Arial" size="2"><<lblFromTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<FromTime>></font></td>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblToTime>> :</font></b></td>  <td width="40%">  <font face="Arial" size="2"><<ToTime>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="16">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr>  <tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table>  </body>  </html>','Forwarded Permission Application Sanction')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('7','<html>  <body direction="<<ltr_rtl>>">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="700" id="AutoNumber2">  <tr bgcolor="#003466">  <td width="100%"><b>  <span>&nbsp;<<lblLeaveApplicationForm>></span></b></td>  </tr>  </table>  <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"  width="700" id="AutoNumber1">  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeId>> </font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeId>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblApplicationDate>> </font></b>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<ApplicationDate>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblLeaveType>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<LeaveType>></font>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblNumberDaysApplied>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<NumberDaysApplied>></font></td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblLeaveDate>></font></b>  </td>  <td width="70%" height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="AutoNumber3">  <tr>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%">  <b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<ToDate>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblSession>></font></b></td>  <td width="70%" height="19">  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"  bordercolor="#111111" width="100%" id="Table1">  <tr>  <td width="8%">  <b><font face="Arial" size="2">&nbsp;<<lblFromSession>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<FromSession>></font></td>  <td width="5%">  <b><font face="Arial" size="2">&nbsp;<<lblToSession>> :</font></b></td>  <td width="25%">  <font face="Arial" size="2"><<ToSession>></font></td>  </tr>  </table>  </td>  </tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblStatus>></font></b></td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<Status>></font></td>  </tr><tr><td height="19"><b><font face="Arial" size="2"> <<lblreason>> </font></b></td><td height="19"><font face="Arial" size="2">&nbsp;<<reason>> </font></td></tr>  <tr>  <td width="30%" height="19">  <b><font face="Arial" size="2"><<lblRemarks>></font></b><lblremarks>  </td>  <td width="70%" height="19">  <font face="Arial" size="2">&nbsp;<<Remarks>></font></td>  </tr>  </table><br/><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval</a></font>  </body>  </html>','Leave Application Sanction By Reporting to Person')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('9','<html><body direction="<<ltr_rtl>>">
<table width="750px" style="border: solid 1px black;"   cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;">
<td style="width: 100%;"> <img src="cid:image1" style="float: left;  padding-left: 10px; border: none;">
<a href="http://www.angleritech.com" target="_blank">
<img src="cid:imgCompLogo" align="right" style="float: right; padding-right:10px; padding-top:10px; border: none;" /></a></td></tr>
<tr><td style="background-color: #E0E6EE;"><br />
<table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="AutoNumber2">
<tr><td     width="100%" style="padding-left: 10px;"><b><font face="Verdana" color="#000">Dear     Admin,</font></b></td></tr>
<tr><td height="12"></td></tr><tr><td width="100%"     style="padding-left: 10px;">
<font face="Verdana" color="#000"     size="2"><<licenserequestdetails>></font></td></tr><tr><td     height="35"></td></tr></table>  
<table border="1" cellpadding="2" style="margin-left: 30px;display:none;"     bordercolor="#666666" width="400 px" id="AutoNumber1">
<tr><td width="80%"     height="19"><font face="Verdana" size="2"><<lblemployee>></font></td>
<td     width="20%" height="19" style="text-align: left;"><b><font face="Verdana"     size="2"><<employee>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblconcurrentusers>> </font>  </td>
<td height="19" style="text-align: left;"><b><font face="Verdana"     size="2"><<concurrentusers>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblterminals>></font></td>
<td height="19"     style="text-align: left;"><b><font face="Verdana"     size="2"><<terminals>></font></b></td></tr>
<tr><td height="19"><font     face="Verdana" size="2"><<lblversion>></font></td><td height="19"     style="text-align: left;">
<b><font face="Verdana"     size="2"><<version>></font></b></td></tr></table>  <table style="width: 100%; padding-left: 20px;">
<tr><td colspan="2"     height="35"></td></tr><tr><td colspan="2" height="19" style="padding-left: 10px;">
<font face="Verdana" color="#000" size="2"><<regards>></font></td></tr><tr><td colspan="2" height="19" style="padding-left: 10px;">
<font face="Verdana" color="#000"     size="2"><<clientname>></font></td></tr></table><br /></td></tr>
<tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;">
<a href="http://www.angleritech.com" target="_blank" style="text-decoration: none; color: #224d6a;padding-right: 10px;">Angler Technologies </a></td></tr></table></body></html>','License Request')


insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('10','<html><body direction="<<ltr_rtl>>">  
<table width="750px" style="border: solid 1px black;" cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;"> 
<td style="width: 100%;">  <img src="cid:image1" style="float: left; padding-left: 10px; border: none;">
<a href="http://www.angleritech.com" target="_blank"> <img src="cid:imgCompLogo" align="right" style="float: right;    padding-right: 10px; padding-top: 10px; border: none;" /></a></td></tr><tr>  
<td style="background-color: #E0E6EE;"><br />
<table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="Table1">  
<tr><td width="100%" style="height: 18px" style="padding-left: 10px;">
<font face="Verdana" color="#000"> <<licenserequestusername>>,</font></td></tr>  <tr><td height="12"></td></tr><tr>
<td width="100%" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<licenserequestdetails>></font></td></tr>
<tr><td height="35"></td></tr>  </table>
<table border="1" cellpadding="2" style="margin-left: 30px;display:none;" bordercolor="#666666" width="400" id="Table2"> 
<tr><td width="80%" height="19"><font face="Verdana" size="2"><<lblemployee>></font></td>  
<td width="20%" height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<employee>></font></b></td></tr>  
<tr><td height="19" ><font face="Verdana" size="2"><<lblconcurrentusers>> </font></td>  <td height="19"  style="text-align: left;"><b>
<font face="Verdana" size="2"><<concurrentusers>></font></b></td></tr>  <tr><td height="19" >
<font face="Verdana" size="2"><<lblterminals>></font></td>  <td height="19"  style="text-align: left;"><b>
<font face="Verdana" size="2"><<terminals>></font></b></td>  </tr><tr><td height="19" ><font face="Verdana" size="2"><<lblversion>></font></td> 
<td height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<version>></font></b></td></tr>  </table><br />
<table style="width: 100%; padding-left: 20px;"><tr><td colspan="2" height="35"></td></tr>  <tr>
<td colspan="2" height="19" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<regards>></font></td></tr> 
<tr><td colspan="2" height="19" style="padding-left: 10px;"><font face="Verdana" color="#000" size="2"><<clientname>></font></td>
</tr></table><br />  </td></tr><tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;"> 
<a href="http://www.angleritech.com" target="_blank" style="text-decoration: none; color: #224d6a; padding-right: 10px;">Angler Technologies </a></td>
  </tr></table></body></html>','License Request Client')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('11','<html><body direction="<<ltr_rtl>>"><table width="750px" style="border: solid 1px black;" cellspacing="0" cellpadding="0"><tr style="background-color: #d3dbe7;"> <td style="width: 100%;"><img src="cid:image1" style="float: left; padding-left: 10px; border: none;"><a href="http://www.angleritech.com" target="_blank"><img src="cid:imgCompLogo"  align="right"  style="float: right; padding-right: 10px; padding-top: 10px; border: none;" /></a></td></tr><tr>
<td style="background-color: #E0E6EE;"><br /><table border="0" cellpadding="0" cellspacing="0" style="padding-left: 20px;" bordercolor="#111111" width="700" id="Table1"><tr><td height="12"></td></tr><tr><td width="100%" style="padding-left: 10px;"><font face="Verdana" color="#000"><<licenserequestdetails>></font></td></tr><tr><td height="35"></td></tr></table>
<table border="1" cellpadding="2" style="margin-left: 30px;" bordercolor="#666666" width="400" id="Table2"><tr><td width="80%" height="19"><font face="Verdana" size="2"><<lblemployee>></font></td><td width="20%" height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<employee>></font></b></td></tr><tr><td height="19" ><font face="Verdana" size="2"><<lblconcurrentusers>> </font></td><td height="19"  style="text-align: left;"><b><font face="Verdana" size="2"><<concurrentusers>></font></b></td></tr><tr><td height="19" ><font face="Verdana" size="2"><<lblterminals>></font></td><td height="19"  style="text-align: left;"><b><font face="Verdana" size="2"><<terminals>></font></b></td>
</tr><tr><td height="19" ><font face="Verdana" size="2"><<lblversion>></font></td><td height="19" style="text-align: left;"><b><font face="Verdana" size="2"><<version>></font></b></td></tr></table><br /><table style="width: 100%; padding-left: 20px;"><tr><td colspan="2" height="35"></td></tr><tr><td colspan="2" height="19"><<regards>></td></tr><tr><td colspan="2" height="19"><<clientname>></td></tr></table><br />
</td></tr><tr style="background-color: #d3dbe7;"><td style="width: 100%; text-align: right;"><a href="http://angeritech.com" target="_blank" style="text-decoration: none; color: #224d6a; padding-right: 10px;">Angler Technologies </a></td></tr></table></body></html>','License Activation')

insert into Ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values ('12','<html>  <body direction="<<ltr_rtl>>"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="700" id="AutoNumber2">    <tr bgcolor="#003466">  <td width="100%" height="25"><span class="Header">&nbsp;<<lblOndutyForm>></span></td>    </tr></table><table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"    width="700" id="AutoNumber1">    <tr>  <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblApplicationDate>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<ApplicationDate>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblODDate>></font></b>  </td>  <td height="19"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="100%" id="AutoNumber3">    <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<ToDate>></font></td>    </tr></table>  </td>    </tr>  <tr>  <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font>  </td>    </tr>   <tr>  <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font>  </td>    </tr></table>  </body>  <br /><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval </a></font>  </html>','Onduty Application From')

insert into TA_TBL_EmailScripts (ScriptId,ScriptText,ScriptType) values ('13','<html>  <body direction="<<ltr_rtl>>"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="700" id="AutoNumber2">    <tr bgcolor="#003466">  <td width="100%" height="25"><b><span class="Header">&nbsp;<<lblOndutyForm>></span></b></td>    </tr></table><table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666"    width="700" id="AutoNumber1">    <tr>  <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b>  </td>  <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblApplicationDate>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<ApplicationDate>></font>  </td>    </tr>    <tr>  <td height="19"><b><font face="Arial" size="2"><<lblODDate>></font></b>  </td>  <td height="19"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"    bordercolor="#111111" width="100%" id="AutoNumber3">    <tr>  <td width="8%"><b><font face="Arial" size="2">&nbsp;<<lblFromDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<FromDate>></font></td>  <td width="5%"><b><font face="Arial" size="2">&nbsp;<<lblToDate>> :</font></b></td>  <td width="25%"><font face="Arial" size="2"><<ToDate>></font></td>    </tr></table>  </td>    </tr>  <tr>  <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font>  </td>    </tr><tr>  <td width="30%" height="16">  <b><font face="Arial" size="2"><<lblRemarks>></font></b></td>  <td width="70%" height="16">  <font face="Arial"><font size="2">&nbsp;<<Remarks>></font></td>  </tr>   <tr>  <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b>  </td>  <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font>  </td>    </tr></table>  </body>  <br /><font face="Arial" size="2"><a href="<<LinkData>>">Click here for approval </a></font>  </html>','Onduty Application Modify')

insert into ta_tbl_emailscripts (ScriptId,ScriptText,ScriptType) values(14,'
<font face="Arial" size="2">
Dear <<lblusername>>,
</font>
<br/>
<br/>
<font face="Arial" size="2">Your Timecheck password has been reset successfully.
</font>
<br/>
<br/>
<font face="Arial" size="2">
Note:Use the default password <b>(i.e. welcome)</b> of timecheck for login right now. 
After the successful login into Timecheck, change the password immediately.
</font>
<br/>
<br/>
<font face="Arial" size="2">Regards,</font>
<br/>
<font face="Arial" size="2">TimeCheck</font>','ResetPassword')

insert into TA_TBL_EmailScripts (ScriptId,ScriptText,ScriptType) values (15,'<html>
<body direction="<<ltr_rtl>>">
    <table border="1" cellpadding="2" style="border-collapse: collapse" bordercolor="#666666" width="600" id="AutoNumber1">
	<tr bgcolor="#003466">
            <td width="100%" height="25" colspan=''2''><b><span class="Header">&nbsp;<<lblCompform>></span></b></td>
        </tr>
        <tr>
            <td height="19" width="30%"><b><font face="Arial" size="2"><<lblEmployeeID>></font></b></td>
            <td height="19" width="70%"><font face="Arial" size="2">&nbsp;<<EmployeeID>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblEmployeeName>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<EmployeeName>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblDutyDate>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<DutyDate>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblInTime>></font> / <font face="Arial" size="2"><<lblOutTime>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<Intime>></font> / <font face="Arial" size="2">&nbsp;<<OutTime>></font></td>
        </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblDayWorked>></font> / <font face="Arial" size="2"><<lblWorkedHours>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<DayWorked>></font> / <font face="Arial" size="2">&nbsp;<<WorkedHours>></font></td>
        </tr>
              <tr style=''display:<<disvalue>>''>
                     <td height="19"><b><font face="Arial" size="2"><<lblReason>></font></b></td>
                     <td height="19"><font face="Arial" size="2">&nbsp;<<Reason>></font></td>
              </tr>
        <tr>
            <td height="19"><b><font face="Arial" size="2"><<lblStatus>></font></b></td>
            <td height="19"><font face="Arial" size="2">&nbsp;<<Status>></font></td>
        </tr>
    </table>
</body>
</html>','CompOff Application form')

INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (50, N'Ta_Tbl_yearsetting', N'Organization_YearSetting.aspx', N'../Organization%20Settings/Organization_YearSetting.aspx', N'Year Settings in Configuration', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (6, N'TA_Tbl_leveldetails', N'TA_UI_Master_OrganisationLevels.aspx', N'../Masters/TA_UI_Master_OrganisationLevels.aspx', N'Organization Levels in Organization Management', 3, 1)
--Commented on 15-05-2019 06:56 PM
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (7, N'TA_Tbl_LeavePolicy', N'TA_UI_MasterLeavePolicyAdd.aspx', N'../Masters/TA_UI_MasterLeavePolicyAdd.aspx', N'Leave Policy Master', 2, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (223, N'TA_Tbl_terminaldatatype', N'TA_UI_Master_TerminalDatatypeAdd.aspx', N'../Masters/TA_UI_Master_TerminalDatatypeAdd.aspx', N'Terminal Data Type in Device Management', 1, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (224, N'TA_Tbl_terminal', N'TA_UI_Master_TerminalAdd.aspx', N'../Masters/TA_UI_Master_TerminalAdd.aspx', N'Terminal Master', 3, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (15, N'TA_Tbl_entrance', N'TA_UI_Master_EntranceAdd.aspx', N'../Masters/TA_UI_Master_EntranceAdd.aspx', N'Entrance Master', 1, 1)
--INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (68, N'TA_Tbl_punchTypes', N'TA_UI_Master_PunchTypes_Add.aspx', N'../Masters/TA_UI_Master_PunchTypes_Add.aspx', N'Punch Types', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (17, N'TA_Tbl_Title', N'TA_UI_Master_TitleFirstAdd.aspx', N'../Masters/TA_UI_Master_TitleFirstAdd.aspx', N'Designation', 0, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (18, N'TA_Tbl_Employee', N'TA_UI_Master_EmployeeAdd.aspx', N'../Masters/TA_UI_Master_EmployeeAdd.aspx', N'Employee Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirect] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (28, N'Ta_tbl_permanentshiftallocation', N'TA_UI_Transaction_ShiftAllocationAdd.aspx', N'../Transactions/TA_UI_Transaction_ShiftAllocationAdd.aspx', N'Shift Allocation for Employee', 24, 0)
GO
--Standard Demo
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (50, N'Ta_Tbl_yearsetting', N'Organization_YearSetting.aspx', N'../Organization%20Settings/Organization_YearSetting.aspx', N'Year Settings in Configuration', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (6, N'TA_Tbl_leveldetails', N'TA_UI_Master_OrganisationLevels.aspx', N'../Masters/TA_UI_Master_OrganisationLevels.aspx', N'Organization Levels in Organization Management', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (7, N'TA_Tbl_LeavePolicy', N'TA_UI_MasterLeavePolicyAdd.aspx', N'../Masters/TA_UI_MasterLeavePolicyAdd.aspx', N'Leave Policy Master', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (223, N'TA_Tbl_terminaldatatype', N'TA_UI_Master_TerminalDatatypeAdd.aspx', N'../Masters/TA_UI_Master_TerminalDatatypeAdd.aspx', N'Terminal Data Type in Device Management', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (224, N'TA_Tbl_terminal', N'TA_UI_Master_TerminalAdd.aspx', N'../Masters/TA_UI_Master_TerminalAdd.aspx', N'Terminal Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (15, N'TA_Tbl_entrance', N'TA_UI_Master_EntranceAdd.aspx', N'../Masters/TA_UI_Master_EntranceAdd.aspx', N'Entrance Master', 1, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (68, N'TA_Tbl_punchTypes', N'TA_UI_Master_PunchTypes_Add.aspx', N'../Masters/TA_UI_Master_PunchTypes_Add.aspx', N'Punch Types', 2, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (17, N'TA_Tbl_Title', N'TA_UI_Master_TitleFirstAdd.aspx', N'../Masters/TA_UI_Master_TitleFirstAdd.aspx', N'Designation', 0, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (18, N'TA_Tbl_Employee', N'TA_UI_Master_EmployeeAdd.aspx', N'../Masters/TA_UI_Master_EmployeeAdd.aspx', N'Employee Master', 3, 1)
INSERT [dbo].[Ta_Tbl_PageRedirectStandard] ([PageId], [TableName], [Page], [PageFullPath], [Module], [Rows], [Active]) VALUES (28, N'Ta_tbl_permanentshiftallocation', N'TA_UI_Transaction_ShiftAllocationAdd.aspx', N'../Transactions/TA_UI_Transaction_ShiftAllocationAdd.aspx', N'Shift Allocation for Employee', 24, 1)

INSERT [dbo].[TA_Tbl_Level] ([levelName], [parentLevelID], [isDeleted], [timeStamp], [emp_Id]) VALUES (N'Company', 0, 0, GETDATE(), N'1')
INSERT [dbo].[TA_Tbl_Level] ([levelName], [parentLevelID], [isDeleted], [timeStamp], [emp_Id]) VALUES (N'Department', 1, 0, GETDATE(), N'1')
-----Default Leave Types
insert into TA_Tbl_LeaveType VAlues('CL','Casual Leave',0,1,getdate(),0,0,0,'Both',0,0)
insert into TA_Tbl_LeaveType VAlues('SL','Sick Leave',0,1,getdate(),0,0,0,'Both',0,0)
insert into TA_Tbl_LeaveType VAlues('ML','Maternity Leave',0,1,getdate(),0,0,0,'Both',0,0)
insert into TA_Tbl_LeaveType VAlues('EL','Earned Leave',0,1,getdate(),1,0,0,'Both',0,0)
insert into TA_Tbl_LeaveType VAlues('WFH','Work From Home',0,1,getdate(),1,0,0,'Both',0,1)
insert into TA_Tbl_LeaveType VAlues('PL','Paternity Leave',0,1,getdate(),1,0,0,'Both',0,1)
insert into TA_Tbl_LeaveType VAlues('COM-L','Commuted Leave',0,1,getdate(),1,0,0,'Both',0,1)

insert into TA_Tbl_Category values('Staff',0,1,0,'48',8,'08:00',null,null,null)
insert into TA_Tbl_Type values('Permanent',0,1,0)
insert into TA_Tbl_Religion values('All','All',0)


--Dashboard Rights tabls
insert into ta_tbl_DashboardData values('AttendanceData','Present',1)
insert into ta_tbl_DashboardData values('AttendanceData','Absent',2)
insert into ta_tbl_DashboardData values('AttendanceData','Approved Leave',3)
insert into ta_tbl_DashboardData values('AttendanceData','Approved Onduty',4)
insert into ta_tbl_DashboardData values('AttendanceData','Punctuality',5)
insert into ta_tbl_DashboardData values('AttendanceData','Attendance Summary',6)
insert into ta_tbl_DashboardData values('ApprovalData','Leave',1)
insert into ta_tbl_DashboardData values('ApprovalData','Onduty',2)
insert into ta_tbl_DashboardData values('ApprovalData','Permission',3)
insert into ta_tbl_DashboardData values('ExceptionData','Late Entry',1)
insert into ta_tbl_DashboardData values('ExceptionData','Early Exit',2)
insert into ta_tbl_DashboardData values('ExceptionData','Shift Not Allocated',3)
insert into ta_tbl_DashboardData values('ExceptionData','Approved Overtime',4)
insert into ta_tbl_DashboardData values('ExceptionData','Discrepancy',5)
insert into ta_tbl_DashboardData values('ExceptionData','Non Processed Record',6)

insert into ta_tbl_DashboardUserrights  values(1,1,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,2,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,3,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,4,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,5,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,6,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,7,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,8,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,9,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,10,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,11,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,12,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,13,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,14,1,1,1,1,1)
insert into ta_tbl_DashboardUserrights  values(1,15,1,1,1,1,1)

--Individual usergroup Dashboard rights
insert into ta_tbl_DashboardUserrights  values(2,1,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,2,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,3,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,4,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,5,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,6,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,7,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,8,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,9,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,10,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,11,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,12,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,13,0,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,14,1,1,0,0,1)
insert into ta_tbl_DashboardUserrights  values(2,15,0,1,0,0,1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 179, 179, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 246, 246, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 208, 235, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 32, 208, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 210, 236, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 22, 210, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 211, 236, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 35, 211, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 216, 236,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 23, 216,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 89, 236,  0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 173, 215,  1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 175, 215, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 213, 237, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 33, 213, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 144, 192, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 41, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 39, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 40, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 105, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 183, 144, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 145, 192, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 34, 145, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 37, 145, 0, 0, 0, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES (N'IndividualUsers', 2, 55, 190, 1, 1, 1, 1, 0,GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,0,0,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,50,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,51,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,52,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,16,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,75,194,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,47,189,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,6,189,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,10,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,223,10,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,224,10,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,15,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,68,187,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,204,188,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,17,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,228,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,94,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,95,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,104,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,18,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,103,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,225,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,226,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,227,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,229,204,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,205,188,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,42,205,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,84,205,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,206,235,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,19,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId]) VALUES ('IndividualUsers',	2,20,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,69,206,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,207,235,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,28,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,29,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,255,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,202,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,60,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,116,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])  VALUES ('IndividualUsers',	2,203,207,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,208,235,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,32,208,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,44,208,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,254,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,97,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,36,214,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,209,236,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,195,209,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,196,209,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,108,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,96,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,76,210,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,211,236,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,35,211,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,117,211,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,89,236,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,248,236,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,175,215,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,212,237,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,220,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,26,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,98,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,222,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,102,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,221,212,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,213,237,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,92,213,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,33,213,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,218,217,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,27,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,62,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,66,218,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,219,217,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,71,219,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,70,219,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,144,192,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,41,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,30,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,39,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,180,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,40,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,105,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,45,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,118,144,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,183,144,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,145,192,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,34,145,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,37,145,0,0,0,1,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,127,145,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,147,192,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,160,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,171,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,79,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,265,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,43,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,233,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,232,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,234,147,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,177,177,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,21,190,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,54,190,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,53,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,49,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,48,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,78,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,99,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,100,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,72,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,107,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,197,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,198,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,199,107,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,12,193,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,230,12,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,231,12,0,0,0,0,0,GETDATE(),1)
INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,109,193,0,0,0,0,0,GETDATE(),1)
--INSERT  INTO [dbo].[TA_Tbl_userRights]([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv],[isDeleted], [timeStamp], [employeeId])   VALUES ('IndividualUsers',	2,249,249,0,0,0,0,0,GETDATE(),1)
/*********************/




insert into ta_tbl_SMSTags values('{Employee ID}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Late By Hrs}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','LateEntry',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Early Exit Hrs}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','EarlyExit',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Less Hours}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','LessHours',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','AbsentSingleDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Date}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Count}','AbsentContinuousDay',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Leave From - Leave To}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Leave Type}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{No.of Days}','LeaveApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee ID}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Permission From - Permission To}','PermissionApplication',GETDATE())
GO
insert into ta_tbl_SMSTags values('{No.of Hrs}','PermissionApplication',GETDATE())
Go
insert into ta_tbl_SMSTags values('{Employee ID}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{User Name}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{Employee Name}','OnDuty',GETDATE())
GO
insert into ta_tbl_SMSTags values('{OnDuty From - OnDuty To}','OnDuty',GETDATE())
Go
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (243, N'Menu_SMSConfiguration', N'Masters/SMS_Configuration.aspx', 194, 10, NULL)
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (244, N'Menu_SMSTemplate', N'Masters/SMS_TemplateList.aspx', 194, 11, NULL)
--INSERT  INTO [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) 
--VALUES (245, N'Menu_SMSLogDetails', N'Masters/SMS_LogDetails.aspx', 194, 12, NULL)
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Late Entry', N'Dear {User Name}, The following employees are late comers today', 1, CAST(0x0000A6EF011D1238 AS DateTime), 1, N'03:00', N'01:00', 0, N'', 0, N'{Employee Name}-{Late By Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Early Exit', N'Dear {User Name}, The following employees are left before shift end time', 0, CAST(0x0000A68D00B93DE5 AS DateTime), 1, N'00:05', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Early Exit Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Less Hours Worked', N'Dear {User Name}, The following employees are not met the defined work hours,', 0, CAST(0x0000A689012CF23B AS DateTime), 1, N'01:00', N'', 0, N'00:10', 0, N'{Employee ID}-{Employee Name}-{Less Hours}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Absent - Single Day', N'Dear {User Name}, The following employees are absent today', 1, CAST(0x0000A6EF01047AEA AS DateTime), 1, N'00:59', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Continuous Absent', N'Dear {User Name}, The following employees are continously absent from last {count} days', 0, CAST(0x0000A68D00C0CFEA AS DateTime), 1, N'00:20', N'', 0, N'', 4, N'{Employee ID}-{Employee Name}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Apply', N'Dear {User Name}, The below employees applied the leave for below duration,', 0, CAST(0x0000A68E01209068 AS DateTime), 1, N'', N'', 1, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Forward', N'Dear {User Name}, The following employees leave is forward to approval,', 0, CAST(0x0000A681013554FD AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Leave Application - Approved', N'Dear {User Name}, The below leave was approved,', 0, CAST(0x0000A68101357062 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Leave From - Leave To}-{Leave Type}-{No.of Days}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Apply', N'Dear {User Name}, The below employee applied the permission for below date,', 0, CAST(0x0000A68F00C78563 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Forward', N'Dear Manikandan', 0, CAST(0x0000A6A900D41391 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], [Second_TriggeringTime], 
[ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'Permission Application - Approved', N'Dear {UserName},The following employee permission was approved.', 1, CAST(0x0000A6A900D44EEA AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{Permission From - Permission To}-{No.of Hrs}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Apply', N'Dear {User Name}, The below employee applied the Onduty for below date,', 0, CAST(0x0000A68F00C78563 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Forward', N'Dear {User Name}, the below employee OnDuty forwarded to approval,', 0, CAST(0x0000A6A900D41391 AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
INSERT [dbo].[Ta_Tbl_SMSTemplates] ([TemplateName], [Message], [Status], [LastModified], [ModifiedBy], [First_TriggeringTime], 
[Second_TriggeringTime], [ToEmployee], [LessHrsLimitation], [Continue_AbsentDays], [Tags]) VALUES (N'OnDuty - Approved', N'Dear {UserName},The following employee OnDuty was approved.', 1, CAST(0x0000A6A900D44EEA AS DateTime), 1, N'', N'', 0, N'', 0, N'{Employee ID}-{Employee Name}-{OnDuty From - OnDuty To}')
insert into TA_Tbl_Grade values('Grade 1',1,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 2',2,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 3',3,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 4',4,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 5',5,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 6',6,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 7',7,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 8',8,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 9',9,1,GETDATE(),0)
Insert into TA_Tbl_Grade values('Grade 10',10,1,GETDATE(),0)
Insert into Ta_tbl_ReasonForNonProcessedData values(1,'Employee id is not available')
Insert into Ta_tbl_ReasonForNonProcessedData values(2,'Device is not created')
Insert into Ta_tbl_ReasonForNonProcessedData values(3,'Shift is not allocated')
Insert into Ta_tbl_ReasonForNonProcessedData values(4,'Punch Type is not created for this device')
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (243, N'Menu_SMSConfiguration', N'Masters/SMS_Configuration.aspx', 194, 10, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (244, N'Menu_SMSTemplate', N'Masters/SMS_TemplateList.aspx', 194, 11, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (245, N'Menu_SMSLogDetails', N'Masters/SMS_LogDetails.aspx', 194, 12, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (267, N'AutoShiftConfiguration', N'Transactions/TA_UI_Transaction_AutoShiftConfiguration.aspx', 207, 3, NULL)
INSERT [dbo].[TA_Tbl_Page] ([pageId], [displayName], [path], [parentId], [orderBy], [ParentIdForSubMenu]) VALUES (271, N'CanteenReport', N'Reports/TA_UI_Report_CanteenReport.aspx', 144, 3, NULL)

INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) 
VALUES (N'SuperAdmin', 1, 267, 207, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))
INSERT  INTO [dbo].[TA_Tbl_userRights] ([groupName], [groupId], [pageId], [pageGroupId], [addPrv], [modifyPrv], [deletePrv], [viewPrv], [isDeleted], [timeStamp], [employeeId]) 
VALUES (N'SuperAdmin', 1, 271, 144, 1, 1, 1, 1, 0, GETDATE(), CAST(1 AS Decimal(18, 0)))

Insert into ta_tbl_HelpContent values('How to create employees in TimeCheck?',' <p style="text-align: left !important; padding-left: 10px !important;">
                                        Once you have created the details of your organization, the next step is to add up your employees to application.
                                    </p>
                                    <p style="text-align: left !important; padding-left: 10px !important;">Employees can be added to your organization in any of the below two methods:</p>
                                    <ul>
                                        <li><a href="#">Create Employee(s) manually</a></li>
                                        <li><a href="#">Import Employee(s)</a></li>
                                    </ul>
                                    <p style="text-align: left !important; padding-left: 10px !important;">Create Employee(s) manually is a method to add employees manually to application. You can give the users user id and password. They can change their password later.</p>
                                    <ul>
                                        <li>Click Employee Management > Masters > Employee Master</li>
                                        <li>Click ''Add'' Button, it will redirect to add page for create employee manually.</li>
                                    </ul>
                                    <p style="text-align: left !important; padding-left: 10px !important;">''Import Employee(s)''</p>
                                    <ul>
                                        <li>Click Employee Management > Masters > Master Data Import</li>
                                        <li>Download Template file</li>
                                        <li>Fill the document as per information mentioned in the screen and then upload it</li>
                                    </ul>',GETDATE())
Insert into ta_tbl_HelpContent values('Where to configure Overtime in TimeCheck?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    For calculating overtime on working day , you need to configure overtime in below pages.
                                    <ul>
                                        <li>In Employee master, you need to configure overtime eligible as <b>Yes</b></li>
                                        <li>And then in shift master, you need to configure below fields for overtime calculation.
                                            <ul>
                                                <li>Minimum Extra time for overtime </li>
                                                <li>Maximum Extra time for overtime</li>
                                                <li>And Over Time On Working Days</li>
                                            </ul>
                                        </li>
                                        <li>Based on the above configurations the system will calculate overtime.</li>
                                        <li>Note: if any one of above mentioned fields are not configured, that case the system wont calculate Overtime.</li>
                                    </ul>
                                    For calculating overtime on weekly off and Holiday, you need to configure overtime value in below page.
                                    <ul>
                                        <li>Configuration -> Organization Settings -> OT & Comp Off Tab</li>
                                    </ul>
                                </p>',GETDATE())                                    

Insert into ta_tbl_HelpContent values('How to allocate Shift to employees?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    For allocating the shift to employee(s), please proceed the below steps,
                                    <ul>
                                        <li>Click Shift Management > Transaction > Shift Allocation > Add </li>
                                        <li>Choose the Employee selection mode, based on your needs.</li>
                                        <li>If you want to allocate shift for one employee alone, please choose Single option otherwise choose Multiple option for allocation</li>
                                        <li>Based on the employee selection, it will load shift details into shift dropdown.</li>
                                        <li>Pick the Shift and select the weekly off days</li>
                                        <li>And then enter the from and to date</li>
                                        <li>Click Save Button.</li>
                                        Note:Based on the from and to date mentioning, it will allocate the shift to employee(s).
                                    </ul>
                                </p>',GETDATE())
                                
Insert into ta_tbl_HelpContent values('How to update email id to all employees?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    Using CSV / excel file, we can update email id to all employees within few seconds.
                                    For updating email ids to all employee(s), proceed the below steps.
                                    <ul>
                                        <li>Click Employee Management > Masters > Employee Master > Bulk Configuration Button, it will redirect you to one new window for updation. </li>
                                        <li>Click Download Template Button, it will download one excel file in CSV format.</li>
                                        <li>Fill employee Id, Official / person Email id of the employees.</li>
                                        <li>Then save and close the file</li>
                                        <li>Now click choose file button, it will open one new window. Please choose the file where you are saved the filled document.</li>
                                        <li>And then choose the category as Official Email ID / Personal Email ID option. Based on this selection only, the system will refer the data in excel document and update it into database.</li>
                                        <li>Now click upload button. if it successfully updated into database you will receive updated successfully alert message otherwise you will receive some other alert message.</li>
                                    </ul>
                                </p>',GETDATE())
Insert into ta_tbl_HelpContent values('How many employees can able to create in demo version?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    User can able to create <b>N Number </b>of employees into demo version using Manual creation / Import Master in Timecheck, but they can able to do any transaction / viewing report for <b>5 employees</b> alone in <b>Demo Version</b>.
                                </p>',GETDATE())
Insert into ta_tbl_HelpContent values('How to add devices and Punch Types in TimeCheck?','<p style="text-align: left !important; padding-left: 10px !important;">
                                    To create device:
                                </p>
                                <ul>
                                    <li>Click Device Management > Terminal > Terminal Master</li>
                                    <li>Click ''Add'' Button in list page, it will redirect you to add page for create device manually.</li>
                                    <li>Enter the device ID, Name and select raw data Format (i.e which database the device logs will be saved, that one select here in the dropdown) </li>
                                    <li>Then Click Save Button</li>
                                </ul>
                                <br />
                                <ul>
                                    <li>After creation of devices in terminal master, you need to define which devices are you using as In device and Out device in each door / entrances. Based on this configuration only, we are differentiating each punches as in and out and saved in database.</li>
                                    <li><strong>So whenever you are purchasing / replacing the devices that time you need to create device in terminal master and in Entrance master.</strong></li>
                                </ul>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    To Configure In & Out device:
                                </p>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    To configure In and Out device of each door / entrance, please proceed the below steps,
                                </p>
                                <ul>
                                    <li>Click Device Management > Entrance Master > Add</li>
                                    <li>Click ''Add'' Button in list page, it will redirect you to add page for create device manually.</li>
                                    <li>Enter the meaningful name in Entrance Name field for your quick access in furture if you have more than one entrance.</li>
                                    <li>Then select the Number of In and Out terminal count of this particular entrance.</li>
                                    <li>Based on the selection, it will load the dropdowns, select device in each dropdowns and then Click save button</li>
                                </ul>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    Create Punch Type:
                                </p>
                                <p style="text-align: left !important; padding-left: 10px !important;">
                                    After creation of entrance master, create the punch types for each devices,
                                </p>
                                <ul>
                                    <li>Click Device Management > PunchType Master > Add</li>
                                    <li>Select Device</li>
                                    <li>Select Punch Type</li>
                                    <li>Enter Punch Type value</li>
                                    <li>Click Save Button</li>
                                </ul>',GETDATE())
Insert into ta_tbl_HelpContent values('What is meant by Freescan and Function Key in shift master?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    Free Scan:<br />
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Before doing an punch in device if any key is not pressed by employee, that should be called as Free Scan.
                                    <br />
                                    Function Key:<br />
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Before doing an punch in device any key is pressed by employee, that should be called as Function Key.
                                </p>',GETDATE())                                                                
Insert into ta_tbl_HelpContent values('Where to Configure Mail Domain details for Email Triggerring?','<p style="text-align: left !important; padding: 0px 10px !important;">
                                    Mail Configuration :
                                </p>
                                <ul>
                                    <li>Click Device Management > PunchType Master > Add</li>
                                    <li>Select Device</li>
                                    <li>Select Punch Type</li>
                                    <li>Enter Punch Type value</li>
                                    <li>Click Save Button</li>
                                </ul>',GETDATE())