USE [ICDAS_3_0]
GO
/****** Object:  StoredProcedure [dbo].[UserMaster_LoginValidation]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[UserMaster_LoginValidation]
GO
/****** Object:  StoredProcedure [dbo].[UserGroupAccess_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[UserGroupAccess_ListData]
GO
/****** Object:  StoredProcedure [dbo].[UserGroup_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[UserGroup_Sync]
GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[SMSLog_Sync]
GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[SMSLog_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[SMSLog_ManageTestSMS]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[SMSLog_ManageTestSMS]
GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[SMSLog_Manage]
GO
/****** Object:  StoredProcedure [dbo].[SMSLog_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[SMSLog_ListData]
GO
/****** Object:  StoredProcedure [dbo].[ServiceStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ServiceStatus_Update]
GO
/****** Object:  StoredProcedure [dbo].[ServiceStatus_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ServiceStatus_ListData]
GO
/****** Object:  StoredProcedure [dbo].[IOStatus_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[IOStatus_Service]
GO
/****** Object:  StoredProcedure [dbo].[Get_RunningHours]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Get_RunningHours]
GO
/****** Object:  StoredProcedure [dbo].[Get_IOStatus_RealTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Get_IOStatus_RealTime]
GO
/****** Object:  StoredProcedure [dbo].[Get_Equipment_RunningHours]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Get_Equipment_RunningHours]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentType_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentType_List]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentSupervisorEmail_LogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentSupervisorEmail_LogDateTime]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentSupervisorEmail]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentSupervisorEmail]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentStatus_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_Status_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterWrite_Status_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterWrite_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterWrite_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterVersionUpdate_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterVersionUpdate_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterRunningHours_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterRunningHours_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_UpdateColor]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_UpdateColor]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Unit_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_Unit_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_Populate]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_ListData_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_ListData_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_CreateList]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterParameter_CreateList]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterOnlineStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterOnlineStatus_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMovingLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterMovingLog_CreateTable]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMKT_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterMKT_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMKT_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterMKT_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApproveAuditTrail_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogReviewApproveAuditTrail_rpt]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_rpt]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_rpt_old]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogMKT_rpt_old]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogMKT_rpt]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_GetPending]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogMKT_GetPending]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogMKT_Delete]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogManage_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLogManage_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_rpt1]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_rpt1]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_rpt]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_LogDateTime_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_LogDateTime_Populate]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_LastLogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_LastLogDateTime]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterLog_CreateTable]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterHourlyLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterHourlyLog_CreateTable]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAuditTrail_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAuditTrail_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAuditTrail_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_LookUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAuditTrail_LookUp_Populate]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLookUp_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmLookUp_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLogManage_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmLogManage_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLog_LastLogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmLog_LastLogDateTime]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_List]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Update_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Update_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_TimerProcess]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_TimerProcess]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_SynDate_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_SynDate_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_SyncDate_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_SyncDate_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Search]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Reset_Request]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Reset_Request]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_RealTimeSummary]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_RealTimeSummary]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Populate]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_List_Service]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_List_Service]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_List]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_HomePage_Display]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_HomePage_Display]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_GetEquipmentType]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_GetEquipmentType]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_DoorAccess_AuditTrail]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_DoorAccess_AuditTrail]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Department_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Department_Populate]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_DemoApp_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_DemoApp_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_Delete]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_CheckActiveEquipment]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentMaster_CheckActiveEquipment]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentIOStatus_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentIOStatus_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_Insert]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentIOStatus_Insert]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentComponentRunningHours_Update]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentComponentRunningHours_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentComponentRunningHours_ListData]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Insert]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentComponentRunningHours_Insert]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentAlarmConfig_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentAlarmConfig_List]
GO
/****** Object:  StoredProcedure [dbo].[EquipmentAlarmConfig_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EquipmentAlarmConfig_Delete]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_Sync]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ManageTestMail]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_ManageTestMail]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_Manage]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ListData_TestMail]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_ListData_TestMail]
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[EmailLog_ListData]
GO
/****** Object:  StoredProcedure [dbo].[DoorAccessUsers_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[DoorAccessUsers_Update]
GO
/****** Object:  StoredProcedure [dbo].[Department_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Department_Search]
GO
/****** Object:  StoredProcedure [dbo].[Department_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Department_Manage]
GO
/****** Object:  StoredProcedure [dbo].[Department_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Department_List]
GO
/****** Object:  StoredProcedure [dbo].[Department_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Department_Delete]
GO
/****** Object:  StoredProcedure [dbo].[dbo.App_Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[dbo.App_Company_Manage]
GO
/****** Object:  StoredProcedure [dbo].[Database_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Database_Sync]
GO
/****** Object:  StoredProcedure [dbo].[CompanyMaster_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[CompanyMaster_List]
GO
/****** Object:  StoredProcedure [dbo].[Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Company_Manage]
GO
/****** Object:  StoredProcedure [dbo].[Company_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Company_List]
GO
/****** Object:  StoredProcedure [dbo].[Company_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Company_Delete]
GO
/****** Object:  StoredProcedure [dbo].[Company_Activation_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Company_Activation_Update]
GO
/****** Object:  StoredProcedure [dbo].[Company_Activation]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[Company_Activation]
GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[CommGroup_Search]
GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[CommGroup_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[CommGroup_Populate]
GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[CommGroup_Manage]
GO
/****** Object:  StoredProcedure [dbo].[BusinessUnit_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[BusinessUnit_Delete]
GO
/****** Object:  StoredProcedure [dbo].[BranchMaster_SupervisorEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[BranchMaster_SupervisorEmailTime]
GO
/****** Object:  StoredProcedure [dbo].[BranchMaster_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[BranchMaster_Populate]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestSMSTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_TestSMSTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestSMSTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_TestSMSTime]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestEmailTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_TestEmailTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_TestEmailTime]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_SYNCTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_SYNCTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_SMSCheck]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_SMSCheck]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_ListData]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_List]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_EmailCheck]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_EmailCheck]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_CheckStatus]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_CheckStatus]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BIOSYNCTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_BIOSYNCTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BackupTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_BackupTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BackupTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[ApplicationSetup_BackupTime]
GO
/****** Object:  StoredProcedure [dbo].[AppCompany_SupervisorEmailTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AppCompany_SupervisorEmailTime_Update]
GO
/****** Object:  StoredProcedure [dbo].[AppCompany_SupervisorEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AppCompany_SupervisorEmailTime]
GO
/****** Object:  StoredProcedure [dbo].[AppCompany_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AppCompany_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Update_Login_Status]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Update_Login_Status]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Sync]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Search]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Password_Change]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Password_Change]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Manage]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login_Temp_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Login_Temp_Update]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login_Temp_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Login_Temp_List]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Login]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_List]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_DepartmentWise_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_DepartmentWise_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Department_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Department_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_Delete]
GO
/****** Object:  StoredProcedure [dbo].[App_Users_AuditTrail_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Users_AuditTrail_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[App_UserMasterAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserMasterAuditTrail_Sync]
GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_Update_Login_Status]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserMaster_Update_Login_Status]
GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_Login]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserMaster_Login]
GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_AuditTrail]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserMaster_AuditTrail]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroupAccess_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroupAccess_Manage]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroupAccess_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroupAccess_ListData]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_Sync]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_Search]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_Manage]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_List]
GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_UserGroup_Delete]
GO
/****** Object:  StoredProcedure [dbo].[App_Reports_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Reports_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_ProjectSearch_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_ProjectSearch_List]
GO
/****** Object:  StoredProcedure [dbo].[App_ProjectMenu_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_ProjectMenu_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_ProjectMenu_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_ProjectMenu_List]
GO
/****** Object:  StoredProcedure [dbo].[App_General_Delete]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_General_Delete]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Sync]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_Sync]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Search]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_Search]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_Manage]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_ListData]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_ListData]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_List]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_AlarmEvent_Update]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_AlarmEvent_Update]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_AlarmEvent_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_AlarmEvent_List]
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Accesible_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_Company_Accesible_List]
GO
/****** Object:  StoredProcedure [dbo].[App_CombinedReport_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_CombinedReport_Rpt]
GO
/****** Object:  StoredProcedure [dbo].[App_AuditTrail_Lookup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_AuditTrail_Lookup_Populate]
GO
/****** Object:  StoredProcedure [dbo].[App_ApplicationSetup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_ApplicationSetup_Manage]
GO
/****** Object:  StoredProcedure [dbo].[App_ApplicationSetup_List]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[App_ApplicationSetup_List]
GO
/****** Object:  StoredProcedure [dbo].[AlarmCodeLookUp_Manage]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AlarmCodeLookUp_Manage]
GO
/****** Object:  StoredProcedure [dbo].[AlarmCodeLkUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AlarmCodeLkUp_Populate]
GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_Trend_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AlarmAuditTrail_Trend_rpt]
GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_rpt]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AlarmAuditTrail_rpt]
GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_LookUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
DROP PROCEDURE [dbo].[AlarmAuditTrail_LookUp_Populate]
GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_LookUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Procedure [dbo].[AlarmAuditTrail_LookUp_Populate]
  
As 
Begin
	SET NOCOUNT ON;
           
    SELECT AlarmCodeLookUpId,AlarmDescription
	FROM AlarmCodeLookUp (NoLock)
	Order By AlarmDescription

End



GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--AlarmAuditTrail_rpt '163','2018/08/01 00:00','2018/08/27 23:59','','','','0','2','0',''
CREATE PROCEDURE [dbo].[AlarmAuditTrail_rpt]      
 @BranchId AS nvarchar(100) = '',  
 @ReportFromDate AS DATETIME='',        
 @ReportToDate AS DATETIME='',               
 @UserList AS varchar(4000)='',        
 @EquipmentList AS varchar(4000)='',        
 @FilterParameter AS varchar(100)='',        
 @ReviewApproveType INTEGER=0,        
 @GroupBy as tinyint=0,
 @OrderBy as tinyint=0,
 @AlarrmType as nvarchar(10) = ''        
AS        
SET NOCOUNT ON;        
BEGIN        
 DECLARE @strQuery AS VARCHAR(4000)        
         
 SET @strQuery=' SELECT (row_number() over(order by (Case ''' + Convert(varchar, @OrderBy) + ''' When 0 Then DML.AlarmLogDateTime Else DML.EquipmentMasterAlarmAuditTrailId End))) As [Sr No],        
 Convert(varchar, DML.AlarmLogDateTime, 105) As [Log Date], substring(convert(varchar(8), DML.AlarmLogDateTime, 108), 0, 9) As [Log Time], DM.EquipmentName As [Equipment Name], 
 DML.AlarmEvent As [Alarm Description], Convert(varchar, DML.AckDatetime, 105) As [Ack Date], substring(convert(varchar(8), DML.AckDatetime, 108), 0, 6) As [Ack Time],        
 DML.AckUserId As [Acknowledged By], DML.AckComments As [Ack Comments], 
(Case When  AlarmType =''E'' THEN  ''EVENT'' When  AlarmType =''N'' THEN  ''NOTIFICATION'' When  AlarmType =''A'' THEN  ''ALARM''  ELSE '''' END ) AS AlarmType,
 --,DML.EquipmentMasterAlarmAuditTrailId,(Case When ' + Convert(Varchar, @GroupBy) + ' = ''1'' Then DM.EquipmentName When ' + Convert(Varchar, @GroupBy) + ' = ''2'' then DML.AckUserId Else '''' End) As GroupName ,
   (Case When ' + Convert(Varchar, @GroupBy) + ' = ''2'' then DM.EquipmentName When ' + Convert(Varchar, @GroupBy) + ' = ''1'' then DML.AckUserId Else '''' End) As GroupName   

 FROM EquipmentMasterAlarmAuditTrail (NOLOCK) AS DML 
 inner join EquipmentMaster (NOLOCK) as DM on DM.EquipmentMasterId = DML.EquipmentMasterId              
 WHERE (DML.AlarmLogDateTime BETWEEN ''' + cast(@ReportFromDate as varchar(50)) + ''' AND ''' + cast(@ReportToDate as varchar(50)) + ''') '        
         
	IF @BranchId<>''        
		BEGIN        
			SET @strQuery = @strQuery + ' AND  DM.BranchId in (select * from CSVTOTable(''' + cast(@BranchId as varchar(100)) + ''')) '        
		END 
	       
	IF @EquipmentList<>''        
		BEGIN        
			SET @strQuery = @strQuery + ' AND  DML.EquipmentMasterId in (select * from CSVTOTable('''+cast(@EquipmentList as varchar(4000))+''')) '        
		END    
	    
	IF @UserList<>''        
		BEGIN        
			SET @strQuery = @strQuery + ' AND DML.AckUserId in (select * from CSVTOTable('''+cast(@UserList as varchar(4000))+''')) '        
		END 
	       
	IF @FilterParameter<>''        
		BEGIN        
			SET @strQuery = @strQuery + ' AND AlarmEvent in (select * from CSVTOTable('''+cast(@FilterParameter as varchar(4000))+''')) '        
		END
		        
	IF @ReviewApproveType = 3        
		BEGIN        
			SET @strQuery = @strQuery + ' And AckUserId IS NULL '        
		END
	        
	ELSE IF @ReviewApproveType <>-1        
		BEGIN        
			SET @strQuery = @strQuery + ' And  AckUserId IS NOT NULL'        
		END
	
	IF @AlarrmType <> ''        
		BEGIN        
			SET @strQuery = @strQuery + ' AND  AlarmType in (select * from CSVTOTable(''' + @AlarrmType + ''')) '        
		END        

	IF @OrderBy <> 0         
		Begin        
			SET @strQuery = @strQuery + 'ORDER BY  DML.EquipmentMasterAlarmAuditTrailId' 
		end
	ELSE
		Begin        
			SET @strQuery = @strQuery + ' ORDER BY DML.AlarmLogDateTime '     
		--SET @strQuery = @strQuery + ' ORDER BY DM.EquipmentName '     
			   
		END          
      
      print(@strQuery)    
	exec(@strQuery)        
         
END        
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[AlarmAuditTrail_Trend_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--AlarmAuditTrail_Trend_rpt '3,34','2019/01/01 00:00','2019/03/03 00:00','',''
CREATE Procedure [dbo].[AlarmAuditTrail_Trend_rpt]
 @BranchId as nvarchar(100) = 0,
 @ReportFromDate as Datetime ='',
 @ReportToDate as Datetime='',
 @EquipmentList AS varchar(4000)='',        
 @FilterParameter AS varchar(100)=''
As 
Begin
	SET NOCOUNT ON;	
	begin
		
		select EM.EquipmentName,count(AlarmEvent) as TotalAlarmCount,AlarmEvent,EM.EquipmentMasterId
		from EquipmentMasterAlarmAuditTrail (NOLOCK) AS EAT 
		INNER JOIN EquipmentMaster (NOLOCK) AS EM ON EAT.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId in (select * from CSVTOTable(@BranchId)) 
		AND (@EquipmentList = '' or EAT.EquipmentMasterId in (select * from CSVTOTable(@EquipmentList))) 
		AND (@FilterParameter = '' or EAT.AlarmEvent in (select * from CSVTOTable(@FilterParameter)))
		AND EAT.AlarmLogDateTime BETWEEN @ReportFromDate AND @ReportToDate
		group by em.EquipmentMasterId,AlarmEvent,EM.EquipmentName

		select EM.EquipmentName,eat.AlarmLogDateTime
		from EquipmentMasterAlarmAuditTrail (NOLOCK) AS EAT 
		INNER JOIN EquipmentMaster (NOLOCK) AS EM ON EAT.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId in (select * from CSVTOTable(@BranchId)) 
		AND (@EquipmentList = '' or EAT.EquipmentMasterId in (select * from CSVTOTable(@EquipmentList))) 
		AND (@FilterParameter = '' or EAT.AlarmEvent in (select * from CSVTOTable(@FilterParameter)))
		AND EAT.AlarmLogDateTime BETWEEN @ReportFromDate AND @ReportToDate		
		order by eat.AlarmLogDateTime
	end	
End


GO
/****** Object:  StoredProcedure [dbo].[AlarmCodeLkUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[AlarmCodeLkUp_Populate] 'Heat Senor'


CREATE PROCEDURE [dbo].[AlarmCodeLkUp_Populate]
@Equipmenttype AS nvarchar(10)=''
AS
SET NOCOUNT ON;
BEGIN
	
	select AlarmCodeLookUpId,Alarmdescription 
	from [AlarmCodeLookUp]  (NOLOCK) 
	where EquipmentTypeGroup like '%'+(select EquipmentTypeGroup from EquipmentType(NOLOCK) where  EquipmentType=@Equipmenttype)+'%' 
	and (ParameterNo <=(select ParameterNo/(case When EquipmentTypeGroup='HC' or EquipmentTypeGroup='DC'  or EquipmentTypeGroup='PSH' or EquipmentTypeGroup = 'CO2' then 2 else 1 End) from EquipmentType (NOLOCK)  where  EquipmentType=@Equipmenttype) or  ParameterNo = 0)
END
SET NOCOUNT OFF;


GO
/****** Object:  StoredProcedure [dbo].[AlarmCodeLookUp_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[AlarmCodeLookUp_Manage]
@EquipmentMasterId as bigint,
@AlarmCodeLookUpId as bigint,
@AlarmType as NVARCHAR(5)='',
@hdnLoginComments AS nVARCHAR(255),
@UserName as nvarchar(100)='',
@ReturnMessage as NVARCHAR(255)=''  output,
@ReturnId as  Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	Declare @EquipmentName as nvarchar(100)

	BEGIN TRY  
		
		INSERT INTO EquipmentAlarmConfig (EquipmentMasterId,AlarmCodeLookUpId,AlarmType,[CreatedBy],[ModifedBy]) 
		VALUES(@EquipmentMasterId,@AlarmCodeLookUpId,@AlarmType,@UserName,@UserName)
		
		IF @@rowcount > 0 
			BEGIN 
				
				SET @ReturnMessage = 'EMAIL SMS ALERT UPDATED SUCCESSFULLY !!!'
		        SET @ReturnId = @EquipmentMasterId
			END 
	    ELSE
			BEGIN 
				SET @ReturnMessage = 'EMAIL SMS ALERT UPDATION FAILED !!' 
		        SET @ReturnId = 0
			END		
				

	END TRY  
	BEGIN CATCH  
		
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 

End


GO
/****** Object:  StoredProcedure [dbo].[App_ApplicationSetup_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
CREATE Procedure [dbo].[App_ApplicationSetup_List]
	--@ApplicationSetupId as Bigint=0
	 @RecordKeyId as bigint=0
As 
Begin
	SET NOCOUNT ON;
    begin

	SELECT 	*,dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed FROM App_ApplicationSetup (NOLOCK)  Where (@RecordKeyId = 0 or ApplicationSetupId = @RecordKeyId)
	End
End


GO
/****** Object:  StoredProcedure [dbo].[App_ApplicationSetup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[App_ApplicationSetup_Manage] 
	   @hdnRecordKeyId as Bigint,
	   @CompanyId as BIGINT,
       @PasswordFrequency as smallint=0,
       @BackupLocalPath as nvarchar(500)='',
       @BackupRemotePath as nvarchar(500)='',
       @HistoryRestoreDBPath as nvarchar(500)='',
       @BackupTime as nvarchar(100)='',
       @ReportDisplayDateTime as nvarchar(5),
	   @AutoLogOutTime as smallint =0,
	   @LoginAttempt as  tinyint=0 ,
       @EmailSystem as tinyint=0 ,
       @SMTPAuthentication as tinyint=0 ,
       @SMTPEmail as nvarchar(250)='',
       @SMTPAddress as nvarchar(250)='',
       @SMTPUserName as nvarchar(100)='',
       @SMTPPassword as nvarchar(100)='',
       @SMTPEmailPort as smallint=0,
       @SMTPEmailSSL as smallint=0,
       @EmailSignature as nvarchar(500) ='',
       @SMSOption as tinyint=0 ,
       @CommunicationPort as tinyint=0,
       @Parity as nvarchar(5)='',
       @BaudRate as bigint=0,
       @DataBits as tinyint=0,
       @StopBits as tinyint=0,
       @TestEmailTime as nvarchar(25)='',
       @TestEmailAddress as nvarchar(100)='',
       @TestSMSTime  as nvarchar(25)='',
       @TestSMSMobileNo as nvarchar(100)='',
       @SMSSystem as tinyint=0,
       @MovingMKTTime as nvarchar(25)='',
       @LoginName as nvarchar(50)='',
	   @LoginType as tinyint=0,
	   @DomainInformation as nvarchar(100)='',
	   @SynchRTCTime as nvarchar(100)='',
	   @BioSynchRTCTime as nvarchar(100)='',
	   @ReturnMessage as varchar(500)='' output ,
	   @ReturnId as bigint =0 output
	   AS
	SET nocount on;
	BEGIN
	
		Declare @oldBackupLocalPath as nvarchar(500),@oldBackupRemotePath as nvarchar(500)
		,@oldBackupTime as nvarchar(100),@oldReportDisplayDateTime as nvarchar(100)
		,@oldPasswordFrequency as nvarchar(100),@oldEmailSystem as nvarchar(100)
		,@oldSMTPEmail as nvarchar(100),@oldSMTPAddress as nvarchar(100)
		,@oldSMTPUserName as nvarchar(100),@oldSMTPPassword as nvarchar(100)
		,@oldSMTPAuthentication as nvarchar(100),@oldCommunicationPort as nvarchar(100)
		,@oldParity as nvarchar(100),@oldBaudRate as nvarchar(100),@oldDataBits as nvarchar(100)
		,@oldStopBits as nvarchar(100),@oldSMSSystem as nvarchar(100)
		,@oldSMTPEmailPort as smallint,@oldSMTPEmailSSL as smallint
		,@oldEmailSignature as nvarchar(500),@oldTestEmailTime as nvarchar(100)
		,@oldTestSMSTime as nvarchar(100),@oldTestEmail as nvarchar(100)
		,@oldTestSMS as nvarchar(100),@oldRestartService as tinyint
		,@oldMKTTime as datetime,@oldMovingMKTTime as datetime,@oldAutoLogOutTime as smallint,@oldUserLockCount as smallint
		,@oldSMSOption as tinyint,@oldLoginType as tinyint,@oldDomainInformation as nvarchar(100),@oldSynchRTCTime as nvarchar(100),@oldHistoryRestoreDBPath as nvarchar(100)
		,@oldBioSynchRTCTime as nvarchar(100)
		
		Select @oldBackupLocalPath = BackupLocalPath,@oldBackupRemotePath = BackupRemotePath,
		@oldBackupTime = BackupTime,@oldReportDisplayDateTime = ReportDisplayDateTime,
		@oldPasswordFrequency = PasswordFrequency,@oldEmailSystem =  EmailSystem,
		@oldSMTPEmail = SMTPEmail,@oldSMTPAddress = SMTPAddress,
		@oldSMTPUserName = SMTPUserName,@oldSMTPPassword = SMTPPassword,
		@oldCommunicationPort= CommunicationPort,@oldParity = Parity,@oldBaudRate = BaudRate,
		@oldDataBits = DataBits,@oldStopBits = StopBits,@oldSMSSystem = SMSSystem,
		@oldSMTPEmailPort = SMTPEmailPort,@oldSMTPEmailSSL = SMTPEmailSSL,
		@oldEmailSignature = EmailSignature,@oldTestEmailTime = TestEmailTime,@oldTestEmail = @TestEmailAddress,
		@oldTestSMSTime = TestSMSTime,@oldTestSMS = @TestSMSMobileNo,
		@oldAutoLogOutTime = AutoLogOutTime,@oldUserLockCount = LoginAttempt,@oldSMTPAuthentication = SMTPAuthentication,
		@oldSMSOption = SMSOption,@oldLoginType = LoginType,@oldDomainInformation = DomainInformation,
		@oldSynchRTCTime = SynchRTCTime,@oldHistoryRestoreDBPath = HistoryRestoreDBPath,
		@oldBioSynchRTCTime = BioSynchRTCTime
		from App_ApplicationSetup
		
		IF (@CommunicationPort = '')
		BEGIN
			SET @CommunicationPort=0
		END

		Begin Try
			
			update App_ApplicationSetup 
			set PasswordFrequency=@PasswordFrequency ,BackupLocalPath=@BackupLocalPath ,BackupRemotePath=@BackupRemotePath ,
			BackupTime=@BackupTime ,ReportDisplayDateTime=@ReportDisplayDateTime ,AutoLogOutTime=@AutoLogOutTime,
			LoginAttempt=@LoginAttempt,EmailSystem=@EmailSystem ,SMTPAuthentication=@SMTPAuthentication ,
			SMTPEmail=@SMTPEmail ,SMTPAddress=@SMTPAddress ,SMTPUserName=@SMTPUserName ,SMTPPassword=@SMTPPassword ,
			SMTPEmailPort=@SMTPEmailPort ,SMTPEmailSSL=@SMTPEmailSSL ,EmailSignature=@EmailSignature ,
			SMSOption=@SMSOption ,CommunicationPort=@CommunicationPort ,Parity=@Parity ,BaudRate=@BaudRate ,
			DataBits=@DataBits ,StopBits=@StopBits ,TestEmailTime=@TestEmailTime ,TestEmailAddress=@TestEmailAddress ,
			TestSMSTime=@TestSMSTime ,TestSMSMobileNo=@TestSMSMobileNo ,LoginName=@LoginName ,
			SMSSystem=@SMSSystem ,MovingMKTTime=@MovingMKTTime,
			LoginType = @LoginType,DomainInformation = @DomainInformation,SynchRTCTime = @SynchRTCTime,HistoryRestoreDBPath = @HistoryRestoreDBPath,
			BioSynchRTCTime = @BioSynchRTCTime,
			ModifedBy = @LoginName , ModifedDate = GetDate()
			WHERE ApplicationSetupId = @hdnRecordKeyId

			if @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @hdnRecordKeyId
						set @ReturnMessage = 'APPLICATION SETUP DETAILS UPDATED SUCCESSFULLY'
						
						IF @oldPasswordFrequency <> @PasswordFrequency
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASPF'
						END
						
						IF @oldBackupLocalPath <> @BackupLocalPath
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASBLP'
						END
						
						IF @oldBackupRemotePath <> @BackupRemotePath
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASBRP'
						END
						
						IF @oldHistoryRestoreDBPath <> @HistoryRestoreDBPath
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','HRDBPT'
						END
						
						IF left(CONVERT(CHAR(24),Cast(@oldBackupTime as DateTime),14),5) <> left(CONVERT(CHAR(24),Cast(@BackupTime as DateTime),14),5)
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASBKT'
						END
						
						IF @oldReportDisplayDateTime <> @ReportDisplayDateTime
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASRDT'
						END
						
						IF @oldAutoLogOutTime <> @AutoLogOutTime
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASALT'
						END
						
						IF @oldUserLockCount <> @LoginAttempt
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASULT'
						END
						
						IF @oldEmailSystem <> @EmailSystem
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASES'
						END
						
						IF @oldSMTPAuthentication <> @SMTPAuthentication
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMA'
						END
						
						IF @oldSMTPEmail <> @SMTPEmail
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSME'
						END
						
						IF @oldSMTPAddress <> @SMTPAddress
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMTA'
						END
						
						IF @oldSMTPUserName <> @SMTPUserName
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMTU'
						END
						
						IF @oldSMTPPassword <> @SMTPPassword
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMTP'
						END
						
						IF @oldSMTPEmailPort <> @SMTPEmailPort
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMTEP'
						END
						
						IF @oldSMTPEmailSSL <> @SMTPEmailSSL
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASESSL'
						END
						
						IF @oldEmailSignature <> @EmailSignature
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASESG'
						END
						
						IF @oldSMSOption <> @SMSOption
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSMO'
						END
						
						IF @oldCommunicationPort <> @CommunicationPort
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSCP'
						END
						
						IF @oldParity <> @Parity
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSPR'
						END
						
						IF @oldBaudRate <> @BaudRate
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSBR'
						END
						
						IF @oldDataBits <> @DataBits
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSDB'
						END
						
						IF @oldStopBits <> @StopBits
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSOSB'
						END
						
						IF left(CONVERT(CHAR(24),Cast(@oldTestEmailTime as DateTime),14),5) <> left(CONVERT(CHAR(24),Cast(@TestEmailTime as DateTime),14),5) 
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSTET'
						END
						
						IF @oldTestEmail <> @TestEmailAddress
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASTEAD'
						END
						
						IF @oldTestSMS <> @TestSMSMobileNo
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASTSM'
						END
						
						IF @oldSMSSystem <> @SMSSystem
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASTSMS'
						END

						IF @oldLoginType <> @LoginType
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASTLT'
						END

						IF @oldDomainInformation <> @DomainInformation
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASTDI'
						END
						
						IF left(CONVERT(CHAR(24),Cast(@oldSynchRTCTime as DateTime),14),5) <> left(CONVERT(CHAR(24),Cast(@SynchRTCTime as DateTime),14),5)
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASSYNCHRTC'
						END
						
						IF left(CONVERT(CHAR(24),Cast(@oldBioSynchRTCTime as DateTime),14),5) <> left(CONVERT(CHAR(24),Cast(@BioSynchRTCTime as DateTime),14),5)
						BEGIN
							execute App_UserMaster_AuditTrail @CompanyId,@LoginName,'','ASBSYNCHRTC'
						END
							
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE APPLICATION SETUP!!'
				
					END
		End try
		Begin catch
			set @ReturnMessage=dbo.RemoveSpecialChars(error_message())
		End catch
	END
	Set nocount off;
 

 
GO
/****** Object:  StoredProcedure [dbo].[App_AuditTrail_Lookup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_AuditTrail_Lookup_Populate] 1
CREATE  Procedure [dbo].[App_AuditTrail_Lookup_Populate]
As 
Begin
	SET NOCOUNT ON;
    
    SELECT Code,Replace (Comments ,'{Name} ','') as Comments
	FROM App_AuditTrail_Lookup (NoLock)
	
	Order By Replace (Comments ,'{Name} ','') 
End


GO
/****** Object:  StoredProcedure [dbo].[App_CombinedReport_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC App_CombinedReport_Rpt '3','2019-01-29 00:00:00','2019-01-31 23:59:00',''
CREATE PROCEDURE [dbo].[App_CombinedReport_Rpt] 
	@CompanyId as nvarchar(100) = '',
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@UserList AS varchar(4000)=''
AS
SET NOCOUNT ON;
BEGIN

	SELECT ROW_NUMBER() OVER (ORDER BY A.LogDateTime ASC) AS [Sr No],Convert(varchar, A.LogDateTime, 105) As [Date],substring(convert(varchar(8), A.LogDateTime, 108), 0, 6) As [Time],A.EquipmentName AS [Equipment Name],A.UserId As [Login Name],A.LogEvent AS [Events],A.Comments
	from
(

	select LogDateTime,'' as EquipmentName, LogEvent,UserId,'' as Comments
	from App_Users_AuditTrail
	where LogDateTime between @ReportFromDate and @ReportToDate
	and (@CompanyId = '' or  CompanyId IN (select * from dbo.CSVToTable(@CompanyId))) 
	AND (@UserList = '' OR UserId IN (select * from dbo.CSVToTable(@UserList)))

	UNION ALL

	select AuditTrailDate as LogDateTime,EquipmentName,Parameter AS LogEvent,UserName AS UserId,Comments
	from EquipmentMasterAuditTrail
	where AuditTrailDate between @ReportFromDate and @ReportToDate
	and (@CompanyId = '' or  CompanyId IN (select * from dbo.CSVToTable(@CompanyId))) 
	AND (@UserList = '' OR UserName IN (select * from dbo.CSVToTable(@UserList)))

	UNION ALL

	select EMA.AckDatetime as LogDateTime,EMA.EquipmentName,EMA.AlarmEvent AS LogEvent,EMA.AckUserId AS UserId,EMA.AckComments as Comments
	from EquipmentMasterAlarmAuditTrail EMA
	INNER JOIN EquipmentMaster EM ON EM.EquipmentMasterId = EMA.EquipmentMasterId
	where EMA.AckDatetime between @ReportFromDate and @ReportToDate
	and EMA.AckUserId IS NOT NULL
	and (@CompanyId = '' or  EM.BranchId IN (select * from dbo.CSVToTable(@CompanyId)))
	AND (@UserList = '' OR EMA.AckUserId IN (select * from dbo.CSVToTable(@UserList))) 
	

	UNION ALL

	select ELRA.ReviewedApprovedDateTime AS LogDateTime,EM.EquipmentName,(CASE ELRA.ReviewedApproved WHEN 'R' THEN 'Data Log Reviwed' ELSE 'Data Log Approved' END) AS LogEvent,ELRA.UserId,ELRA.Comments
	FROM EquipmentMasterLogReviewApprove ELRA
	INNER JOIN EquipmentMaster EM ON ELRA.EquipmentMasterId = EM.EquipmentMasterId
	WHERE ReviewedApprovedDateTime between @ReportFromDate and @ReportToDate
	and (@CompanyId = '' or  EM.BranchId IN (select * from dbo.CSVToTable(@CompanyId))) 
	AND (@UserList = '' OR UserId IN (select * from dbo.CSVToTable(@UserList)))
	
)A

order by LogDateTime 
	
END
SET NOCOUNT OFF

--SELECT * FROM App_Users
GO
/****** Object:  StoredProcedure [dbo].[App_Company_Accesible_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Company_Accesible_List] '3','2'
CREATE  Procedure [dbo].[App_Company_Accesible_List]
 @AccessibleCompanyIds as nvarchar(1000)='',
 @CompanyId as nvarchar(50)=''
As 
Begin
	SET NOCOUNT ON;
		
		SELECT Isnull(CM.CompanyName,Isnull(BU.CompanyName,BM.CompanyName)) as CompanyName ,Isnull(CM.CompanyId,Isnull(BU.CompanyId,BM.CompanyId)) as CompanyId,
		Isnull(BU.CompanyName,BM.CompanyName) as BusinessUnitName, Isnull(BU.CompanyId,BM.CompanyId) as BusinessUnitId,
		BM.CompanyId as BranchId,BM.CompanyName  as BranchName
		,(SELECT CompanyCode from App_Company(NOLOCK) WHERE CompanyId = (Select GroupId from App_Company where CompanyId = @CompanyId)) as [CompanyCode]
		FROM App_Company (NoLock) AS BM 
		LEFT OUTER JOIN App_Company(NoLock) AS BU ON BU.CompanyID = BM.GroupId
		LEFT OUTER JOIN App_Company(NoLock) AS CM ON CM.CompanyID = BU.GroupId
		Where BM.CompanyId in (Select [SId] From dbo.CSVToTable(@AccessibleCompanyIds))
		Order By Bm.CompanyName			
End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_AlarmEvent_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Company_List] 3,3
CREATE  Procedure [dbo].[App_Company_AlarmEvent_List]
 @RecordKeyId as bigint=0

As 
Begin
	SET NOCOUNT ON;
   
		SELECT AlarmEventId,[CompanyId],ACA.AlarmCodeLookUpId,AlarmDescription,AlarmCode,AlarmType
		FROM App_Company_AlarmEvent (NoLock) ACA INNER JOIN AlarmCodeLookUp (NoLock) ACL ON ACL.AlarmCodeLookUpId=ACA.AlarmCodeLookUpId
		Where (@RecordKeyId=0 Or CompanyId=@RecordKeyId)
End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_AlarmEvent_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMasterAlarmAuditTrail_Update 2,'Administrator','','',0
CREATE Procedure [dbo].[App_Company_AlarmEvent_Update]
 @AlarmEventId as bigint=0,
 @CompanyId AS bigint =0,
 @AlarmCodeLookUpId AS bigint=0,
 @AlarmType AS nvarchar(2)='',
 @UserName as nvarchar(100)='',
 @ReturnMessage AS NVARCHAR(1000)='' OUTPUT,
 @ReturnId AS BIGINT=0 OUTPUT
As 
Begin
	SET NOCOUNT ON;	
	begin		
		
		UPDATE App_Company_AlarmEvent SET AlarmType=@AlarmType,ModifedBy=@UserName,ModifedDate=GETDATE()
		WHERE AlarmEventId=@AlarmEventId and CompanyId=@CompanyId and @AlarmCodeLookUpId=@AlarmCodeLookUpId
		
		IF @@ROWCOUNT>0		
			BEGIN
				SET @ReturnMessage='ALARM EVENT UPDATED SUCCESSFULLY'
				SET @ReturnId = @AlarmEventId
			END
		ELSE
			BEGIN	
				SET @ReturnMessage='ALARM EVENT UPDATION FAILED'
				SET @ReturnId = 0
			END
	end	
End

--select *from EquipmentMasterAlarmAuditTrail
GO
/****** Object:  StoredProcedure [dbo].[App_Company_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Company_List] 3,3
CREATE  Procedure [dbo].[App_Company_List]
 @RecordKeyId as bigint=0,
 @CompanyLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
    
	
		SELECT 
		[CompanyId],[CompanyLevel],[GroupId],[CompanyName],[CompanyCode],[CompanyAddress],
		Isnull([GeographicalId],0) as [GeographicalId],[Pincode],[Telephone],[Fax],[Email],[Web],
		[Details1],[Details2],[Details3],[Details4],[Details5],[Details6],[Details7],
        [Details8] ,[Details9],[Details10],[Details11],[Details12],[RecordStatus],[AchiveMonth],
		dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed
		FROM App_Company (NoLock)
		Where (@RecordKeyId=0 Or CompanyId=@RecordKeyId)
		AND CompanyLevel=@CompanyLevel

End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [App_Company_ListData] 163,1 
CREATE PROCEDURE [dbo].[App_Company_ListData] 
	@BranchId as bigint = 0,
	@NotIn as tinyint=0
AS
Set nocount on;
	Begin
    if @NotIn = 0 
	     begin
			SELECT  *
			FROM App_Company
			WHERE (@BranchId = 0 or CompanyId  = @BranchId)
		 end
    else
	     begin
			SELECT CompanyId ,CompanyName 
			FROM App_Company
			WHERE (@BranchId = 0 or CompanyId <> @BranchId )
			Order By CompanyName
		 end

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[App_Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Company_Manage '1708','User Type','U','0017DEBF','','2755C02F','0','Administrator','','0',
CREATE Procedure [dbo].[App_Company_Manage]
 @hdnRecordKeyId as Bigint =0,
 @GroupId as Bigint =0,
 @CompanyLevel as nvarchar(20)='',
 @CompanyName as nvarchar(100)='',
 @CompanyCode as nvarchar(10)='',
 @CompanyAddress as nvarchar(255)='',
 @GeographicalId as Bigint =0,
 @Pincode as nvarchar(20)='',
 @Telephone as nvarchar(100)='',
 @Fax as nvarchar(100)='',
 @Email as nvarchar(100)='',
 @Web as nvarchar(100)='',
 @Details1 as nvarchar(100) = '', 
 @Details2 as nvarchar(100) = '', 
 @Details3 as nvarchar(100) = '', 
 @Details4 as nvarchar(100) = '', 
 @Details5 as nvarchar(100) = '', 
 @Details6 as nvarchar(100) = '', 
 @Details7 as nvarchar(100) = '', 
 @Details8 as nvarchar(100) = '', 
 @Details9 as nvarchar(100) = '', 
 @Details10 as nvarchar(100) = '', 
 @Details11 as nvarchar(100) = '', 
 @Details12 as nvarchar(100) = '', 
 @RecordStatus as tinyint = 0,
 @UserName as nvarchar(100)='',
 @ReturnMessage as NVARCHAR(255)=''  output,
 @ReturnId as Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	---CHECK IF RECORD ALREADY EXIST 
	SELECT CompanyId FROM App_Company (NOLOCK) WHERE CompanyName=@CompanyName
	AND CompanyLevel=@CompanyLevel AND GroupId= @GroupId  AND (@hdnRecordKeyId=0 OR CompanyId <> @hdnRecordKeyId)

	IF @@ROWCOUNT > 0
		BEGIN
			SET @ReturnId=0
			SET @ReturnMessage = 'RECORD ALREADY EXIST'
			return
		END
	---CHECK IF RECORD ALREADY EXIST 

	BEGIN TRY  
		IF @hdnRecordKeyId = 0 ---ADD RECORD
			BEGIN
			
				INSERT INTO  App_Company (CompanyLevel,GroupId,CompanyName,CompanyCode
				,CompanyAddress,GeographicalId,Pincode
				,Telephone,Fax,Email,Web
				,Details1,Details2,Details3,Details4,Details5,Details6
				,Details7,Details8,Details9,Details10,Details11,Details12
				,RecordStatus,CreatedBy,ModifedBy)
				VALUES (@CompanyLevel,@GroupId,@CompanyName,@CompanyCode
				,@CompanyAddress,@GeographicalId,@Pincode
				,@Telephone,@Fax,@Email,@Web
				,@Details1,@Details2,@Details3,@Details4,@Details5,@Details6
				,@Details7,@Details8,@Details9,@Details10,@Details11,@Details12
				,@RecordStatus,@UserName,@UserName)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
				UPDATE App_Company SET [CompanyLevel] = @CompanyLevel,[GroupId] = @GroupId
				,[CompanyName] = @CompanyName,[CompanyCode] = @CompanyCode
				,[CompanyAddress] = @CompanyAddress,[GeographicalId] = @GeographicalId
				,[Pincode] = @Pincode,[Telephone] = @Telephone
				,[Fax] = @Fax,[Email] = @Email
				,[Web] = @Web,
				[Details1] = @Details1,[Details2] = @Details2
				,[Details3] = @Details3,[Details4] = @Details4
				,[Details5] = @Details5,[Details6] = @Details6
				,[Details7] = @Details7,[Details8] = @Details8
				,[Details9] = @Details9,[Details10] = @Details10
				,[Details11] = @Details11,[Details12] = @Details12
				,[RecordStatus] = @RecordStatus
				,[ModifedBy] = @UserName
				,[ModifedDate] = GetDate()
				WHERE CompanyId = @hdnRecordKeyId

				IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @hdnRecordKeyId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Company_Populate] 2
CREATE  Procedure [dbo].[App_Company_Populate]
 @CompanyLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
				;WITH CTE(CompanyId, GroupId, CompanyLevel, CompanyName,CompanyGroup)
				AS 
				(
					SELECT CompanyId, GroupId,  CompanyLevel,CompanyName , CAST('' AS NVARCHAR(Max))  as  CompanyGroup FROM 
					App_Company(NoLock) WHERE GroupId =0 

					UNION ALL

					SELECT A.CompanyId, A.GroupId, A.CompanyLevel, A.CompanyName,cast((
					Case When B.CompanyGroup = '' Then A.CompanyName
					Else A.CompanyName + ' / ' +  B.CompanyGroup End ) as nvarchar(max))from 
					App_Company(NoLock) A INNER JOIN CTE B ON (A.GroupId=B.CompanyId)
					WHERE A.CompanyLevel < @CompanyLevel
				) 

	SELECT CompanyId, (CASE WHEN CompanyGroup='' THEN CompanyName ELSE CompanyGroup END) AS CompanyGroup FROM 
	(
			SELECT CompanyId, GroupId,  CompanyLevel,CompanyName,CompanyGroup FROM CTE
	)MT
	Where CompanyLevel >= @CompanyLevel - 1
	ORDER BY CompanyGroup ASC
	
End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Company_Search] 1,25,'','1',0
CREATE  Procedure [dbo].[App_Company_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @CompanyLevel as tinyint=0
 --@MaxLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint,@CompanyLevel_Sp as tinyint

		Set @CompanyLevel_Sp= @CompanyLevel 
	
	
		CREATE  TABLE #Company_Temp 
			(
				CompanyId bigint, 
				CompanyName nvarchar(500)
			)
			INSERT INTO #Company_Temp
			Exec App_Company_Populate @CompanyLevel_Sp
			
			SELECT ROW_NUMBER() OVER (ORDER BY AG.CompanyName ASC)AS RowNumber,AG.GroupId,
			AG.CompanyId,AG.CompanyName,AG.CompanyCode,GT.CompanyName as CompanyGroup,
			(Case When RecordStatus = 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,ModifedBy,
			dbo.GetLastModifedDate(ModifedDate) as ModifedDate
			INTO #Results FROM App_Company AG (NoLock)
			Inner Join #Company_Temp GT ON GT.CompanyId = Case When @CompanyLevel =1 Then AG.CompanyId Else AG.GroupId End 
			Where (AG.CompanyName like ('%' + @SearchText + '%') or CompanyCode like ('%' + @SearchText + '%') or GT.CompanyName like ('%' + @SearchText + '%') or ModifedBy like ('%' + @SearchText + '%')) 
			And (@CompanyLevel=0 or CompanyLevel=@CompanyLevel)
			
			Set @RecordCount = @@ROWCOUNT

			Drop Table #Company_Temp
		

           
    SELECT CompanyId,@RecordCount as RecordCount,CompanyName,CompanyCode,CompanyGroup,RecordStatus,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	
     
    DROP TABLE #Results

End


GO
/****** Object:  StoredProcedure [dbo].[App_Company_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--App_Company_Sync 3
CREATE PROCEDURE [dbo].[App_Company_Sync]
	
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.App_Company
			(CompanyId,CompanyLevel,GroupId,CompanyName,CompanyCode,CompanyAddress,HeaderNote,FooterNote,AchiveMonth,EmailStatus,ArchiveEmailReminderDate
			,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,RecordStatus,SoftKey,ActivationKey
			,ActivationRemainingTime,ServiceRestart,CreateDate,CreatedBy,ModifedBy,ModifedDate)
		select
		    SourceDBTable.CompanyId,SourceDBTable.CompanyLevel,SourceDBTable.GroupId,SourceDBTable.CompanyName,SourceDBTable.CompanyCode,SourceDBTable.CompanyAddress,SourceDBTable.HeaderNote,SourceDBTable.FooterNote,SourceDBTable.AchiveMonth,SourceDBTable.EmailStatus,SourceDBTable.ArchiveEmailReminderDate
			,SourceDBTable.EmailAlertDelay,SourceDBTable.AlertEmailAddress,SourceDBTable.EmailTime,SourceDBTable.SupervisorEmailAdd,SourceDBTable.SMSStatus,SourceDBTable.SMSAlertDelay,SourceDBTable.MobileUserName,SourceDBTable.MobileNo,SourceDBTable.RecordStatus,SourceDBTable.SoftKey,SourceDBTable.ActivationKey
			,SourceDBTable.ActivationRemainingTime,SourceDBTable.ServiceRestart,SourceDBTable.CreateDate,SourceDBTable.CreatedBy,SourceDBTable.ModifedBy,SourceDBTable.ModifedDate
		 from App_Company (NOLOCK)  SourceDBTable
		where 	 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.App_Company DestinationDBTable
						 where DestinationDBTable.CompanyId = SourceDBTable.CompanyId)
			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.App_Company 
	set CompanyLevel = SourceDBTable.CompanyLevel,
	GroupId = SourceDBTable.GroupId,
	CompanyName=SourceDBTable.CompanyName,
	CompanyCode=SourceDBTable.CompanyCode,
	CompanyAddress=SourceDBTable.CompanyAddress,
	HeaderNote=SourceDBTable.HeaderNote,
	FooterNote=SourceDBTable.FooterNote,
	AchiveMonth=SourceDBTable.AchiveMonth,
	EmailStatus=SourceDBTable.EmailStatus,
	ArchiveEmailReminderDate=SourceDBTable.ArchiveEmailReminderDate,
	EmailAlertDelay=SourceDBTable.EmailAlertDelay,
	AlertEmailAddress=SourceDBTable.AlertEmailAddress,
	EmailTime=SourceDBTable.EmailTime,
	SupervisorEmailAdd=SourceDBTable.SupervisorEmailAdd,
	SMSStatus=SourceDBTable.SMSStatus,
	SMSAlertDelay=SourceDBTable.SMSAlertDelay,
	MobileUserName=SourceDBTable.MobileUserName,
	MobileNo=SourceDBTable.MobileNo,
	RecordStatus=SourceDBTable.RecordStatus,
	SoftKey=SourceDBTable.SoftKey,
	ActivationKey=SourceDBTable.ActivationKey,
	ActivationRemainingTime=SourceDBTable.ActivationRemainingTime,
	ServiceRestart=SourceDBTable.ServiceRestart,
	CreateDate=SourceDBTable.CreateDate,
	CreatedBy=SourceDBTable.CreatedBy,
	ModifedBy=SourceDBTable.ModifedBy,
	ModifedDate=SourceDBTable.ModifedDate
	
	from	ICDAS_3_0_Archive.dbo.App_Company DestinationDBTable,
			(
				select	max(TableName) as TableName,CompanyId,CompanyLevel,GroupId,CompanyName,CompanyCode,CompanyAddress,HeaderNote,FooterNote,AchiveMonth,EmailStatus,ArchiveEmailReminderDate
			           ,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,RecordStatus,SoftKey,ActivationKey
			           ,ActivationRemainingTime,ServiceRestart,CreateDate,CreatedBy,ModifedBy,ModifedDate
			
				from
					(
						select	'SourceTableName' as TableName,CompanyId,CompanyLevel,GroupId,CompanyName,CompanyCode,CompanyAddress,HeaderNote,FooterNote,AchiveMonth,EmailStatus,ArchiveEmailReminderDate
								,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,RecordStatus,SoftKey,ActivationKey
								,ActivationRemainingTime,ServiceRestart,CreateDate,CreatedBy,ModifedBy,ModifedDate
						from App_Company (NOLOCK)  SourceTableName
						
						union all
						
						select	'DestinationiTableName' as TableName, CompanyId,CompanyLevel,GroupId,CompanyName,CompanyCode,CompanyAddress,HeaderNote,FooterNote,AchiveMonth,EmailStatus,ArchiveEmailReminderDate
								,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,RecordStatus,SoftKey,ActivationKey
								,ActivationRemainingTime,ServiceRestart,CreateDate,CreatedBy,ModifedBy,ModifedDate
						from ICDAS_3_0_Archive.dbo.App_Company (NOLOCK)  DestinationTableName
						
					) AliasName
					
					group by CompanyId,CompanyLevel,GroupId,CompanyName,CompanyCode,CompanyAddress,HeaderNote,FooterNote,AchiveMonth,EmailStatus,ArchiveEmailReminderDate
							,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,RecordStatus,SoftKey,ActivationKey
							,ActivationRemainingTime,ServiceRestart,CreateDate,CreatedBy,ModifedBy,ModifedDate
							
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
					
			) SourceDBTable
			
	where DestinationDBTable.CompanyId = SourceDBTable.CompanyId
			
	End
Set nocount off;
--sp_help App_Company
GO
/****** Object:  StoredProcedure [dbo].[App_General_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--App_General_Delete '182','CompanyId','App_Company','Admin','164',''
CREATE  Procedure [dbo].[App_General_Delete]
	@RecordKeyIds  as nvarchar(max),
	@RecordKeyColunm as nvarchar(100),
	@TableName as nvarchar(100),
	@UserName as nvarchar(100),
	@CompanyId as nvarchar(100),
	@ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalCount as int,@DeletedCount as int,@Name AS NVARCHAR(100),@LookUpCode as nvarchar(50)
		Declare @NamesColunm AS nvarchar(100)
		Set @NamesColunm=''
		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				SET @TotalCount=@TotalCount+1

				SET @NamesColunm = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

				if @TableName='App_Users' AND @RecordKeyId='1'
					BEGIN
						SET @ReturnMessage ='RECORDS CONTAIN ADMIN USER'
						continue
					END
				ELSE
					BEGIN
						if @TableName='App_Users'
						BEGIN
							SELECT @Name = UserName FROM App_Users(NOLOCK) WHERE UserId = @RecordKeyId
							SET @LookUpCode ='USRPDEL'
						END
						
						if @TableName='App_UserGroup'
						BEGIN
							SELECT @Name = UserGroupName FROM App_UserGroup(NOLOCK) WHERE UserGroupId = @RecordKeyId
							SET @LookUpCode ='USRGRPDEL'
						END

						SET @strQuery = 'DELETE FROM ' + @TableName + ' WHERE ' + @RecordKeyColunm + ' = ''' + @RecordKeyId + ''''
						print @strQuery
						EXEC sp_executesql @strQuery
						IF  @@RowCount > 0
						BEGIN						
							execute App_UserMaster_AuditTrail @CompanyId,@Username,@Name,@LookUpCode,''
							SET @DeletedCount=@DeletedCount+1
						END
					END

				

			END TRY  
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0

		IF @ReturnMessage <> '' 
			SET @ReturnMessage= 'Record Deleted Successfully'
		ELSE
			SET @ReturnMessage= 'Record Deletion Failed'
		
		print(@ReturnMessage)
	
End


GO
/****** Object:  StoredProcedure [dbo].[App_ProjectMenu_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_ProjectMenu_List] 1,0
CREATE  Procedure [dbo].[App_ProjectMenu_List]
@UserGroupId Bigint=0,
@MenuLock as tinyint=2
As 
Begin
			IF @UserGroupId =0 
				BEGIN
					Select Isnull(MenuGroup, 0) As MenuGroup, PM.MenuCode, MenuName, Isnull(MenuParameters,'') as MenuParameters ,MenuCommand,MenuPageName,'00000' as MenuAccess
					FROM App_ProjectMenu(NOLOCK) PM
					WHERE MenuLevelType= 'C' and MenuLock=@MenuLock
					Order by CAST('/' + MenuSno + '/' AS hierarchyid), MenuLevel 
				END
			ELSE
				BEGIN

					;WITH MenuTree as 
					(
						Select PM.MenuLock,Isnull(PM.MenuGroup, 0) As MenuGroup, PM.MenuCode, PM.MenuName,MenuParameters,MenuCommand,MenuPageName,MenuLevelType,MenuLevel,MenuSno,MenuImagePath,
						(Cast(ViewAccess as nvarchar(1))+ Cast(AddAccess as nvarchar(1))+Cast(EditAccess as nvarchar(1))+Cast(SaveAccess as nvarchar(1))+Cast(DeleteAccess as nvarchar(1))+Cast(PrintAccess as nvarchar(1))) As MenuAccess
						FROM App_ProjectMenu(NOLOCK) PM INNER JOIN App_UserGroupAccess(NOLOCK) UGA on UGA.MenuCode=PM.MenuCode
						WHERE UGA.UserGroupId=@UserGroupId And PM.MenuLock=@MenuLock And UGA.ViewAccess=1
						
						UNION ALL

						SELECT PM.MenuLock,Isnull(PM.MenuGroup, 0) As MenuGroup, PM.MenuCode, PM.MenuName,PM.MenuParameters,PM.MenuCommand,PM.MenuPageName,PM.MenuLevelType,PM.MenuLevel,PM.MenuSno,PM.MenuImagePath,UGA.MenuAccess
						FROM App_ProjectMenu(NOLOCK) PM 
						INNER JOIN MenuTree MT on PM.MenuCode = MT.MenuGroup  -- this is the recursion
						Outer Apply
						(
							SELECT (Cast(ViewAccess as nvarchar(1))+ Cast(AddAccess as nvarchar(1))+Cast(EditAccess as nvarchar(1))+Cast(SaveAccess as nvarchar(1))+Cast(DeleteAccess as nvarchar(1))+Cast(PrintAccess as nvarchar(1))) As MenuAccess
							FROM App_UserGroupAccess(NOLOCK) UGA Where UGA.MenuCode=PM.MenuCode
						)UGA
						Where PM.MenuLock=@MenuLock
					)					
					SELECT Distinct * Into #temp FROM MenuTree;
						
					SELECT * FROM #temp Order by CAST('/' + MenuSno + '/' AS hierarchyid), MenuLevel;

					Drop Table #temp;
					
				END
		
End


GO
/****** Object:  StoredProcedure [dbo].[App_ProjectMenu_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC App_ProjectMenu_Populate 100001
CREATE PROCEDURE [dbo].[App_ProjectMenu_Populate] 
@MenuCode AS VARCHAR(50) =''
AS

SET NOCOUNT ON
	BEGIN
		SELECT MenuCode,MenuName,ISNULL(MenuCommand,'') AS MenuCommand, MenuLevel, MenuGroup, MenuInformation 
		From App_ProjectMenu 
		WHERE MenuCode=@MenuCode 
		And MenuLock = 0 ORDER BY MenuCode,MenuSNo
	END
	SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[App_ProjectSearch_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[ProjectSearch_List] ''
CREATE  Procedure [dbo].[App_ProjectSearch_List]
@SearchCode nvarchar(100)=''
As 
Begin
	SELECT * FROM App_ProjectSearch(noLock)
	WHERE @SearchCode='' or SearchCode=@SearchCode
End


GO
/****** Object:  StoredProcedure [dbo].[App_Reports_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[GeneralMaster_Search] 1,25,'','25'
CREATE Procedure [dbo].[App_Reports_Populate]
 @MenuPageName as nvarchar(100) = '' 
As 
Begin
	SET NOCOUNT ON;
	
	SELECT ReportId,ReportName,ReportURL From
	App_Reports (NOLock) Where @MenuPageName = '' or MenuPageName = @MenuPageName 
	Order By ReportSrNo


End

GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[App_UserGroup_Delete]
	@RecordKeyIds  as nvarchar(max),
	@RecordKeyColunm as nvarchar(100),
	@TableName as nvarchar(100),
	@UserName as nvarchar(100),
	@CompanyId as nvarchar(100),
	@ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalCount as int,@DeletedCount as int,@Name AS NVARCHAR(100),@LookUpCode as nvarchar(50)
		Declare @NamesColunm AS nvarchar(100)
		
		Set @NamesColunm=''
		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				
				SET @TotalCount=@TotalCount+1

				SET @NamesColunm = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

				if @TableName='App_Users' AND @RecordKeyId='1'
					BEGIN
						SET @ReturnMessage ='RECORDS CONTAIN ADMIN USER'
						continue
					END
				ELSE
					BEGIN
					
						Select @TotalCount = count(CompanyId) from App_Users where UserGroupId = @RecordKeyId
						
						IF @TotalCount > 0 
						   BEGIN
								SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
								PRINT(@ReturnMessage)
								return
						   END
						
						Select @Name = UserGroupName from App_UserGroup where UserGroupId = @RecordKeyId

						SET @strQuery = 'DELETE FROM ' + @TableName + ' WHERE ' + @RecordKeyColunm + ' = ''' + @RecordKeyId + ''''
						print @strQuery
						EXEC sp_executesql @strQuery
						
						IF  @@RowCount > 0
							BEGIN
														
								execute App_UserMaster_AuditTrail @CompanyId,@Username,@Name,'UGUD',''
								SET @ReturnMessage= 'RECORD DELETED SUCCESSFULLY'
								PRINT(@ReturnMessage)
							END
						ELSE
							BEGIN
								SET @ReturnMessage= 'RECORD DELETION FAILED'
								PRINT(@ReturnMessage)
							END
						
					END

			END TRY 
			 
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0
		
		
End



GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--UserGroup_List 1
CREATE  Procedure [dbo].[App_UserGroup_List]
 @RecordKeyId as bigint=0
As 
Begin
	SET NOCOUNT ON;
           
    SELECT UserGroupId,UserGroupName,UserGroupDetails,RecordStatus,
	dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed
	FROM App_UserGroup (NoLock)
	Where (@RecordKeyId=0 Or UserGroupId=@RecordKeyId)

End


GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[UserGroup_Manage] '0','hiren4','','0','SaveAs','16','Administrator','','0'
CREATE  Procedure [dbo].[App_UserGroup_Manage]
 @hdnRecordKeyId as Bigint =0,
 @UserGroupId as Bigint=0,
 @UserGroupName as nvarchar(100)='',
 @UserGroupDetails as nvarchar(255)='',
 @RecordStatus as tinyint = 0,
 @Mode as nvarchar(10)='A',
 @hdnEditRecordId as Bigint =0,
 @UserName as nvarchar(100)='',
 @ReturnMessage as NVARCHAR(255)=''  output,
 @ReturnId as Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	---CHECK IF RECORD ALREADY EXIST 
	SELECT UserGroupId FROM App_UserGroup (NOLOCK) WHERE UserGroupName=@UserGroupName
	And (@hdnRecordKeyId=0 OR UserGroupId <> @hdnRecordKeyId)
	
	

	IF @@ROWCOUNT > 0
		BEGIN
			SET @ReturnId=@hdnRecordKeyId
			SET @ReturnMessage = 'RECORD ALREADY EXIST'
			return
		END
	---CHECK IF RECORD ALREADY EXIST 

	BEGIN TRY  
		IF @hdnRecordKeyId = 0 ---ADD RECORD
			BEGIN
			   
			   INSERT INTO  App_UserGroup ([UserGroupName],[UserGroupDetails],[RecordStatus],[CreatedBy],[ModifedBy])
			   VALUES (@UserGroupName,@UserGroupDetails,@RecordStatus,@UserName,@UserName)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
						
						INSERT INTO App_UserGroupAccess ([UserGroupId],[MenuCode],[ViewAccess],[AddAccess],[EditAccess],[SaveAccess],[DeleteAccess],[PrintAccess])
						values (@ReturnId,'110006',1,1,1,1,1,1)
						
						EXEC App_UserMaster_AuditTrail @UserGroupId,@UserName,@UserGroupName,'UGAD',''
						
						IF @Mode='SaveAs'
							
							BEGIN TRY  
								INSERT INTO [UserGroupAccess] ([UserGroupId],[MenuCode],[ViewAccess],[AddAccess],[EditAccess],[SaveAccess],[DeleteAccess],[PrintAccess])
								(SELECT @ReturnId,MenuCode,ViewAccess,AddAccess,EditAccess,SaveAccess,DeleteAccess,PrintAccess From UserGroupAccess Where UserGroupId=@hdnEditRecordId)
							END TRY  
								BEGIN CATCH  
									SET @ReturnId=0
									SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
									print(Error_Message())
								END CATCH; 
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
			
				Declare @oldUserGroupName as nvarchar(100),@oldDescription as nvarchar(255)
				
				Select @oldUserGroupName = UserGroupName,@oldDescription = @UserGroupDetails 
				from App_UserGroup
				Where UserGroupId = @hdnRecordKeyId
				
				UPDATE App_UserGroup SET [UserGroupName] = @UserGroupName,
				[UserGroupDetails] = @UserGroupDetails,
				[RecordStatus] = @RecordStatus,[ModifedBy] = @UserName,[ModifedDate] = GETDATE()
				WHERE UserGroupId = @hdnRecordKeyId
				
				IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @hdnRecordKeyId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
						
						if (@oldUserGroupName <> @UserGroupName) or (@oldDescription <> @UserGroupDetails)
							Begin
								EXEC App_UserMaster_AuditTrail @UserGroupId,@UserName,@UserGroupName,'UGUP',''
							End
						
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 
End


GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_UserGroup_Populate] 1
CREATE  Procedure [dbo].[App_UserGroup_Populate]
 @RecordStatus as tinyint=5
As 
Begin
	SET NOCOUNT ON;
           
    SELECT UserGroupId,UserGroupName,UserGroupDetails,RecordStatus,
	dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed
	FROM App_UserGroup (NoLock)
	Where @RecordStatus=5 or RecordStatus=@RecordStatus
	Order By UserGroupName

End


GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_UserGroup_Search] 1,3,'','1,3'
CREATE  Procedure [dbo].[App_UserGroup_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @SelectedRecord as NVARCHAR(500)=''
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint

	SELECT ROW_NUMBER() OVER (ORDER BY UserGroupName ASC)AS RowNumber
	,UserGroupId,UserGroupName,
	(Case When RecordStatus = 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,ModifedBy,
	dbo.GetLastModifedDate(ModifedDate) as ModifedDate
	INTO #Results FROM App_UserGroup (NoLock)
	Where (UserGroupName like ('%' + @SearchText + '%') Or ModifedBy like ('%' + @SearchText + '%'))
	and (@SelectedRecord = '') OR UserGroupId in (Select * from dbo.CSVToTable(@SelectedRecord))

    Set @RecordCount = @@ROWCOUNT
           
    SELECT UserGroupId,@RecordCount as RecordCount,UserGroupName,RecordStatus,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	
     
    DROP TABLE #Results

End


GO
/****** Object:  StoredProcedure [dbo].[App_UserGroup_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--UserGroup_Sync 3
CREATE PROCEDURE [dbo].[App_UserGroup_Sync]
	@CompanyId as bigint = 0
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.App_UserGroup
			(UserGroupId,CompanyId,UserGroupName,UserGroupDetails,CreateDate)
		select
			SourceDBTable.UserGroupId,SourceDBTable.CompanyId,SourceDBTable.UserGroupName
			,SourceDBTable.UserGroupDetails,SourceDBTable.CreateDate
		from UserGroup (NOLOCK)  SourceDBTable
		where CompanyId=@CompanyId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.App_UserGroup DestinationDBTable
						 where DestinationDBTable.UserGroupId = SourceDBTable.UserGroupId)
			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.App_UserGroup 
	set    CompanyId=SourceDBTable.CompanyId,UserGroupName=SourceDBTable.UserGroupName
		   ,UserGroupDetails=SourceDBTable.UserGroupDetails,ModifedDate=SourceDBTable.ModifedDate
	from	ICDAS_3_0_Archive.dbo.App_UserGroup (NOLOCK)  DestinationDBTable,
			(
				select	max(TableName) as TableName,  CompanyId,UserGroupName,UserGroupDetails,ModifedDate
				from
					(
						select	'SourceTableName' as TableName, CompanyId,UserGroupName,UserGroupDetails,ModifedDate
						from UserGroup (NOLOCK)  SourceTableName
						
						union all
						
						select	'DestinationiTableName' as TableName, UserGroupId,CompanyId,UserGroupName,UserGroupDetails,ModifedDate
						from ICDAS_3_0_Archive.dbo.App_UserGroup (NOLOCK)  DestinationTableName
					) AliasName
					
					group by UserGroupId,CompanyId,UserGroupName,UserGroupDetails,ModifedDate
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable
	where DestinationDBTable.UserGroupId = SourceDBTable.UserGroupId and SourceDBTable.CompanyId=@CompanyId
			
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[App_UserGroupAccess_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_UserGroupAccess_ListData] 1
CREATE  PROCEDURE [dbo].[App_UserGroupAccess_ListData]   
 @UserGroupId as BIGINT =0
 AS  
Set nocount on;  
BEGIN    

	Declare @UserGroup as nvarchar(100)
	
	Select @UserGroup = UserGroupName From App_UserGroup Where UserGroupId=@UserGroupId

	SELECT PRM.MenuCode,@UserGroup as UserGroupName,@UserGroupId as UserGroupId,
		isnull(PRM.MenuGroup,PRM.MenuCode) AS MenuGroup, PRM.MenuLevel,  MenuLevelType, 
		(CASE WHEN PRM.MenuLevel = 1 THEN '<b>' + PRM.Menuname + '</b>' 
		 When PRM.MenuLevel = 2 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname 
		 When PRM.MenuLevel = 3 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 When PRM.MenuLevel = 4 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 When PRM.MenuLevel = 5 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 End) as MenuName,
		 PRM.MenuSno as SrNo,PRM.MenuType,'N' as Modifed, 
		(Case When MenuLevelType= 'C' Then  Isnull(UAG.AccessId, 0)  Else 0 End) as AccessId,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.ViewAccess, 0) Else 0 End) as ViewAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.AddAccess, 0) Else 0 End) as AddAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.EditAccess, 0) Else 0 End) as EditAccess, 
		(Case When MenuLevelType= 'C' Then Isnull(UAG.SaveAccess, 0) Else 0 End) as SaveAccess, 
		(Case When MenuLevelType= 'C' Then Isnull(UAG.DeleteAccess, 0) Else 0 End) as DeleteAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.PrintAccess, 0) Else 0 End) as PrintAccess  
	FROM App_ProjectMenu(NoLock) PRM 
	Left Outer Join App_UserGroupAccess(NoLock) UAG on UAG.MenuCode= PRM.MenuCode And UAG.UserGroupId=@UserGroupId
	WHERE PRM.MenuLock = 0 and PRM.menucode <> 110006
	ORDER BY CAST('/' + MenuSno + '/' AS hierarchyid),MenuLevel    
END  

GO
/****** Object:  StoredProcedure [dbo].[App_UserGroupAccess_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[App_UserGroupAccess_Manage]
 @AccessId as Bigint=0,
 @UserGroupId as Bigint =0,
 @MenuCode as nvarchar(6)='',
 @ViewAccess as tinyint=0,
 @AddAccess as tinyint=0,
 @EditAccess as tinyint=0,
 @SaveAccess as tinyint=0,
 @DeleteAccess as tinyint=0,
 @PrintAccess as tinyint=0,
 @ReturnMessage as NVARCHAR(255)=''  output,
 @ReturnId as Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	

	BEGIN TRY  
		IF @AccessId = 0 ---ADD RECORD
			BEGIN
				INSERT INTO  App_UserGroupAccess (UserGroupId,MenuCode,ViewAccess,AddAccess,EditAccess,SaveAccess,DeleteAccess,PrintAccess)
			   VALUES (@UserGroupId,@MenuCode,@ViewAccess,@AddAccess,@EditAccess,@SaveAccess,@DeleteAccess,@PrintAccess)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
				if @ViewAccess=1
					BEGIN
						UPDATE App_UserGroupAccess SET UserGroupId = @UserGroupId,
						MenuCode = @MenuCode,
						ViewAccess =@ViewAccess,
						AddAccess=@AddAccess,
						EditAccess=@EditAccess,
						SaveAccess = @SaveAccess,
						DeleteAccess=@DeleteAccess,
						PrintAccess=@PrintAccess
						WHERE AccessId = @AccessId
					END
				ELSE
					BEGIN
						DELETE FROM App_UserGroupAccess WHERE AccessId = @AccessId
					END

				IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @AccessId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


End
GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_AuditTrail]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select * from App_Users_AuditTrail order by UserAuditTrailId desc
--App_UserMaster_AuditTrail 'Administrator','Administrator Deparment1','BUU'
--App_UserMaster_AuditTrail 'Administrator','Administrator Deparment1','','App_Company'
CREATE PROCEDURE [dbo].[App_UserMaster_AuditTrail]
	@CompanyId as BIGINT, 
	@txtUserName as NVARCHAR(100)='',	
	@Name as NVARCHAR(100)='',
	@AuditTrail as NVARCHAR(500)='',
	@TableName as NVARCHAR(100)=''
	
	
AS
SET nocount on;
BEGIN

	INSERT INTO App_Users_AuditTrail (CompanyId,UserId,LogEvent,Code) 
	(select @CompanyId,@txtUserName ,REPLACE(ATL.Comments,'{Name}', @Name),ATL.code
	FROM APP_AuditTrail_Lookup(NOLOCK) as ATL 
	where (ATL.Code like @AuditTrail) OR (TableName= @TableName) )
	

		 
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_Login]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec App_UserMaster_Login 'DVFUz+31bkU='
--Exec UserMaster_Login 'fIos1g+9Guw=','Manager','BEAdy5S5aS/tU7xpwgPWPg=='
CREATE PROCEDURE [dbo].[App_UserMaster_Login] 
	@txtLoginName as NVARCHAR(100)=''
	
AS
SET nocount on;
BEGIN

	Declare @AuditTrail as tinyint,@LoginAttempt as tinyint

	SELECT @LoginAttempt = LoginAttempt,@AuditTrail=AuditTrail from App_ApplicationSetup (NOLOCK) 

	SELECT UM.*,'' as BusinessUnitName, 0 asBusinessUnitId,'' as BusinessUnitCode,0 as BranchId,''  as BranchName,CompanyName
	,@LoginAttempt as LoginAttempt,@AuditTrail as AuditTrail
	FROM  App_UserMaster (NOLOCK)  AS UM
	INNER JOIN App_UserGroup (NOLOCK)  AS UG ON UM.UserGroupId = UG.UserGroupId
    LEFT OUTER JOIN App_CompanyMaster (NOLOCK)  AS COM ON COM.CompanyID = UM.CompanyId
    WHERE LoginName=@txtLoginName
			
		 
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[App_UserMaster_Update_Login_Status]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- execute App_UserMaster_Update_Login_Status 'DVFUz%2b31bkU%3d','admin','Administrator','VL',0
CREATE PROCEDURE [dbo].[App_UserMaster_Update_Login_Status] 
	@txtLoginName as NVARCHAR(100)='',
	@strLoginName as NVARCHAR(100)='',
	@txtUserName as NVARCHAR(100)='',
	@LoginType as nvarchar(5)='',
	@AuditTrail as tinyint=0
	
AS
SET nocount on;
BEGIN

	Declare @CompanyId as bigint
	
	Select @CompanyId = CompanyId from App_Users where LoginName = @txtLoginName
	
	PRINT(@CompanyId)

	IF @LoginType = 'IVL' --INVALID LOGIN
		
		Update App_Users Set UserLockCount=UserLockCount+1 WHERE LoginName=@txtLoginName
		
		IF @AuditTrail=0
				Execute App_UserMaster_AuditTrail @CompanyId,@strLoginName,@strLoginName,'UIL'
		
	IF @LoginType='LA' --ACCOUNT LOCK
		BEGIN
			Update App_Users Set UserLockCount=0,RecordStatus = 2 WHERE LoginName=@txtLoginName
			
			IF @AuditTrail=0
				Execute App_UserMaster_AuditTrail @CompanyId,@strLoginName,@strLoginName,'ULCK'
		END
	
	IF @LoginType='VL' --VALID LOGIN
		BEGIN
			Update App_Users Set UserLockCount=0,LastLogin=GetDate() WHERE LoginName=@txtLoginName
			
			IF @AuditTrail=0
				Execute App_UserMaster_AuditTrail @CompanyId,@strLoginName,@strLoginName,'ULS'
		END
			
		 
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[App_UserMasterAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Users_AuditTrail_Sync] '2012-09-03 16:52:33.983'
CREATE PROCEDURE [dbo].[App_UserMasterAuditTrail_Sync]
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.App_Users_AuditTrail
			([UserAuditTrailId],[CompanyId],[LogDateTime],[LogEvent],[UserId],[code])
		select
			SourceDBTable.[UserAuditTrailId],SourceDBTable.[CompanyId],SourceDBTable.[LogDateTime] ,SourceDBTable.[LogEvent],SourceDBTable.[UserId],SourceDBTable.[code]
		from App_Users_AuditTrail (NOLOCK)  SourceDBTable
		where LogDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.App_Users_AuditTrail (NOLOCK)  DestinationDBTable
						 where DestinationDBTable.UserAuditTrailId = SourceDBTable.UserAuditTrailId)
						 
--Delete Record	
		
		Delete From App_Users_AuditTrail Where LogDateTime <= @LogDateTime
		
	End
Set nocount off;


--drop procedure App_Users_AuditTrail_Sync
GO
/****** Object:  StoredProcedure [dbo].[App_Users_AuditTrail_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec  [App_Users_AuditTrail_Rpt]  '','2019-03-01 00:00:00','2019-03-18 23:59:000','','Local Database Backup Failed',0
CREATE PROCEDURE [dbo].[App_Users_AuditTrail_Rpt] 
	@CompanyId as nvarchar(100) = '',
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@UserList AS varchar(4000)='',
	@FilterParameter AS varchar(4000)='',	
	@OrderBy as tinyint=0
	
AS
SET NOCOUNT ON;
BEGIN

	SELECT ROW_NUMBER() OVER (ORDER BY LogDateTime ASC)AS [Sr No], Convert(varchar, LogDateTime, 105) As [Log Date]
	,substring(convert(varchar(8), LogDateTime, 108), 0, 6) As [Log Time]
	,UserId as [Login Name],LogEvent as [Event] FROM App_Users_AuditTrail (NOLOCK) 
	    
	WHERE (@CompanyId = '' or  CompanyId IN (select * from dbo.CSVToTable(@CompanyId))) 
	AND (LogDateTime BETWEEN @ReportFromDate AND @ReportToDate) 
	AND (@UserList = '' OR UserId IN (select * from dbo.CSVToTable(@UserList)))
	AND (@FilterParameter ='' OR LogEvent IN (select * from dbo.CSVToTable(@FilterParameter)))	
    order by Case @OrderBy When 0 Then LogDateTime Else UserAuditTrailId End
END
SET NOCOUNT OFF

--SELECT * FROM App_Users
GO
/****** Object:  StoredProcedure [dbo].[App_Users_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--App_Users_Delete '1,24','UserId','App_Users','Admin','3','admin,arpit',0
CREATE Procedure [dbo].[App_Users_Delete]
	@RecordKeyIds  as nvarchar(max),
	@RecordKeyColunm as nvarchar(100),
	@TableName as nvarchar(100),
	@UserName as nvarchar(100),
	@CompanyId as nvarchar(100),
	@LoginName as nvarchar(20),
	@ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalUserCount as int,@TotalEquipUserCount as int,@DeletedCount as int,@Name AS NVARCHAR(100),@LookUpCode as nvarchar(50)
		Declare @NamesColunm AS nvarchar(100)
		
		SET @NamesColunm=''
		SET @DeletedCount=0
		SET @TotalUserCount=0
		SET @TotalEquipUserCount=0
		
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  

				SET @NamesColunm = LEFT(@LoginName, ISNULL(NULLIF(CHARINDEX(',', @LoginName) - 1, -1),LEN(@LoginName)))
				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))
				SET @LoginName = SUBSTRING(@LoginName,ISNULL(NULLIF(CHARINDEX(',', @LoginName), 0),LEN(@LoginName)) + 1, LEN(@LoginName))

				if @TableName='App_Users' AND @RecordKeyId='1'
					BEGIN
						SET @ReturnMessage ='RECORDS CONTAIN ADMIN USER'
						continue
					END
				ELSE
					BEGIN
					
						Select @TotalUserCount = count(UserAuditTrailId) from App_Users_AuditTrail where UserId = @NamesColunm
						Select @TotalEquipUserCount = count(EquipmentMasterAuditTrailId) from EquipmentMasterAuditTrail where UserName = @NamesColunm
						
						print(@NamesColunm)
						print(@TotalUserCount)
						print(@TotalEquipUserCount)
						
						IF @TotalUserCount > 0 OR @TotalEquipUserCount > 0
						   BEGIN
								SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
								PRINT(@ReturnMessage)
								return
						   END
						
						Select @Name = UserName from App_Users where UserId = @RecordKeyId

						SET @strQuery = 'DELETE FROM ' + @TableName + ' WHERE ' + @RecordKeyColunm + ' = ''' + @RecordKeyId + ''''
						print @strQuery
						EXEC sp_executesql @strQuery
						
						IF  @@RowCount > 0
							BEGIN
														
								execute App_UserMaster_AuditTrail @CompanyId,@Username,@NamesColunm,'USD',''
								SET @ReturnMessage= 'RECORD DELETED SUCCESSFULLY'
								PRINT(@ReturnMessage)
							END
						ELSE
							BEGIN
								SET @ReturnMessage= 'RECORD DELETION FAILED'
								PRINT(@ReturnMessage)
							END
						
					END

			END TRY 
			 
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0
		
		
End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Department_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--App_Users_Department_Populate 1
CREATE Procedure [dbo].[App_Users_Department_Populate]
    @CompanyId as nvarchar(100)=''
As 
Begin
	SET NOCOUNT ON;
           
    SELECT UserName,LoginName
	FROM App_Users (NoLock)
	where username not in ('Guest')
	and CompanyId in (select * from dbo.CSVToTable(@CompanyId))
	Order By UserId

End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_DepartmentWise_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXECUTE App_Users_DepartmentWise_Populate  1,6,'Admin'
CREATE Procedure [dbo].[App_Users_DepartmentWise_Populate]
@sssUserId as BIGINT,
@sssBranchId as BIGINT,
@sssLoginName as NVARCHAR(100)
As 
Begin
	SET NOCOUNT ON;
    Declare @STRAccessibleCompanyId as NVARCHAR(1000)    
	
	SELECT  @STRAccessibleCompanyId = AU.AccessibleCompanyId FROM App_Users (NOLOCK) AU where AU.UserId=@sssUserId 
	--And AU.CompanyId=@sssBranchId
	
	PRINT(@STRAccessibleCompanyId)

	SELECT UserId,Loginname,CompanyId
	From (
			select AU.CompanyId,AU.AccessibleCompanyId, AU.UserId,AU.Loginname
			FROM App_Users (NOLOCK) AU 
			inner join App_Company (NOLOCK) AC ON AC.CompanyId=AU.CompanyId and CompanyLevel=3 
			where (AU.CompanyId=@sssBranchId 
			--and loginName <> 'DVFUz%2b31bkU%3d'
			) 
			union  
			SELECT ACC.CompanyId ,ACC.AccessibleCompanyId ,ACC.UserId,ACC.Loginname 
			FROM App_Users (NOLOCK) ACC 
			LEFT OUTER JOIN  App_Company (NOLOCK) ACD ON ACD.CompanyId=ACC.CompanyId
			WHERE ACC.CompanyId in (select * from dbo.CSVToTable(@STRAccessibleCompanyId)) 
			--and loginName <> 'DVFUz%2b31bkU%3d' 
		) as sa
		order by CompanyId


End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--App_Users_List 1
CREATE  Procedure [dbo].[App_Users_List]
  @RecordKeyId as bigint=0
As 
Begin
	SET NOCOUNT ON;
           
    SELECT UserId,UserGroupId,CompanyId,AccessibleCompanyId,UserName,LoginName,
	LoginPassword,PasswordFrequency,RecordStatus,
	dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed
	FROM App_Users (NoLock)
	Where (@RecordKeyId=0 Or UserId=@RecordKeyId)

End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec [App_Users_Login] 'rVc2S+6vmXE='
CREATE  PROCEDURE [dbo].[App_Users_Login] 
	@txtLoginName as NVARCHAR(100)=''
	
AS
SET nocount on;
BEGIN

	Declare @AuditTrail as tinyint,@LoginAttempt as tinyint,@CompanyCode as bigint,@LoginType as tinyint,@PasswordFrequency as bigint

	SELECT @LoginAttempt = LoginAttempt,@AuditTrail=AuditTrail,@LoginType = LoginType,@PasswordFrequency = PasswordFrequency from App_ApplicationSetup

	SELECT UM.*,
	Isnull(CM.CompanyName,Isnull(BU.CompanyName,BM.CompanyName)) as CompanyName ,Isnull(CM.CompanyId,Isnull(BU.CompanyId,BM.CompanyId)) as CompanyId,
	Isnull(BU.CompanyName,BM.CompanyName) as BusinessUnitName, Isnull(BU.CompanyId,BM.CompanyId) as BusinessUnitId,
	ISNULL(BM.CompanyId,0) as BranchId,BM.CompanyName  as BranchName
	,(SELECT CompanyCode from App_Company where CompanyId=(select AC.GroupId FROM App_Users(NoLock) AU INNER JOIN App_Company AC ON AC.CompanyId=AU.CompanyId WHERE LoginName=@txtLoginName ))AS CompanyCode
	,@LoginAttempt as LoginAttempt,@AuditTrail as AuditTrail,@LoginType	AS LoginType,@PasswordFrequency as AppPasswordFrequency
	FROM  App_Users(NoLock) AS UM
	INNER JOIN App_UserGroup(NoLock) AS UG ON UM.UserGroupId = UG.UserGroupId
    LEFT OUTER JOIN App_Company(NoLock) AS BM ON BM.CompanyID = UM.CompanyId	
	LEFT OUTER JOIN App_Company(NoLock) AS BU ON BU.CompanyID = BM.GroupId
	LEFT OUTER JOIN App_Company(NoLock) AS CM ON CM.CompanyID = BU.GroupId	
    WHERE LoginName=@txtLoginName
			
		 
END
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login_Temp_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_Users_Login_Temp_List] 'DVFUz%2b31bkU%3d','admin','LogIn','5','','0'
CREATE  Procedure [dbo].[App_Users_Login_Temp_List]
 @LoginName as nvarchar(100)='',
 @strLoginName as nvarchar(100)='', 
 @LogType as nvarchar(10)='',
 @SessionTime as smallint = 0,
 @ReturnMessage as nvarchar(500) = '' output,
 @ReturnId as BIGINT = 0  output
As 
Begin
	SET NOCOUNT ON;
	DECLARE @LastLoginDateTime as datetime,@TimeDiff as int,@CompanyId as bigint
	
	if @LogType='LogIn'
		BEGIN
			
			Select @CompanyId = CompanyId from App_Users where LoginName = @LoginName
			SELECT @LastLoginDateTime=LoginDateTime FROM App_Users_Login_Temp(NOLOCK) WHERE LoginName = @LoginName
			
			IF @@ROWCOUNT>0
				BEGIN
					print 'entered'
					
					SET @TimeDiff = (SELECT DATEDIFF(MINUTE,@LastLoginDateTime,GETDATE()))--GET TIME DIFFERENCE 
					PRINT @TimeDiff
						
					IF (@TimeDiff > (@SessionTime))--FIND IF LAST LOGIN IS OVER 5 MINUTES
						BEGIN 
							DELETE FROM App_Users_Login_Temp WHERE LoginName = @LoginName
							execute App_UserMaster_AuditTrail @CompanyId,@strLoginName,@strLoginName,'UALOG',''							
						END
					ELSE
						BEGIN
						print '<5'
							SET @ReturnMessage = 'USER ALREADY LOGIN ! TRY AGAIN IN 10 MINUTES !'
							SET @ReturnId = @@ROWCOUNT
						END	
									
				END
			ELSE --LOGOUT CONDITION
				BEGIN
					SET @ReturnMessage=''
					SET @ReturnId =0
				END
								
		END
    ELSE
		BEGIN
			DELETE FROM App_Users_Login_Temp WHERE LoginName = @LoginName
			IF @@ROWCOUNT>0	
				BEGIN
					SET @ReturnMessage = 'USER LOGOUT SUCCESSFULLY !!!'
					SET @ReturnId = @@ROWCOUNT
				END
		END
End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Login_Temp_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  Procedure [dbo].[App_Users_Login_Temp_Update]
 @LoginName as nvarchar(500)=''
As 
Begin
	SET NOCOUNT ON;
	
	UPDATE App_Users_Login_Temp SET LoginDateTime=GETDATE() 
	WHERE LoginName = @LoginName
	
End



GO
/****** Object:  StoredProcedure [dbo].[App_Users_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec [App_Users_Manage] '26','51','165','','parth1','parth','JFsxAOQUF%2bg%3d','Bdstqndiqljw8AVbAjU3wg%3d%3d',5,1,'Administrator','',0
CREATE  Procedure [dbo].[App_Users_Manage]
	@hdnRecordKeyId as Bigint =0,	
	@UserGroupId as Bigint,
	@CompanyId as bigint ,
	@AccessibleCompanyId as nvarchar(300) ,
	@LoginUserName as nvarchar(100) ,
	@txtLoginName as nvarchar(100) ,
	@LoginName as nvarchar(100) ,
	@LoginPassword as nvarchar(100) ,
	@PasswordFrequency as smallint  ,
	@RecordStatus as tinyint ,
	@UserName as nvarchar(100)='',
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	---CHECK IF RECORD ALREADY EXIST 
	SELECT UserId FROM App_Users (NOLOCK) WHERE LoginName=@LoginName
	And (@hdnRecordKeyId=0 OR UserId <> @hdnRecordKeyId)

	IF @@ROWCOUNT > 0
		BEGIN
			SET @ReturnId=@hdnRecordKeyId
			SET @ReturnMessage = 'RECORD ALREADY EXIST'
			return
		END
	---CHECK IF RECORD ALREADY EXIST 

	BEGIN TRY  
		IF @hdnRecordKeyId = 0 ---ADD RECORD
			
			BEGIN
				
				INSERT INTO  App_Users (UserGroupId,CompanyId,AccessibleCompanyId
				,UserName,LoginName,LoginPassword,PasswordFrequency
				,UserLockCount,RecordStatus
				,CreatedBy,ModifedBy)
				 VALUES (@UserGroupId,@CompanyId,@AccessibleCompanyId 
				,@LoginUserName,@LoginName,@LoginPassword,@PasswordFrequency
				,0,@RecordStatus,@UserName,@UserName)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
						
						execute App_UserMaster_AuditTrail @CompanyId,@UserName,@LoginUserName,'USA'
						
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
			
				 Declare @oldUserGroupId as nvarchar(100),@oldCompanyId as nvarchar(100)
				,@oldAccessibleCompanyId as nvarchar(100),@oldUserName as nvarchar(100),@oldLoginName as nvarchar(100),@oldUserPassword as nvarchar(100),@oldPasswordFrequency as nvarchar(100)
				,@oldRecordStatus as nvarchar(100)
				
				Select @oldLoginName = LoginName,
				@oldUserName = UserName,
				@oldUserPassword = LoginPassword,
				@oldCompanyId = CompanyId,
				@oldAccessibleCompanyId = AccessibleCompanyId,
				@oldUserGroupId = UserGroupId,
				@oldPasswordFrequency = PasswordFrequency,
				@oldRecordStatus = RecordStatus
				from App_Users Where UserId = @hdnRecordKeyId
			
				UPDATE App_Users SET UserGroupId=@UserGroupId,CompanyId = @CompanyId, AccessibleCompanyId = @AccessibleCompanyId, UserName = @LoginUserName, 
				LoginName = @LoginName, LoginPassword = @LoginPassword, PasswordFrequency = @PasswordFrequency, RecordStatus = @RecordStatus, ModifedBy = @UserName, ModifedDate = GetDate() 
				WHERE UserId = @hdnRecordKeyId
								
				IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @hdnRecordKeyId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
						
						IF @RecordStatus = 1 or @RecordStatus = 2
							Begin
								update App_Users set LastPasswordChange = NULL where UserId = @hdnRecordKeyId
							END
						
						IF @oldLoginName <> @LoginName 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMLNU'
							End
						
						IF @oldUserName <> @LoginUserName 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMUNU'
							End
							
						IF @oldUserPassword <> @LoginPassword 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMUPU'
							End	
						
						IF @oldCompanyId <> @CompanyId 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMCGU'
							End
					
						IF @oldAccessibleCompanyId <> @AccessibleCompanyId 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMACU'
							End
						
						IF @oldUserGroupId <> @UserGroupId 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMAGU'
							End
						
						IF @oldPasswordFrequency <> @PasswordFrequency 
							Begin
								execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMPFU'
							End
						
						IF @oldRecordStatus <> @RecordStatus 
							Begin
								
								if @RecordStatus = 0
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMUSAU'
									End
								else if @RecordStatus = 1
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMUSNAU'
									End
								else
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@UserName,@txtLoginName,'UMUSBU'
									End
							End
						
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Password_Change]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--UserMaster_PassowrdChange 'DVFUz%2b31bkU%3d','Administrator','BEAdy5S5aS9ROCOA%2bOOVXA%3d%3d'
CREATE  PROCEDURE [dbo].[App_Users_Password_Change]
	@txtLoginName as NVARCHAR(100)='',
	@strLoginName as NVARCHAR(100)='',
	@txtUserName as NVARCHAR(100)='',
	@txtPassword as  NVARCHAR(100)='',
	@txtNewPassword as  NVARCHAR(100)='',
	@AuditTrail as tinyint=0,
	@ReturnId as tinyint=0 output,
	@ReturnMessage as NVARCHAR(255)=''  output
	
AS
SET nocount on;
BEGIN

	BEGIN TRY 
	
		DECLARE @CompanyId as bigint
		
		SELECT @CompanyId = CompanyId from App_Users
		where LoginName = @txtLoginName
	
		UPDATE App_Users set LoginPassword=@txtNewPassword,LastPasswordChange=GetDate(),UserLockCount = 0 Where LoginName=@txtLoginName
		AND LoginPassword=@txtPassword
		
		IF @@ROWCOUNT > 0 
			BEGIN
				SET @ReturnMessage ='PASSWORD CHANGED SUCCESSFULLY. PLEASE RE LOGIN'
				SET @ReturnId=0
				
				if @AuditTrail=1
					execute App_UserMaster_AuditTrail @CompanyId,@strLoginName,@strLoginName,'CPS'
					delete from dbo.App_Users_Login_Temp where LoginName=@txtLoginName
			END
		ELSE
			BEGIN
				SET @ReturnId=1
				SET @ReturnMessage ='UNABLE TO UPDATE PASSWORD REQUEST, PASSWORD DOES NOT MATCH'
				--execute App_UserMaster_AuditTrail @CompanyId,@txtUserName,@strLoginName,'CPF'
			END
			
	END TRY
	  
	BEGIN CATCH  
		SET @ReturnId=1
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


END

Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_UserGroup_Populate] 1
CREATE Procedure [dbo].[App_Users_Populate]
@Users as nvarchar(255)=''
As 
Begin
	SET NOCOUNT ON;
           
    SELECT UserId,Replace (UserName ,'{Name}','') as Users
	FROM App_Users (NoLock)
	where LoginName <> 'rVc2S+6vmXE='
	Order By UserId

End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--App_Users_Rpt 1,2,'',''
CREATE  Procedure [dbo].[App_Users_Rpt]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @SelectedRecord as NVARCHAR(100)=''
 
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint

	SELECT ROW_NUMBER() OVER (ORDER BY UserName ASC)AS RowNumber
	,UserId,UserName,LoginName,UserGroupName,
	AC.CompanyName as [Comm. Group],AC.CompanyName as [Department Name],
	(Case When U.RecordStatus = 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,U.ModifedBy,
	dbo.GetLastModifedDate(U.ModifedDate) as ModifedDate

	INTO #Results FROM App_Users(NoLock) as U 
	Inner Join App_UserGroup(NoLock)  UG ON UG.UserGroupId=U.UserGroupId
	Inner Join App_Company(NoLock) AC ON U.CompanyId=AC.CompanyId
	Where (UserName like ('%' + @SearchText + '%')) 
	--and 
	--(@SelectedRecord = '') OR UserId in (Select * from dbo.CSVToTable(@SelectedRecord))
    and 
	U.UserName <> 'Guest' 
		 
    Set @RecordCount = @@ROWCOUNT
           
    SELECT UserId,@RecordCount as RecordCount,LoginName,UserName,
	UserGroupName,[Comm. Group],[Department Name],
	RecordStatus,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
     
    DROP TABLE #Results

End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--App_Users_Search 1,25,''
CREATE  Procedure [dbo].[App_Users_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)=''
 
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint

	SELECT ROW_NUMBER() OVER (ORDER BY UserName ASC)AS RowNumber
	,UserId,UserName,LoginName,UserGroupName,
	(Case When U.RecordStatus = 0 Then 'Active' 
	      When U.RecordStatus = 1 Then 'Not Active' 
	      Else 'Blocked' End) as RecordStatus ,U.ModifedBy,
	dbo.GetLastModifedDate(U.ModifedDate) as ModifedDate
	INTO #Results FROM App_Users(NoLock) as U Inner Join App_UserGroup(NoLock)  UG ON UG.UserGroupId=U.UserGroupId
	Where (UserName like ('%' + @SearchText + '%') or UserGroupName like ('%' + @SearchText + '%') Or U.ModifedBy like ('%' + @SearchText + '%')) 
	and UserName <> 'Guest'

     
    Set @RecordCount = @@ROWCOUNT
           
    SELECT UserId,@RecordCount as RecordCount,LoginName,UserName,UserGroupName,RecordStatus,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	
     
    DROP TABLE #Results

End


GO
/****** Object:  StoredProcedure [dbo].[App_Users_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--[App_User_Sync] 3
CREATE PROCEDURE [dbo].[App_Users_Sync]
	@BranchId as bigint = 0
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.App_User
			([UserGroupId],[CompanyId] ,[AccessibleCompanyId],[UserName],[LoginName],[LoginPassword],[PasswordFrequency],[LastPasswordChange]
           ,[UserLockCount],[RecordStatus])
		select
			SourceDBTable.[UserGroupId],SourceDBTable.[CompanyId] ,SourceDBTable.[AccessibleCompanyId],SourceDBTable.[UserName]
           ,SourceDBTable.[LoginName],SourceDBTable.[LoginPassword],SourceDBTable.[PasswordFrequency],SourceDBTable.[LastPasswordChange],SourceDBTable.[UserLockCount],SourceDBTable.[RecordStatus]
		from App_User SourceDBTable
		where CompanyId=@BranchId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.App_User DestinationDBTable
						 where DestinationDBTable.UserId = SourceDBTable.UserId)
			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.App_User 
	set    [UserGroupId]=SourceDBTable.[UserGroupId],[CompanyId]=SourceDBTable.[CompanyId],[AccessibleCompanyId]=SourceDBTable.[AccessibleCompanyId],[UserType]=SourceDBTable.[UserType]
		   ,[UserName]=SourceDBTable.[UserName],[LoginName]=SourceDBTable.[LoginName],[UserPassword]=SourceDBTable.[UserPassword],[PasswordFrequency]=SourceDBTable.[PasswordFrequency]
		   ,[LastPasswordChange]=SourceDBTable.[LastPasswordChange],[UserLockCount]=SourceDBTable.[UserLockCount],[UserStatus]=SourceDBTable.[UserStatus]
	from	ICDAS_3_0_Archive.dbo.App_User DestinationDBTable,
			(
				select	max(TableName) as TableName,  [UserGroupId],[CompanyId],[AccessibleCompanyId],[UserType],[UserName],[LoginName],[UserPassword]
					   ,[PasswordFrequency],[LastPasswordChange],[UserLockCount],[UserStatus]
				from
					(
						select	'SourceTableName' as TableName,[UserGroupId],[CompanyId],[AccessibleCompanyId],[UserType],[UserName],[LoginName],[UserPassword]
					   ,[PasswordFrequency],[LastPasswordChange],[UserLockCount],[UserStatus]
						from App_User SourceTableName
						
						union all
						
						select	'DestinationiTableName' as TableName, [UserGroupId],[CompanyId],[AccessibleCompanyId],[UserType],[UserName],[LoginName],[UserPassword]
					   ,[PasswordFrequency],[LastPasswordChange],[UserLockCount],[UserStatus]
						from ICDAS_3_0_Archive.dbo.App_User DestinationTableName
					) AliasName
					
					group by [UserGroupId],[CompanyId],[AccessibleCompanyId],[UserType],[UserName],[LoginName],[UserPassword]
						   ,[PasswordFrequency],[LastPasswordChange],[UserLockCount],[UserStatus]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable

	where DestinationDBTable.UserId = SourceDBTable.UserId and SourceDBTable.CompanyId=@BranchId
			
	End
Set nocount off;



GO
/****** Object:  StoredProcedure [dbo].[App_Users_Update_Login_Status]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- App_Users_Update_Login_Status 'DVFUz%2b31bkU%3d','Administrator','VL','0'
CREATE  PROCEDURE [dbo].[App_Users_Update_Login_Status] 
	@txtLoginName as NVARCHAR(100)='',
	@strLoginName as NVARCHAR(100)='',
	@txtUserName as NVARCHAR(100)='',
	@LoginType as nvarchar(5)='',
	@AuditTrail as tinyint=0
	
AS
SET nocount on;
BEGIN

	   Declare @STRCompanyId as BIGINT  
	   SELECT  @STRCompanyId = CompanyId FROM App_Users (NOLOCK) AU where LoginName=@txtLoginName

	IF @LoginType='IVL' --INVALID LOGIN
		BEGIN
			print 'IVL'
			Update App_Users Set UserLockCount=UserLockCount+1 WHERE LoginName=@txtLoginName
			IF @AuditTrail=0
				execute App_UserMaster_AuditTrail @STRCompanyId,@strLoginName,@strLoginName,'UIL'
		END
	IF @LoginType='IVLLD' --INVALID LOGIN
		BEGIN
			print 'IVL'
			IF @AuditTrail=0
				execute App_UserMaster_AuditTrail @STRCompanyId,@strLoginName,@strLoginName,'UIL'
		END
	IF @LoginType='LA' --ACCOUNT LOCK
		BEGIN
			print 'LA'
			Update App_Users Set UserLockCount=0,RecordStatus=2 WHERE LoginName=@txtLoginName
			IF @AuditTrail=0
				execute App_UserMaster_AuditTrail @STRCompanyId,@strLoginName,@strLoginName,'ULCK'
		END
	ELSE IF @LoginType='VL' --VALID LOGIN
		BEGIN
			PRINT 'VL'
			Update App_Users Set UserLockCount=0,LastLogin=GetDate() WHERE LoginName=@txtLoginName
			IF @AuditTrail=0
				execute App_UserMaster_AuditTrail @STRCompanyId,@strLoginName,@strLoginName,'ULS'
				INSERT INTO App_Users_Login_Temp (LoginName,LoginDateTime)VALUES(@txtLoginName,GETDATE()) --INSERT 'LoginName' RECORD IN 'App_Users_Login_Temp' TABLE TO AVOID MULTIPLE DEVICE LOGIN
				print 'Success'
		END				 
END
Set nocount off;

--SELECT * FROM App_Users_AuditTrail  ORDER BY  UserAuditTrailId DESC
GO
/****** Object:  StoredProcedure [dbo].[AppCompany_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec AppCompany_Populate 0
CREATE PROCEDURE [dbo].[AppCompany_Populate]
@BranchId as bigint = 0
AS
SET NOCOUNT ON;
BEGIN
	SELECT CompanyId,CompanyName,AchiveMonth,ArchiveEmailReminderDate,CompanyLevel FROM  App_Company
	WHERE (@BranchId = 0 or CompanyId = @BranchId) And CompanyLevel=3
END
SET NOCOUNT OFF;


GO
/****** Object:  StoredProcedure [dbo].[AppCompany_SupervisorEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Exec [AppCompany_SupervisorEmailTime] 163
CREATE  PROCEDURE [dbo].[AppCompany_SupervisorEmailTime]
	@BranchId as bigint = 0
AS
Set nocount on;
	Begin

	
	SELECT 
	(Case  When DateDiff(mi,EmailTime,GetDate())>=1440 Then 1 Else 0 End) as SupervisorEmailDiff,EmailTime 
	FROM App_Company where  CompanyId=@BranchId
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[AppCompany_SupervisorEmailTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[AppCompany_SupervisorEmailTime_Update]
	@BranchId as bigint = 0
AS
Set nocount on;
	Begin

	Declare @strSupervisorEmailTime as varchar(25),@EmailTime as  DateTime

	Select @EmailTime=EmailTime from App_Company where CompanyId=@BranchId
	
	Set @strSupervisorEmailTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@EmailTime,108)
	
	Update App_Company set EmailTime = @strSupervisorEmailTime where CompanyId=@BranchId

End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BackupTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_BackupTime]
	
AS
Set nocount on;
	Begin

	SELECT (Case  When DateDiff(mi,BackupTime,GetDate())>=1440 Then 1 Else 0 End) as BackupDateDiff,BackupTime,
	(Case  When DateDiff(mi,SynchRTCTime,GetDate())>=1440 Then 1 Else 0 End) as SYNCDateDiff,SynchRTCTime ,
	BackupLocalPath,BackupRemotePath,HistoryRestoreDBPath,BioSynchRTCTime FROM App_ApplicationSetup  

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BackupTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_BackupTime_Update]
	
AS
Set nocount on;
	Begin

	Declare @strBackupTime as varchar(25),@BackupTime as  DateTime

	Select @BackupTime=BackupTime from App_ApplicationSetup 

	Set @strBackupTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@BackupTime,108)

	Update App_ApplicationSetup set BackupTime = @strBackupTime


	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_BIOSYNCTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [dbo].[ApplicationSetup_BIOSYNCTime_Update]
	
AS
Set nocount on;
	Begin

	Declare @strBIOSYNCTime as varchar(25),@BIOSYNCTime as  DateTime

	Select @BIOSYNCTime=BioSynchRTCTime  from App_ApplicationSetup 

	Set @strBIOSYNCTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@BIOSYNCTime,108)

	Update App_ApplicationSetup set BioSynchRTCTime = @strBIOSYNCTime


	End
Set nocount off;



GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_CheckStatus]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[ApplicationSetup_CheckStatus]
	@ApplicationSetupId as Bigint=0
AS
Set nocount on;
	Begin

	SELECT *,CN.CompanyName FROM App_ApplicationSetup 
	OUTER APPLY
	(
		SELECT CompanyName
		FROM App_Company
		WHERE CompanyId = 1
	)CN
	Where (@ApplicationSetupId = 0 or ApplicationSetupId = @ApplicationSetupId)

	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_EmailCheck]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_EmailCheck]
	
AS
Set nocount on;
	Begin
	Declare @CompanyName as nvarchar(100)

	Select @CompanyName=CompanyName from App_Company where GroupId = 0
	
	SELECT 	@CompanyName as CompanyName,SMTPAuthentication,SMTPEmail,SMTPAddress,SMTPUserName,SMTPPassword,SMTPEmailPort, SMTPEmailSSL,EmailSignature 
	FROM App_ApplicationSetup where EmailSystem=0

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[ApplicationSetup_List]
	@ApplicationSetupId as Bigint=0
	
As 
Begin
	SET NOCOUNT ON;
    begin

	SELECT 
	 *
	 FROM App_ApplicationSetup (NoLock)
	 Where (@ApplicationSetupId = 0 or ApplicationSetupId = @ApplicationSetupId)
	End
End


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[ApplicationSetup_ListData]
	@ApplicationSetupId as Bigint=0
AS
Set nocount on;
	Begin

	SELECT * FROM App_ApplicationSetup (NOLOCK)  Where (@ApplicationSetupId = 0 or ApplicationSetupId = @ApplicationSetupId)

	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_SMSCheck]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_SMSCheck]
	
AS
Set nocount on;
	Begin
	Declare @CompanyName as nvarchar(100)

	Select @CompanyName=CompanyName from App_Company where GroupId = 0
	
	SELECT 	@CompanyName as CompanyName,CommunicationPort,Parity,BaudRate,DataBits,StopBits,SMSOption,SMSDelay
	FROM App_ApplicationSetup where SMSSystem=0

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_SYNCTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_SYNCTime_Update]
	
AS
Set nocount on;
	Begin

	Declare @strSYNCTime as varchar(25),@SYNCTime as  DateTime

	Select @SYNCTime=SynchRTCTime  from App_ApplicationSetup 

	Set @strSYNCTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@SYNCTime,108)

	Update App_ApplicationSetup set SynchRTCTime = @strSYNCTime


	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_TestEmailTime]
	
AS
Set nocount on;
	Begin

	SELECT *,(Case  When DateDiff(mi,TestEmailTime,GetDate())>=1440 Then 1 Else 0 End) as TestEmailTimeDiff FROM App_ApplicationSetup  

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestEmailTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_TestEmailTime_Update]
	
AS
Set nocount on;
	Begin

	Declare @strTestEmailTime as varchar(25),@TestEmailTime as  DateTime

	Select @TestEmailTime=TestEmailTime from App_ApplicationSetup 

	Set @strTestEmailTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@TestEmailTime,108)

	Update App_ApplicationSetup set TestEmailTime = @strTestEmailTime


	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestSMSTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_TestSMSTime]
	
AS
Set nocount on;
	Begin

	SELECT *,(Case  When DateDiff(mi,TestSMSTime,GetDate())>=1440 Then 1 Else 0 End) as TestSMSTimeDiff FROM App_ApplicationSetup 

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ApplicationSetup_TestSMSTime_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[ApplicationSetup_TestSMSTime_Update]
	
AS
Set nocount on;
	Begin

	Declare @strTestSMSTime as varchar(25),@TestSMSTime as  DateTime

	Select @TestSMSTime=TestSMSTime from App_ApplicationSetup

	Set @strTestSMSTime = Convert(varchar(25),GetDate(),111) + ' ' + Convert(varchar(25),@TestSMSTime,108)

	Update App_ApplicationSetup set TestSMSTime = @strTestSMSTime


	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[BranchMaster_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[BranchMaster_Populate]
@BranchId as bigint = 0
AS
SET NOCOUNT ON;
BEGIN
	SELECT BranchId,BranchName,ArchiveMonth,ArchiveEmailReminderDate FROM  BranchMaster
	WHERE (@BranchId = 0 or BranchId = @BranchId)
END
SET NOCOUNT OFF;


GO
/****** Object:  StoredProcedure [dbo].[BranchMaster_SupervisorEmailTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Exec [BranchMaster_SupervisorEmailTime] 1
CREATE  PROCEDURE [dbo].[BranchMaster_SupervisorEmailTime]
	@BranchId as bigint = 0
AS
Set nocount on;
	Begin

	
	SELECT 
	(Case  When DateDiff(mi,EmailTime,GetDate())>=1440 Then 1 Else 0 End) as SupervisorEmailDiff,EmailTime 
	FROM BranchMaster where  BranchId=@BranchId
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[BusinessUnit_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--BusinessUnit_Delete '8','CompanyId','App_Company','Admin','3'
CREATE  Procedure [dbo].[BusinessUnit_Delete]
	@RecordKeyIds  as nvarchar(max),
	@RecordKeyColunm as nvarchar(100),
	@TableName as nvarchar(100),
	@UserName as nvarchar(100),
	@CompanyId as nvarchar(100),
	@CompanyLevel as nvarchar(100),
	@ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalCount as int,@DeletedCount as int,@Name AS NVARCHAR(100),@LookUpCode as nvarchar(50)
		Declare @NamesColunm AS nvarchar(100)
		Set @NamesColunm=''
		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				SET @TotalCount=@TotalCount+1

				SET @NamesColunm = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

				if @TableName='App_Users' AND @RecordKeyId='1'
					BEGIN
						SET @ReturnMessage ='RECORDS CONTAIN ADMIN USER'
						continue
					END
				ELSE
					BEGIN
					
						Select @TotalCount = count(CompanyId) from App_Company where GroupId = @RecordKeyId
						
						IF @TotalCount > 0 
						   BEGIN
								SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
								PRINT(@ReturnMessage)
								return
						   END
						
						Select @Name = CompanyName from App_Company where CompanyId = @RecordKeyId

						SET @strQuery = 'DELETE FROM ' + @TableName + ' WHERE ' + @RecordKeyColunm + ' = ''' + @RecordKeyId + ''''
						print @strQuery
						EXEC sp_executesql @strQuery
						
						IF  @@RowCount > 0
							BEGIN
														
								execute App_UserMaster_AuditTrail @CompanyId,@Username,@Name,'BUD',''
								SET @ReturnMessage= 'RECORD DELETED SUCCESSFULLY'
								PRINT(@ReturnMessage)
							END
						ELSE
							BEGIN
								SET @ReturnMessage= 'RECORD DELETION FAILED'
								PRINT(@ReturnMessage)
							END
						
					END

			END TRY 
			 
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0
		
		
End


GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
	--Execute CommGroup_Manage '0','2','Comm Group 3','1','QWFRRV3435','Administrator','','0'
	--select *from app_company
	CREATE PROCEDURE [dbo].[CommGroup_Manage] 
		@hdnRecordKeyId as Bigint =0,
		@CompanyId as BIGINT,
		@CompanyLevel as tinyint=0,
		@CompanyName as NVARCHAR(200)='',
		@GroupId as bigint=0,				
		@ActivationKey as nvarchar(200) = '',
		@LoginName as nvarchar(100)='',
		@ReturnMessage as varchar(500)='' output,
		@ReturnId as bigint =0 output
	
		AS
		SET nocount on;
		BEGIN

			Declare @CompanyCode as nvarchar(10),@Validation as nvarchar(10)								  			
			set @Validation='True'

			SELECT *,CompanyId from App_Company (nolock) where CompanyName = rtrim(ltrim(@CompanyName)) 
			and CompanyLevel=@CompanyLevel
			and (@hdnRecordKeyId=0 or CompanyId<>@hdnRecordKeyId)
			if @@ROWCOUNT>0
			BEGIN
				SET @ReturnMessage = 'COMM. GROUP ALREADY EXIST  !!'
				SET @ReturnId = 0
				Set @Validation='False'
			END

		if @Validation='True'
			begin
				begin try
				if @hdnRecordKeyId=0
					begin


						set @CompanyCode = (Select top (1)convert(int,CompanyCode)+1 FROM App_Company (NOLOCK)   WHERE CompanyLevel=2 order by CompanyId desc)

						if @CompanyCode  is null 
						BEGIN 
							set @CompanyCode = 1001
						END


						insert into App_Company(CompanyLevel,GroupId,CompanyName,ActivationKey,CompanyCode,CreateDate,CreatedBy,ModifedBy)
						values(@CompanyLevel,@GroupId,@CompanyName,@ActivationKey,@CompanyCode,GETDATE(),@LoginName,@LoginName)
							if @@ROWCOUNT>0
							BEGIN
								SET @ReturnId = @@IDENTITY
								set @ReturnMessage = 'RECORD ADDED SUCCESSFULLY'
								
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'BUA'
								
							END
						ELSE
							BEGIN
								SET @ReturnId = 0
								SET @ReturnMessage ='FAILED TO ADD RECORD'
				
							END		
					end
				else
					begin
						update App_Company set CompanyName=@CompanyName			
						,ActivationKey = @ActivationKey
						,ModifedBy = @LoginName
						,ModifedDate = GetDate()
						where CompanyId=@hdnRecordKeyId AND CompanyLevel = @CompanyLevel
						if @@ROWCOUNT>0
							BEGIN
								SET @ReturnId = @hdnRecordKeyId
								set @ReturnMessage = 'RECORD UPDATED SUCESSFULLY'								
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'BUU'
							END
						ELSE
							BEGIN
								SET @ReturnId = 0
								SET @ReturnMessage ='FAILED TO UPDATE COMM. GROUP DETAILS!!'
				
							END
						end
				end try
				begin catch
					set @ReturnMessage=dbo.RemoveSpecialChars(error_message())
				end catch
			end
	END
	Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC CommGroup_Populate ''
CREATE  PROCEDURE [dbo].[CommGroup_Populate]
  @AccessibleCompanyIds as nvarchar(100)=''
AS
Set nocount on;
	Begin
		SELECT AC.CompanyCode,AC.CompanyName 
		From App_Company (NOLOCK) AC
		OUTER APPLY
		(
			SELECT Groupid
			FROM App_Company
			WHERE CompanyId in (Select [SId] From dbo.CSVToTable(@AccessibleCompanyIds))
			AND CompanyLevel=3 and RecordStatus=0
		)GID
		where AC.CompanyId = GID.Groupid
		AND AC.CompanyLevel=2 and AC.RecordStatus=0 

		
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[CommGroup_Search] 1,25,'','2'
CREATE Procedure [dbo].[CommGroup_Rpt]

As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint
	select  ROW_NUMBER() OVER (ORDER BY CompanyName ASC)AS [Sr. No.],CompanyName as [Comm. Group Name] ,
	CompanyCode as [Code] from App_Company(nolock) where CompanyLevel=2
End


GO
/****** Object:  StoredProcedure [dbo].[CommGroup_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[CommGroup_Search] 1,25,'','2'
CREATE Procedure [dbo].[CommGroup_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @CompanyLevel as tinyint=0,
 @SelectedRecord as NVARCHAR(100)=''
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint,@CompanyLevel_Sp as tinyint

		Set @CompanyLevel_Sp= @CompanyLevel 
	
	
		Create TABLE #Company_Temp 
			(
				CompanyId bigint, 
				CompanyName nvarchar(500)
			)
			INSERT INTO #Company_Temp
			Exec App_Company_Populate @CompanyLevel_Sp
			
			SELECT ROW_NUMBER() OVER (ORDER BY AG.CompanyName ASC)AS RowNumber,AG.GroupId,
			AG.CompanyId,AG.CompanyName,AG.CompanyCode,ModifedBy,
			dbo.GetLastModifedDate(ModifedDate) as ModifedDate
			INTO #Results FROM App_Company AG (NoLock)
			Inner Join #Company_Temp GT ON GT.CompanyId = Case When @CompanyLevel =1 Then AG.CompanyId Else AG.GroupId End 
			Where (AG.CompanyName like ('%' + @SearchText + '%') or CompanyCode like ('%' + @SearchText + '%') or GT.CompanyName like ('%' + @SearchText + '%') or ModifedBy like ('%' + @SearchText + '%')) 
			And (@CompanyLevel=0 or CompanyLevel=@CompanyLevel) 
			and (@SelectedRecord = '') OR AG.CompanyId in (Select * from dbo.CSVToTable(@SelectedRecord))
			
			Set @RecordCount = @@ROWCOUNT

			Drop Table #Company_Temp
		

           
    SELECT CompanyId,@RecordCount as RecordCount,CompanyName,CompanyCode,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	
     
    DROP TABLE #Results


End


GO
/****** Object:  StoredProcedure [dbo].[Company_Activation]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec Company_Activation 3,'9E64-8489-71C2-F643-048B-0617-4B99-29B3'
	CREATE PROCEDURE [dbo].[Company_Activation] 
		@hdnRecordKeyId as nvarchar(10) ='',
		@SoftKey as nvarchar(100)='',
		@ActivationKey as varchar(500)='' output
	
	AS
	SET nocount on;
	BEGIN
		begin try
			update App_Company set SoftKey=@SoftKey
			where CompanyCode=@hdnRecordKeyId 
			if @@ROWCOUNT>0
				BEGIN
					Select ActivationKey From App_Company (NOLOCK)  where CompanyCode =@hdnRecordKeyId
				END
			ELSE
			print (@@ROWCOUNT)
				BEGIN
					Set @ActivationKey=''
				END
		End try
		Begin catch
			Set @ActivationKey=''
		End catch
	

		 
	END
	Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[Company_Activation_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Company_Activation_Update] 
		@hdnRecordKeyId as nvarchar(10) ='',
		@strValue as nvarchar(5) = ''
	AS
SET nocount on;
	
	BEGIN
			
		update App_Company set ActivationRemainingTime = @strValue where CompanyCode = @hdnRecordKeyId 
		
		if @@ROWCOUNT>0
			BEGIN
				return 1
			END
		ELSE
			BEGIN
				return 0
			END
		 
	END
	Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[Company_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Company_Delete] '17','CompanyId','App_Company','admin','3','0'
CREATE Procedure [dbo].[Company_Delete]
 @RecordKeyIds  as nvarchar(max),
 @RecordKeyColunm as nvarchar(100),
 @TableName as nvarchar(100),
 @UserName as nvarchar(100),
 @CompanyId as nvarchar(100),
 @CompanyLevel as nvarchar(100),
 @ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@TotalCount as int,@DeletedCount as int,@Name as nvarchar(100),@LookUpCode as nvarchar(50)

		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				SET @TotalCount=@TotalCount+1

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

				IF Not EXISTS(SELECT CompanyId FROM App_Company WITH(NOLOCK) WHERE GroupId = @RecordKeyId )
					BEGIN
						IF  Not EXISTS(SELECT AccessibleCompanyId FROM App_Users WITH(NOLOCK) WHERE ','+ AccessibleCompanyId +',' Like '%,'+ @RecordKeyId +',%' )
							BEGIN
								SELECT @Name = CompanyName from App_Company WHERE CompanyId=@RecordKeyId				
								DELETE FROM App_Company WHERE CompanyId=@RecordKeyId
								
								IF  @@RowCount > 0
									BEGIN
										
										IF @CompanyLevel='2'
											SET @LookUpCode = 'BUD'
										ELSE
											SET @LookUpCode = 'DMD'

										EXECUTE App_UserMaster_AuditTrail @CompanyId,@Username,@Name,@LookUpCode,''
										
										SET @ReturnMessage ='RECORD DELETED SUCCESSFULLY'
										PRINT(@ReturnMessage)
										SET @Name=''
										SET @DeletedCount=@DeletedCount+1
										
									END	
								ELSE
									BEGIN
										SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
										PRINT(@ReturnMessage)
									END
							END
						ELSE
							BEGIN
								SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
								PRINT(@ReturnMessage)
							END
					END
			END TRY  
			BEGIN CATCH  				
				IF @ReturnMessage = ''
						SET @ReturnMessage ='CAN NOT DELETE RECORD AS RELATED RECORD IS IN USED'
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0

		--IF @ReturnMessage <> '' 
		--	SET @ReturnMessage= 'Record Deleted Successfully'
		--ELSE
		--	SET @ReturnMessage= 'Record Deletion Failed'
		
		
	
End


GO
/****** Object:  StoredProcedure [dbo].[Company_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Company_List] 1,1
CREATE  Procedure [dbo].[Company_List]
 @RecordKeyId as bigint=0,
 @CompanyLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
    
	
		SELECT 
		[CompanyId],[CompanyLevel],[GroupId],[CompanyName],[CompanyCode],[CompanyAddress],
		Isnull([GeographicalId],0) as [GeographicalId],[Pincode],[Telephone],[Fax],[Email],[Web],
		[Details1],[Details2],[Details3],[Details4],[Details5],[Details6],[Details7],
        [Details8] ,[Details9],[Details10],[Details11],[Details12],[RecordStatus],SoftKey,ActivationKey,ActivationRemainingTime,
		dbo.GetLastModifedDetails(ModifedBy,ModifedDate) as LastModifed
		FROM App_Company (NoLock)
		Where (@RecordKeyId=0 Or CompanyId=@RecordKeyId)
		AND CompanyLevel=@CompanyLevel

End


GO
/****** Object:  StoredProcedure [dbo].[Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Company_Manage '1','Newtronic Lifecare Equipment Pvt .Ltd.','108-ABCD, HINDUSTAN NAKA,KANDIVALI ','0','Administrator','','0'
	--Execute Company_Manage '1','Newtronic Lifecare Equipment Pvt .Ltd.','108-ABCD, HINDUSTAN NAKA,KANDIVALI west','Company Details Updated','0','Administrator','','0'
	--select *from app_company
	CREATE PROCEDURE [dbo].[Company_Manage] 
		@hdnRecordKeyId as Bigint =0,
		@CompanyId as BIGINT,
		@CompanyName as NVARCHAR(100)='',
		@CompanyAddress as NVARCHAR(500)='',
		@RecordStatus as tinyint = 0,
		@LoginName as nvarchar(100)='',
		@ReturnMessage as varchar(500)='' output,
		@ReturnId as bigint =0 output
	
	AS
	SET nocount on;
	BEGIN
		Begin Try
		
			Declare @oldCompanyName as nvarchar(100),@oldAddress as nvarchar(500)
			
			Select @oldCompanyName=CompanyName,@oldAddress=CompanyAddress from App_Company where CompanyLevel=@hdnRecordKeyId AND GroupId = 0
		
			Update App_Company set CompanyName=@CompanyName,CompanyAddress=@CompanyAddress,RecordStatus = @RecordStatus,ModifedBy = @LoginName,ModifedDate = GetDate()
			where CompanyLevel=@hdnRecordKeyId AND GroupId = 0
			
			IF @@ROWCOUNT>0
				
				BEGIN
					
					SET @ReturnId = @hdnRecordKeyId
					set @ReturnMessage = 'RECORD UPDATED SUCCESSFULLY!!'
					
					IF @oldCompanyName <> @CompanyName
					Begin
						execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@LoginName,'CD'
					End
					
					IF @oldAddress <> @CompanyAddress
					Begin
						execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@LoginName,'AD'		
					End
					
				END
				
			ELSE
				BEGIN	
					SET @ReturnId = 0
					SET @ReturnMessage ='RECORD UPDATION FAILED'
				
				END
		End Try
		
		Begin Catch
			       SET @ReturnMessage=dbo.RemoveSpecialChars(error_message())
		End Catch
	

		 
	END
	Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[CompanyMaster_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[GeneralMaster_List] 27
CREATE Procedure [dbo].[CompanyMaster_List]
 @RecordKeyId as bigint=0,
 @CompanyLevel as tinyint =1
As 
Begin
	SET NOCOUNT ON;
           
    SELECT CompanyId,CompanyName,CompanyLevel,CompanyGroup,SystemImplemented,Address,
	dbo.GetLastModifedDetails(ModifedBy,LastModifedDate) as LastModifed
	FROM App_CompanyMaster (NoLock)
	Where (@RecordKeyId=0 Or CompanyId=@RecordKeyId) 
	and (@CompanyLevel = 0 Or CompanyLevel=@CompanyLevel) 

End

GO
/****** Object:  StoredProcedure [dbo].[Database_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Database_Sync '3','2016-11-01 23:59:00.000'
CREATE PROCEDURE [dbo].[Database_Sync]
	@CompanyId as bigint = 0,
	@LogDateTime as Datetime,
	@Username as nvarchar(200)='',
	@ReturnMessage as nvarchar(200)='' OUTPUT,
	@ReturnId as BIGINT =0 OUTPUT
AS
	Set nocount on
	Begin
		BEGIN TRY		
			
			--EXEC App_Company_Sync --'SystemImplemented' column in app_Company Not Found
			--EXEC App_UserGroup_Sync
			--EXEC App_Users_Sync @CompanyId
			EXEC EquipmentMaster_Sync @CompanyId,@LogDateTime
			EXEC EquipmentMasterParameter_Sync @CompanyId
			EXEC App_UserMasterAuditTrail_Sync @LogDateTime
			EXEC EquipmentMasterAuditTrail_Sync @CompanyId,@LogDateTime
			EXEC EquipmentMasterAlarmAuditTrail_Sync @CompanyId,@LogDateTime
			EXEC EquipmentMasterLogReviewApprove_Sync @CompanyId,@LogDateTime --required to create table 'EquipmentMasterLogReviewApprove'
			EXEC EmailLog_Sync @CompanyId,@LogDateTime 
			EXEC SMSLog_Sync @CompanyId,@LogDateTime
			--EXEC EquipmentMasterMKT_Sync @CompanyId,@LogDateTime
			--EXEC EquipmentIOStatus_Sync @CompanyId
			--EXEC EquipmentComponentRunningHours_Sync @CompanyId

			update App_Company set ArchiveEmailReminderDate = DateAdd(year,2,@LogDateTime) Where CompanyId=@CompanyId
			
			IF @@ROWCOUNT>0
				BEGIN
					SET @ReturnMessage = 'DATA ARCHIVED!!!'
					SET @ReturnId = @CompanyId
					EXECUTE App_UserMaster_AuditTrail @CompanyId,@Username,'','DBSYNC',''
				END
			ELSE
				BEGIN
					SET @ReturnMessage = 'DATA ARCHIVE FAILED!!!'
					SET @ReturnId = 0
					EXECUTE App_UserMaster_AuditTrail @CompanyId,@Username,'','DBUNSYNC',''
				END
		END TRY	
		
		BEGIN CATCH
			SET @ReturnMessage = dbo.RemoveSpecialChars(ERROR_MESSAGE())
			SET @ReturnId = 0
			EXECUTE App_UserMaster_AuditTrail @CompanyId,@Username,'','DBUNSYNC',''
		END CATCH
		
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[dbo.App_Company_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Company_Manage '1708','User Type','U','0017DEBF','','2755C02F','0','Administrator','','0',
CREATE Procedure [dbo].[dbo.App_Company_Manage]
 @hdnRecordKeyId as Bigint =0,
 @GroupId as Bigint =0,
 @CompanyLevel as nvarchar(20)='',
 @CompanyName as nvarchar(100)='',
 @CompanyCode as nvarchar(10)='',
 @CompanyAddress as nvarchar(255)='',
 @GeographicalId as Bigint =0,
 @Pincode as nvarchar(20)='',
 @Telephone as nvarchar(100)='',
 @Fax as nvarchar(100)='',
 @Email as nvarchar(100)='',
 @Web as nvarchar(100)='',
 @Details1 as nvarchar(100) = '', 
 @Details2 as nvarchar(100) = '', 
 @Details3 as nvarchar(100) = '', 
 @Details4 as nvarchar(100) = '', 
 @Details5 as nvarchar(100) = '', 
 @Details6 as nvarchar(100) = '', 
 @Details7 as nvarchar(100) = '', 
 @Details8 as nvarchar(100) = '', 
 @Details9 as nvarchar(100) = '', 
 @Details10 as nvarchar(100) = '', 
 @Details11 as nvarchar(100) = '', 
 @Details12 as nvarchar(100) = '', 
 @RecordStatus as tinyint = 0,
 @UserName as nvarchar(100)='',
 @ReturnMessage as NVARCHAR(255)=''  output,
 @ReturnId as Bigint=0 output
 
As 
Begin
	SET NOCOUNT ON;

	---CHECK IF RECORD ALREADY EXIST 
	SELECT CompanyId FROM App_Company (NOLOCK) WHERE CompanyName=@CompanyName
	AND CompanyLevel=@CompanyLevel AND GroupId= @GroupId  AND (@hdnRecordKeyId=0 OR CompanyId <> @hdnRecordKeyId)

	IF @@ROWCOUNT > 0
		BEGIN
			SET @ReturnId=0
			SET @ReturnMessage = 'RECORD ALREADY EXIST'
			return
		END
	---CHECK IF RECORD ALREADY EXIST 

	BEGIN TRY  
		IF @hdnRecordKeyId = 0 ---ADD RECORD
			BEGIN
				INSERT INTO  App_Company (CompanyLevel,GroupId,CompanyName,CompanyCode
				,CompanyAddress,GeographicalId,Pincode
				,Telephone,Fax,Email,Web
				,Details1,Details2,Details3,Details4,Details5,Details6
				,Details7,Details8,Details9,Details10,Details11,Details12
				,RecordStatus,CreatedBy,ModifedBy)
				VALUES (@CompanyLevel,@GroupId,@CompanyName,@CompanyCode
				,@CompanyAddress,@GeographicalId,@Pincode
				,@Telephone,@Fax,@Email,@Web
				,@Details1,@Details2,@Details3,@Details4,@Details5,@Details6
				,@Details7,@Details8,@Details9,@Details10,@Details11,@Details12
				,@RecordStatus,@UserName,@UserName)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
				UPDATE App_Company SET [CompanyLevel] = @CompanyLevel,[GroupId] = @GroupId
				,[CompanyName] = @CompanyName,[CompanyCode] = @CompanyCode
				,[CompanyAddress] = @CompanyAddress,[GeographicalId] = @GeographicalId
				,[Pincode] = @Pincode,[Telephone] = @Telephone
				,[Fax] = @Fax,[Email] = @Email
				,[Web] = @Web,
				[Details1] = @Details1,[Details2] = @Details2
				,[Details3] = @Details3,[Details4] = @Details4
				,[Details5] = @Details5,[Details6] = @Details6
				,[Details7] = @Details7,[Details8] = @Details8
				,[Details9] = @Details9,[Details10] = @Details10
				,[Details11] = @Details11,[Details12] = @Details12
				,[RecordStatus] = @RecordStatus
				,[ModifedBy] = @UserName
				,[ModifedDate] = GetDate()
				WHERE CompanyId = @hdnRecordKeyId

				IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @hdnRecordKeyId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


End


GO
/****** Object:  StoredProcedure [dbo].[Department_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Department_Delete '8','CompanyId','App_Company','Admin','3'
CREATE  Procedure [dbo].[Department_Delete]
	@RecordKeyIds  as nvarchar(max),
	@RecordKeyColunm as nvarchar(100),
	@TableName as nvarchar(100),
	@UserName as nvarchar(100),
	@CompanyId as nvarchar(100),
	@CompanyLevel as nvarchar(100),
	@ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalCount as int,@DeletedCount as int,@Name AS NVARCHAR(100),@LookUpCode as nvarchar(50)
		Declare @NamesColunm AS nvarchar(100)
		Declare @TotalUserAuidtCount as int,@TotalEquipmentAuidtCount as int,@TotalEquipmentCount as int,@TotalGroupId as int
		
		Set @NamesColunm=''
		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				
				SET @TotalCount=@TotalCount+1

				SET @NamesColunm = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

				if @TableName='App_Users' AND @RecordKeyId='1'
					BEGIN
						SET @ReturnMessage ='RECORDS CONTAIN ADMIN USER'
						continue
					END
				ELSE
					BEGIN
					
						Select @TotalUserAuidtCount = count(UserAuditTrailId) from App_Users_AuditTrail where CompanyId = @RecordKeyId
						Select @TotalEquipmentAuidtCount = count(EquipmentMasterAuditTrailId) from EquipmentMasterAuditTrail where CompanyId = @RecordKeyId
						Select @TotalEquipmentCount = count(EquipmentMasterId) from EquipmentMaster where BranchId = @RecordKeyId
						Select @TotalGroupId = count(CompanyId) from App_Company where GroupId = @RecordKeyId
						
						IF isnull(@TotalUserAuidtCount,0) > 0 or isnull(@TotalEquipmentAuidtCount,0) > 0 or isnull(@TotalEquipmentCount,0) > 0 or isnull(@TotalGroupId,0) > 0
						   BEGIN
								SET @ReturnMessage ='CAN NOT DELETE THE RECORD, RECORD IN USE'
								PRINT(@ReturnMessage)
								return
						   END
						
						Select @Name = CompanyName from App_Company where CompanyId = @RecordKeyId

						SET @strQuery = 'DELETE FROM ' + @TableName + ' WHERE ' + @RecordKeyColunm + ' = ''' + @RecordKeyId + ''''
						print @strQuery
						EXEC sp_executesql @strQuery
						
						IF  @@RowCount > 0
							BEGIN
														
								execute App_UserMaster_AuditTrail @CompanyId,@Username,@Name,'DMD',''
								SET @ReturnMessage= 'RECORD DELETED SUCCESSFULLY'
								PRINT(@ReturnMessage)
							END
						ELSE
							BEGIN
								SET @ReturnMessage= 'RECORD DELETION FAILED'
								PRINT(@ReturnMessage)
							END
						
					END

			END TRY 
			 
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0
		
		
End



GO
/****** Object:  StoredProcedure [dbo].[Department_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--[Department_List] 163,3
CREATE Procedure [dbo].[Department_List]
 @RecordKeyId as bigint=0,
 @CompanyLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
    SELECT CompanyId,CompanyLevel,GroupId,CompanyName,
		   HeaderNote,FooterNote,AchiveMonth,
		   EmailStatus,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,
		   SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,
		   RecordStatus,dbo.GetLastModifedDetails(ModifedBy,ModifedDate)as LastModifed
		
		FROM App_Company (NoLock)

		Where (@RecordKeyId=0 Or CompanyId=@RecordKeyId)
		AND CompanyLevel=@CompanyLevel

End


GO
/****** Object:  StoredProcedure [dbo].[Department_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Department_Manage '0','162','3','DS 12','','','DS 12','DS 12','10','1','','','2018/6/4 00:00','','1','','','','0','Administrator','','0'

--Company_Manage '1708','User Type','U','0017DEBF','','2755C02F','0','Administrator','','0',
CREATE Procedure [dbo].[Department_Manage]
	 @hdnRecordKeyId as Bigint =0,
	 @CompanyId as BIGINT,
	 @CompanyLevel as tinyint = 0,
	 @GroupId as bigint,
	 @CompanyName as nvarchar(100) = '',
	 @HeaderNote as nvarchar(250)='',
	 @FooterNote as nvarchar(250)='',
	 @AchiveMonth  as tinyint = 0,
	 @EmailStatus as tinyint = 0,
	 @EmailAlertDelay as smallint = 0,
	 @AlertEmailAddress as nvarchar(1000)='',
	 @EmailTime as nvarchar(25), 
	 @SupervisorEmailAdd as nvarchar(100) = '', 
	 @SMSStatus as tinyint = 0, 
	 @SMSAlertDelay as  smallint = 0, 
	 @MobileUserName as nvarchar(1000) = '',
	 @MobileNo as nvarchar(100) = '',
	 @LoginName as nvarchar(100)='',
	 @ReturnMessage as NVARCHAR(255)=''  output,
	 @ReturnId as Bigint=0 output
As 
Begin
	SET NOCOUNT ON;

	if @SMSAlertDelay  = 0
	BEGIN
		SET @SMSAlertDelay = NULL
	END 

	If @EmailAlertDelay = 0
	BEGIN
		SET @EmailAlertDelay = NULL
	END 

	---CHECK IF RECORD ALREADY EXIST 
	SELECT CompanyId FROM App_Company (NOLOCK) WHERE CompanyName=@CompanyName
	AND CompanyLevel=@CompanyLevel AND GroupId= @GroupId  AND (@hdnRecordKeyId=0 OR CompanyId <> @hdnRecordKeyId)

	IF @@ROWCOUNT > 0
		BEGIN
			SET @ReturnId=0
			SET @ReturnMessage = 'RECORD ALREADY EXIST'
			return
		END
	---CHECK IF RECORD ALREADY EXIST 

	BEGIN TRY  
		IF @hdnRecordKeyId = 0 ---ADD RECORD
			BEGIN
			
				INSERT INTO  App_Company (CompanyLevel,GroupId,CompanyName,HeaderNote,FooterNote,AchiveMonth,EmailStatus,EmailAlertDelay,AlertEmailAddress,EmailTime,SupervisorEmailAdd,
				SMSStatus,SMSAlertDelay,MobileUserName,MobileNo,CreatedBy,ModifedBy)
				VALUES (@CompanyLevel,@GroupId,@CompanyName,@HeaderNote,@FooterNote,@AchiveMonth,@EmailStatus,@EmailAlertDelay,@AlertEmailAddress,@EmailTime,@SupervisorEmailAdd,
				@SMSStatus,@SMSAlertDelay,@MobileUserName,@MobileNo,@LoginName,@LoginName)

			   IF @@ROWCOUNT > 0
					BEGIN
						SET @ReturnId = @@IDENTITY
						SET @ReturnMessage ='RECORD ADDEDD SUCESSFULLY'
						execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DMA',''

						INSERT INTO App_Company_AlarmEvent(CompanyId,AlarmCodeLookUpId,AlarmType,CreatedBy)
						SELECT @ReturnId,AlarmCodeLookUpId,'A',@LoginName
						FROM AlarmCodeLookUp


					END

				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO ADD RECORD'
					END
           
			END --IF @hdnRecordKeyId = 0
		ELSE ---UPDATE RECORDS
			BEGIN
			
				Declare  @oldCompanyLevel as nvarchar(100),@oldGroupId as bigint,@oldCompanyName as nvarchar(100),@oldHeaderNote as nvarchar(100),@oldFooterNote as nvarchar(100)
				        ,@oldArchiveMonth as nvarchar(10),@oldEmailStatus as bigint,@oldEmailAlertDelay as smallint,@oldAlertEmailAddress as nvarchar(1000)
				        ,@oldEmailTime as nvarchar(25),@oldSupervisorEmailAddress as nvarchar(100)
				        ,@oldSMSStatus as tinyint,@oldSMSAlertDelay as smallint,@oldMobileUserName as nvarchar(1000),@oldMobileNo as nvarchar(1000)
				
				 Select @oldCompanyLevel = [CompanyLevel],@oldGroupId = [GroupId],@oldCompanyName = [CompanyName],@oldHeaderNote = HeaderNote,@oldFooterNote = FooterNote,
				        @oldArchiveMonth = AchiveMonth,@oldEmailStatus = EmailStatus,@oldEmailAlertDelay = EmailAlertDelay,@oldAlertEmailAddress = AlertEmailAddress,
				        @oldEmailTime = EmailTime,@oldSupervisorEmailAddress = SupervisorEmailAdd,
				        @oldSMSStatus = SMSStatus,@oldSMSAlertDelay = SMSAlertDelay,@oldMobileUserName = MobileUserName,@oldMobileNo = MobileNo
						from App_Company Where CompanyId = @hdnRecordKeyId		
						
			
				UPDATE App_Company 
				SET [CompanyLevel] = @CompanyLevel,[GroupId] = @GroupId,[CompanyName] = @CompanyName
				,HeaderNote = @HeaderNote,FooterNote = @FooterNote,AchiveMonth = @AchiveMonth,EmailStatus = @EmailStatus
				,EmailAlertDelay = @EmailAlertDelay,AlertEmailAddress = @AlertEmailAddress,EmailTime = @EmailTime
				,SupervisorEmailAdd = @SupervisorEmailAdd,SMSStatus = @SMSStatus,SMSAlertDelay = @SMSAlertDelay
				,MobileUserName = @MobileUserName,MobileNo = @MobileNo,[ModifedBy] = @LoginName,[ModifedDate] = GetDate()
				WHERE CompanyId = @hdnRecordKeyId

				IF @@ROWCOUNT > 0
					BEGIN
						
						SET @ReturnId = @hdnRecordKeyId
						SET @ReturnMessage ='RECORD UPDATED SUCESSFULLY'
						
						IF isnull(@oldGroupId,'') <> @GroupId
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DBU',''
							END
						
						IF isnull(@oldCompanyName,'') <> @CompanyName
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DCU',''
							END
						
						IF isnull(@oldHeaderNote,'') <> @HeaderNote
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DHN',''
							END
						
						IF isnull(@oldFooterNote,'') <> @FooterNote
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DFN',''
							END
					
					    IF isnull(@oldArchiveMonth,'') <> @AchiveMonth
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DAM',''
							END
							
						IF isnull(@oldEmailStatus,'') <> @EmailStatus
							BEGIN
								if @EmailStatus = 0
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DESE',''
									End
								Else
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DESD',''
									End
							END
								
						IF left(CONVERT(CHAR(24),Cast(@oldEmailTime as DateTime),14),5) <> left(CONVERT(CHAR(24),Cast(@EmailTime as DateTime),14),5)
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DET',''
							END
						
						 IF isnull(@oldEmailAlertDelay,'') <> @EmailAlertDelay
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DEAT',''
							END
							
					    IF isnull(@oldAlertEmailAddress,'') <> @AlertEmailAddress
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DEA',''
							END
							
						IF isnull(@oldSupervisorEmailAddress,'') <> @SupervisorEmailAdd
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DSE',''
							END
							
						if isnull(@oldSMSStatus,'') <> @SMSStatus
							BEGIN
								IF @SMSStatus = 0
									Begin
										execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DSME',''
									End
								Else
									Begin
									    execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DSMD',''
									End
							END
							
						IF isnull(@oldSMSAlertDelay,'') <> @SMSAlertDelay
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DSMA',''
							END
							
						IF isnull(@oldMobileUserName,'') <> @MobileUserName
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DMBU',''
							END
							
						IF isnull(@oldMobileNo,'') <> @MobileNo
							BEGIN
								execute App_UserMaster_AuditTrail @CompanyId,@LoginName,@CompanyName,'DMN',''
							END
					END
				ELSE
					BEGIN
						SET @ReturnId = 0
						SET @ReturnMessage ='FAILED TO UPDATE RECORD'
					END

			END --IF @hdnRecordKeyId = 0
	END TRY  
	BEGIN CATCH  
		SET @ReturnId=0
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	END CATCH; 


End


GO
/****** Object:  StoredProcedure [dbo].[Department_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Department_Search] 1,25,'','3','17,3'
CREATE Procedure [dbo].[Department_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @CompanyLevel as tinyint=0,
 @SelectedRecord as NVARCHAR(100)=''
 --@MaxLevel as tinyint=0
As 
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint,@CompanyLevel_Sp as tinyint

		Set @CompanyLevel_Sp= @CompanyLevel 
	
	
		Create TABLE #Company_Temp 
			(
				CompanyId bigint, 
				CompanyName nvarchar(500)
			)
			INSERT INTO #Company_Temp
			Exec App_Company_Populate @CompanyLevel_Sp
			
			SELECT ROW_NUMBER() OVER (ORDER BY AG.CompanyName ASC)AS RowNumber,AG.GroupId,
			AG.CompanyId,AG.CompanyName,GT.CompanyName as CompanyGroup,
			(Case When RecordStatus = 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,ModifedBy,
			dbo.GetLastModifedDate(ModifedDate) as ModifedDate
			INTO #Results FROM App_Company AG (NoLock)
			Inner Join #Company_Temp GT ON GT.CompanyId = Case When @CompanyLevel =1 Then AG.CompanyId Else AG.GroupId End 
			Where (AG.CompanyName like ('%' + @SearchText + '%') or CompanyCode like ('%' + @SearchText + '%') or GT.CompanyName like ('%' + @SearchText + '%') or ModifedBy like ('%' + @SearchText + '%')) 
			And (@CompanyLevel=0 or CompanyLevel=@CompanyLevel)
			and (@SelectedRecord = '') OR AG.CompanyId in (Select * from dbo.CSVToTable(@SelectedRecord))
			
			Set @RecordCount = @@ROWCOUNT

			Drop Table #Company_Temp
		

           
    SELECT CompanyId,@RecordCount as RecordCount,CompanyName,CompanyGroup,RecordStatus,ModifedBy,ModifedDate FROM #Results
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	
     
    DROP TABLE #Results

End

GO
/****** Object:  StoredProcedure [dbo].[DoorAccessUsers_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- DoorAccessUsers_Update '54','EQUIPMENT -TCT','B','PARTH,','1,','','','1','192.168.0.203',0,'test','admin','',0
CREATE PROCEDURE [dbo].[DoorAccessUsers_Update] 
	@EquipmentMasterId AS bigint,
	@EquipmentName as nvarchar(50)='',
	@DoorAccessType as nvarchar(5)='',
	@EquipmentNewAccessUserName as nvarchar(1000)='',
	@EquipmentNewAccessUserCode as nvarchar(1000)='',
	@EquipmentOldAccessUserName as nvarchar(1000)='',
	@EquipmentOldAccessUserCode as nvarchar(1000)='',
	@BiometricBannerText as nvarchar(50)='',
	@BiometricIPAddress as nvarchar(50)='',
	@DoorAccessUserNameDisplay as NVARCHAR(200)='',
	@LoginComments as nvarchar(255)='',
	@Username as nvarchar(100)='',
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
AS
SET NOCOUNT ON;
BEGIN
	begin try
		
		DECLARE @EquipmentAccessUserNameOLD AS NVARCHAR(200),@EquipmentAccessUserCodeOLD AS NVARCHAR(200),@BiometricBannerTextOLD AS NVARCHAR(200),
		@BiometricIPAddressOLD AS NVARCHAR(200),@DoorAccessUserNameDisplayOLD AS NVARCHAR(200),@CompnayId as integer

		SELECT @EquipmentAccessUserNameOLD=EquipmentAccessUserName,@EquipmentAccessUserCodeOLD=EquipmentAccessUserCode,
		@BiometricBannerTextOLD=BiometricBannerText,@BiometricIPAddressOLD=BiometricIPAddress,@DoorAccessUserNameDisplayOLD=CAST(DoorAccessUserNameDisplay AS nvarchar(200))
		,@CompnayId = BranchId
		FROM EquipmentMaster(NOLOCK) Where EquipmentMasterId =@EquipmentMasterId		 

		Update EquipmentMaster Set  EquipmentAccessUserName=@EquipmentNewAccessUserName,EquipmentAccessUserCode=@EquipmentNewAccessUserCode,
		BiometricBannerText=@BiometricBannerText,BiometricIPAddress=@BiometricIPAddress,DoorAccessUserNameDisplay=@DoorAccessUserNameDisplay,
		ModifedBy=@Username,LastModifedDate=GETDATE()	
		Where EquipmentMasterId =@EquipmentMasterId
				
		IF @@rowcount > 0 
			
			BEGIN 			
			
				IF @BiometricBannerText <> isnull(@BiometricBannerTextOLD,'')
				BEGIN
					SET @BiometricBannerTextOLD = @BiometricBannerTextOLD
					SET @BiometricBannerText = @BiometricBannerText
					Execute EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,'EQUPBT',@BiometricBannerTextOLD,@BiometricBannerText,@LoginComments,@Username,''
				END

				IF @BiometricIPAddress <> isnull(@BiometricIPAddressOLD,'')
				BEGIN
					SET @BiometricIPAddressOLD = @BiometricIPAddressOLD
					SET @BiometricIPAddress = @BiometricIPAddress
					Execute EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,'EQUPBIP',@BiometricIPAddressOLD,@BiometricIPAddress,@LoginComments,@Username,''
				END

				IF @DoorAccessUserNameDisplay <> isnull(@DoorAccessUserNameDisplayOLD,'')
				BEGIN
					SET @DoorAccessUserNameDisplayOLD = (CASE WHEN @DoorAccessUserNameDisplayOLD = '0' THEN 'ACTIVE' WHEN @DoorAccessUserNameDisplayOLD = '1' THEN 'NOT ACTIVE' ELSE '' END)
					SET @DoorAccessUserNameDisplay = (CASE WHEN @DoorAccessUserNameDisplay = '0' THEN 'ACTIVE' WHEN @DoorAccessUserNameDisplay = '1' THEN 'NOT ACTIVE' ELSE '' END)
					Execute EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,'EQUPDAU',@DoorAccessUserNameDisplayOLD,@DoorAccessUserNameDisplay,@LoginComments,@Username,''
				END

				IF (@EquipmentAccessUserNameOLD <> @EquipmentNewAccessUserName)
					Execute EquipmentMaster_DoorAccess_AuditTrail @CompnayId,@EquipmentMasterId,@EquipmentName,'EQUPDAUN',@EquipmentAccessUserNameOLD,@EquipmentNewAccessUserName,@EquipmentAccessUserCodeOLD,@EquipmentNewAccessUserCode,@LoginComments,@Username,''

				IF  (@EquipmentAccessUserCodeOLD <> @EquipmentOldAccessUserCode)
					Execute EquipmentMaster_DoorAccess_AuditTrail @CompnayId,@EquipmentMasterId,@EquipmentName,'EQUPDAUC',@EquipmentAccessUserNameOLD,@EquipmentNewAccessUserName,@EquipmentAccessUserCodeOLD,@EquipmentNewAccessUserCode,@LoginComments,@Username,''
				
				set @ReturnMessage = 'ACCESS USERS UPDATED SUCESSFULLY'
				
				set @ReturnId = @EquipmentMasterId					
			END
	end try
	begin catch
		set @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
		set @ReturnId =0
	end catch
		
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[EmailLog_ListData]
	
AS
	Set nocount on
	Begin

	Select * from EmailLog where EmailStatus=0 and EquipmentMasterId is NOT NULL
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ListData_TestMail]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[EmailLog_ListData_TestMail]
	
AS
	Set nocount on
	Begin

	Select * from EmailLog where EquipmentMasterId is NULL and EmailStatus=0
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[EmailLog_Manage]
	
AS
	Set nocount on
	Begin

	Declare @SMTPEmail as nvarchar(100),@EmailAlertDelay as bigint

	Select @SMTPEmail=SMTPEmail from App_ApplicationSetup

	--Select @EmailAlertDelay = EmailAlertDelay
	--FROM EquipmentMaster AS DM INNER JOIN
	--EquipmentMasterAlarmAuditTrail AS DMAL ON DM.EquipmentMasterId = DMAL.EquipmentMasterId INNER JOIN
	--App_Company AS AC ON DM.BranchId = AC.CompanyId 

	INSERT INTO EmailLog ([EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailSubject])
	(	
		SELECT DM.EquipmentMasterId,GetDate() as EmailDateTime,@SMTPEmail,MN.EmailAddress
		,('<tr><td width=''20%''>Department Name</td><td width=''80%''>: ' + upper(AC.CompanyName) +  '</td></tr><tr><td width=''20%''>Equipment Name</td><td width=''80%''>: ' + upper(DM.EquipmentName) +  '</td></tr><tr><td width=''20%''>Alarm Log DateTime</td><td width=''80%''>: ' + upper(convert(varchar(17), getdate(), 113)) + '</td></tr><tr><td width=''20%''>Alarm Event</td><td width=''80%''>: ' + upper(AlarmEvent) + upper(AlarmInfo) +'</td></tr>') as EmailMessage
		,0 as EmailStatus
		,(upper(DM.EquipmentName) +  ' : ' + upper(AlarmEvent)) as EmailSubject
		
		FROM EquipmentMaster AS DM INNER JOIN
		EquipmentMasterAlarmAuditTrail AS DMAL ON DM.EquipmentMasterId = DMAL.EquipmentMasterId 
		INNER JOIN
		App_Company AS AC ON DM.BranchId = AC.CompanyId
		Outer Apply
		(
			Select [SID] as EmailAddress from dbo.CSVToTable(AC.AlertEmailAddress )
			Where isnull([SID],'') <> ''
		) MN
		Where DMAL.EmailStatus=0 and isnull(MN.EmailAddress,'') <> '' 
		and Isnull(AckUserId,'') =''
		and Datediff(n,AlarmLogDateTime,GetDate()) > AC.EmailAlertDelay
	)
	if @@rowcount>0
	Begin
		Update EquipmentMasterAlarmAuditTrail Set EmailStatus=1 
		Where EmailStatus=0 
		and Datediff(n,AlarmLogDateTime,GetDate()) > 
		(Select EmailAlertDelay From App_Company AC Inner Join EquipmentMaster EM ON AC.CompanyId = EM.BranchId
		Where EquipmentMasterAlarmAuditTrail.EquipmentMasterId= EM.EquipmentMasterId)
		
	End
	
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EmailLog_ManageTestMail]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EmailLog_ManageTestMail] '0','2018-May-24 14:28:54','noor@dreamosoftindia.com','noor@dreamsoftindia.com','Test message from ICDAS 3.0 QC','0','Test mail generated by admin'

CREATE PROCEDURE [dbo].[EmailLog_ManageTestMail]
	@EquipmentMasterId as bigint=0,
	@EmailDateTime  as nvarchar(25)='',
	@EmailFromAddress as nvarchar(100)='',
	@EmailToAddress as nvarchar(100)='',
	@EmailMessage as ntext='',
	@EmailStatus as tinyint,
	@EmailSubject as nvarchar(100),
	@LoginName as nvarchar(100)=''
	
AS
	Set nocount on
	Begin

	begin try

	if @EquipmentMasterId=0
	set @EquipmentMasterId=null

	INSERT INTO EmailLog ([EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailSubject],CreatedBy,ModifedBy)
	values(@EquipmentMasterId,@EmailDateTime,@EmailFromAddress,@EmailToAddress,@EmailMessage,@EmailStatus,@EmailSubject,@LoginName,@LoginName)	
	end try	

	begin catch
	end catch
	End
Set nocount off;



--select * from EmailLog
GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec EmailLog_Rpt 3,'2018-05-24 12:22:37.000', '2018-08-25 12:22:37.000', '', '', '', '', -1, 1,0
CREATE PROCEDURE [dbo].[EmailLog_Rpt]  
 @BranchId AS Bigint=0,
 @ReportFromDate AS DATETIME='',  
 @ReportToDate AS DATETIME='',     
 @EquipmentName AS varchar(4000)='',  
 @FilterParameter AS varchar(100)='',  
 @EmailSubject AS varchar(100)='',  
 @ToAddress AS varchar(100)='',  
 @EmailStatus AS int=-1,
 @IsSystemEmail As tinyint,  
 @OrderBy as tinyint=0  
AS  
SET NOCOUNT ON  
Begin  
   IF @IsSystemEmail = 0
	  BEGIN
		  SELECT Row_Number() Over(Order by (Case @OrderBy When 0 Then EmailDateTime Else EMAT.EmailLogId End),EM.EquipmentName) As [Sr No],
				 Convert(varchar, EMAT.EmailDateTime, 105) As [Date], substring(convert(varchar(8), EMAT.EmailDateTime, 108), 0, 6) As [Time],
				 EM.EquipmentName, EMAT.EmailFromAddress As [Email From], EMAT.EmailToAddress As [Email To],
				 EmailSubject As [Subject], EMAT.EmailMessage As [Email Message], 
				 (Case EMAT.EmailStatus When 0 then 'PENDING' When 1 then 'SENT' When 2 then 'FAILED' End) As[Status]
		  FROM  EmailLog AS EMAT left JOIN  
		  EquipmentMaster AS EM ON EMAT.EquipmentMasterId = EM.EquipmentMasterId  
		  WHERE (EMAT.EmailDateTime BETWEEN @ReportFromDate and @ReportToDate)  
		  And (@BranchId=0 or EM.BranchId=@BranchId)  
		  And (@EmailStatus=-1 or EmailStatus=@EmailStatus)  
		  And ((@EquipmentName = '' and EMAT.EquipmentMasterId is not null ) or ( @EquipmentName = '' and EMAT.EquipmentMasterId is null ) or (EM.EquipmentMasterId in(select * from CSVTOTable(@EquipmentName)) and EMAT.EquipmentMasterId is not null ))  
		  And (@FilterParameter='' or EmailMessage like '%' + @FilterParameter + '%')  
		  And (@EmailSubject='' or EmailSubject like '%' + @EmailSubject + '%')  
		  And (@ToAddress='' or EmailToAddress like '%' + @ToAddress + '%')  
		  order by (Case @OrderBy When 0 Then EmailDateTime Else EMAT.EmailLogId End),EM.EquipmentName  
	  END
  ELSE
	  BEGIN
		  SELECT Row_Number() Over(Order by (Case @OrderBy When 0 Then EmailDateTime Else EMAT.EmailLogId End),EM.EquipmentName) As [Sr No],
				 Convert(varchar, EMAT.EmailDateTime, 105) As [Date], substring(convert(varchar(8), EMAT.EmailDateTime, 108), 0, 6) As [Time],
				 EMAT.EmailFromAddress As [Email From], EMAT.EmailToAddress As [Email To],
				 EmailSubject As [Subject],(Case EMAT.EmailStatus When 0 then 'PENDING' When 1 then 'SENT' When 2 then 'FAILED' End) As[Status]
		  FROM  EmailLog AS EMAT left JOIN  
		  EquipmentMaster AS EM ON EMAT.EquipmentMasterId = EM.EquipmentMasterId  
		  WHERE (EMAT.EmailDateTime BETWEEN @ReportFromDate and @ReportToDate)  
		  And (@EmailStatus=-1 or EmailStatus=@EmailStatus)  
		  And EMAT.EquipmentMasterId is null
		  And (@FilterParameter='' or EmailMessage like '%' + @FilterParameter + '%')  
		  And (@EmailSubject='' or EmailSubject like '%' + @EmailSubject + '%')  
		  And (@ToAddress='' or EmailToAddress like '%' + @ToAddress + '%')  
		  order by (Case @OrderBy When 0 Then EmailDateTime Else EMAT.EmailLogId End),EM.EquipmentName  
	  END
	  
End  
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[EmailLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EmailLog_Sync] 3
CREATE PROCEDURE [dbo].[EmailLog_Sync]
	@CompanyId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record

--SET  identity_insert ICDAS_3_0_Archive.dbo.EmailLog ON

		insert into	ICDAS_3_0_Archive.dbo.EmailLog
			([EmailLogId],[EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailErrorDesc],[EmailSubject],[CreateDate] ,[CreatedBy] ,[ModifedBy] ,[ModifedDate])
		select
			SourceDBTable.[EmailLogId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[EmailDateTime] ,SourceDBTable.[EmailFromAddress]
			,SourceDBTable.[EmailToAddress],SourceDBTable.[EmailMessage],SourceDBTable.[EmailStatus],SourceDBTable.[EmailErrorDesc],SourceDBTable.[EmailSubject]
			,SourceDBTable.[CreateDate] ,SourceDBTable.[CreatedBy] ,SourceDBTable.[ModifedBy] ,SourceDBTable.[ModifedDate]
		from EmailLog (NOLOCK)  SourceDBTable inner join EquipmentMaster (NOLOCK)  EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@CompanyId AND EmailDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EmailLog DestinationDBTable
						 where DestinationDBTable.EmailLogId = SourceDBTable.EmailLogId)
						 
--SET  identity_insert ICDAS_3_0_Archive.dbo.EmailLog OFF
			
--Update Record			

	update  ICDAS_3_0_Archive.dbo.EmailLog 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[EmailDateTime]=SourceDBTable.[EmailDateTime],[EmailFromAddress]=SourceDBTable.[EmailFromAddress]
		   ,[EmailToAddress]=SourceDBTable.[EmailToAddress],[EmailMessage]=SourceDBTable.[EmailMessage],[EmailStatus]=SourceDBTable.[EmailStatus],[EmailErrorDesc]=SourceDBTable.[EmailErrorDesc],[EmailSubject]=SourceDBTable.[EmailSubject]
	from	ICDAS_3_0_Archive.dbo.EmailLog DestinationDBTable,
			(
				select	max(TableName) as TableName,[EmailLogId],[EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailErrorDesc],[EmailSubject],[BranchId]
				from
					(
						select	'SourceTableName' as TableName,[EmailLogId],SourceTableName.[EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailErrorDesc],[EmailSubject],[BranchId]
						from EmailLog SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName, [EmailLogId],DestinationTableName.[EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailErrorDesc],[EmailSubject],[BranchId]
						from ICDAS_3_0_Archive.dbo.EmailLog DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EmailLogId],[EquipmentMasterId],[EmailDateTime],[EmailFromAddress],[EmailToAddress],[EmailMessage],[EmailStatus],[EmailErrorDesc],[EmailSubject],[BranchId]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.EmailLogId = SourceDBTable.EmailLogId and SourceDBTable.BranchId=@CompanyId
	
--Delete Record	
		
		Delete From EmailLog Where EmailDateTime<=@LogDateTime AND EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@CompanyId )

			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentAlarmConfig_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[EquipmentAlarmConfig_Delete] 
	@EquipmentMasterId as bigint,	
	@AlarmType as nvarchar(5)='',
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output

AS
SET NOCOUNT ON;
BEGIN 
		
	DELETE FROM EquipmentAlarmConfig WHERE AlarmType=@AlarmType and EquipmentMasterId=@EquipmentMasterId
    IF @@rowcount > 0 
		BEGIN
					
			SET @ReturnMessage = 'Record Deleted Successfully !!' 
	        SET @ReturnId = @@identity
	        
		END
    ELSE
		BEGIN 
			SET @ReturnMessage = 'Record Deletion Failed !!' 
	        SET @ReturnId = 0
		END		    
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentAlarmConfig_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--UserGroup_List 1
CREATE  Procedure [dbo].[EquipmentAlarmConfig_List]
 @RecordKeyId as bigint=0
As 
Begin
	SET NOCOUNT ON;
           
    SELECT *
	FROM EquipmentAlarmConfig (NoLock)
	Where (@RecordKeyId=0 Or EquipmentMasterId=@RecordKeyId)

End


GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Insert]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentComponentRunningHours_Insert] 24
CREATE PROCEDURE [dbo].[EquipmentComponentRunningHours_Insert]
	@EquipmentMasterId as bigint,
	@EquipmentTypeGroup as nvarchar(10)
AS
	Set nocount on
	Begin

	INSERT INTO [EquipmentComponentRunningHours]([EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value])
    (Select @EquipmentMasterId,ComponentRunningHoursId,0,'' from ComponentRunningHours (NOLOCK) Where (',' + EquipmentTypeGroup + ',') like '%,' +  @EquipmentTypeGroup  + ',%')
	
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Select * from EquipmentComponentRunningHours 6
--EquipmentComponentRunningHours_ListData 6 
CREATE  PROCEDURE [dbo].[EquipmentComponentRunningHours_ListData]
	@EquipmentMasterId as Bigint=0
AS
Set nocount on;
	Begin

	SELECT EquipmentComponentRunningHoursId,EquipmentMasterId,EQR.ComponentRunningHoursId,Name,
	CASE WHEN SetRunHours is null THEN 32000 ELSE SetRunHours END SetRunHours,RunHours,Value
	 FROM EquipmentComponentRunningHours (NOLOCK)  EQR
	INNER JOIN ComponentRunningHours (NOLOCK)  CRH ON CRH.ComponentRunningHoursId=EQR.ComponentRunningHoursId
	Where (EquipmentMasterId = @EquipmentMasterId)

	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentComponentRunningHours_Sync] 3
CREATE PROCEDURE [dbo].[EquipmentComponentRunningHours_Sync]
	@BranchId as bigint = 0
AS
	Set nocount on
	Begin
--Insert Record


SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours ON
		insert into	ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours
			([EquipmentComponentRunningHoursId],[EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value],[SetRunHours])
		select
			SourceDBTable.[EquipmentComponentRunningHoursId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[ComponentRunningHoursId] ,SourceDBTable.[RunHours],SourceDBTable.[Value],SourceDBTable.[SetRunHours] 
		from EquipmentComponentRunningHours (NOLOCK)  SourceDBTable inner join EquipmentMaster EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours (NOLOCK) DestinationDBTable
						 where DestinationDBTable.EquipmentComponentRunningHoursId = SourceDBTable.EquipmentComponentRunningHoursId)
SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours OFF
			
--Update Record			

	update  ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[ComponentRunningHoursId]=SourceDBTable.[ComponentRunningHoursId],[RunHours]=SourceDBTable.[RunHours],[Value]=SourceDBTable.[Value],[SetRunHours] =SourceDBTable.[SetRunHours]
	from	ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours (NOLOCK) DestinationDBTable,
			(
				select	max(TableName) as TableName,[EquipmentComponentRunningHoursId],[EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value],[BranchId],[SetRunHours]
				from
					(
						select	'SourceTableName' as TableName,[EquipmentComponentRunningHoursId],SourceTableName.[EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value],[BranchId],[SetRunHours]
						from EquipmentComponentRunningHours (NOLOCK) SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName, [EquipmentComponentRunningHoursId],DestinationTableName.[EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value],[BranchId],[SetRunHours]
						from ICDAS_3_0_Archive.dbo.EquipmentComponentRunningHours (NOLOCK) DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EquipmentComponentRunningHoursId],[EquipmentMasterId],[ComponentRunningHoursId],[RunHours],[Value],[BranchId],[SetRunHours]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.EquipmentComponentRunningHoursId = SourceDBTable.EquipmentComponentRunningHoursId and SourceDBTable.BranchId=@BranchId
			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentComponentRunningHours_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--SELECT * FROM EquipmentComponentRunningHours where EquipmentMasterId=14
--SELECT top(25) * FROM EquipmentMasterAuditTrail order by EquipmentMasterAuditTrailId desc
--EquipmentComponentRunningHours_Update '31','14','1','67000','testtt','','TEST BY POONAM','admin','','0'
CREATE Procedure [dbo].[EquipmentComponentRunningHours_Update]
@EquipmentComponentRunningHoursId as bigint=0,
@EquipmentMasterId AS bigint =0,
@ComponentRunningHoursId AS bigint=0,
@SetRunHours AS bigint=0,
@EquipmentName as nvarchar(50)='',
@Name as nvarchar(100)='',
@LoginComments as nvarchar(255)='',
@UserName as nvarchar(100)='',
@ReturnMessage AS NVARCHAR(1000)='' OUTPUT,
@ReturnId AS BIGINT=0 OUTPUT
As 
Begin
	SET NOCOUNT ON;	
	begin	
		DECLARE @EquipmentSetRunHoursOLD AS bigint, @ComponentName AS NVARCHAR(200)
			
		SELECT @EquipmentSetRunHoursOLD=SetRunHours
		FROM EquipmentComponentRunningHours(NOLOCK) 
		Where EquipmentComponentRunningHoursId =@EquipmentComponentRunningHoursId and EquipmentMasterId=@EquipmentMasterId	

		Print(@EquipmentSetRunHoursOLD)

		SET @ComponentName = Upper(@Name) + ' UPDATED SUCCESSFULLY'

		print (@Name)

		UPDATE EquipmentComponentRunningHours SET SetRunHours=@SetRunHours
		WHERE EquipmentComponentRunningHoursId=@EquipmentComponentRunningHoursId and EquipmentMasterId=@EquipmentMasterId and ComponentRunningHoursId=@ComponentRunningHoursId
		
		IF @@ROWCOUNT>0		
		BEGIN
			
			SET @ReturnMessage='COMPONENT RUNNING HOURS UPDATED SUCCESSFULLY'
			SET @ReturnId = @EquipmentComponentRunningHoursId

			IF (@EquipmentSetRunHoursOLD <> @SetRunHours)
			BEGIN
				Execute EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName, 'EQPCRNH' ,@EquipmentSetRunHoursOLD,@SetRunHours,@LoginComments,@Username,''
			END

		END
		ELSE		
			SET @ReturnMessage='COMPONENT RUNNING HOURS UPDATION FAILED!!'
			SET @ReturnId = 0
	end	
End

--select *from EquipmentMasterAlarmAuditTrail
GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_Insert]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentIOStatus_Insert] 1
CREATE PROCEDURE [dbo].[EquipmentIOStatus_Insert]
	@EquipmentMasterId as bigint,
	@EquipmentTypeGroup as nvarchar(10) = ''
AS
	Set nocount on
	Begin
		
		Begin try

			INSERT INTO [EquipmentIOStatus]([EquipmentMasterId],[IOStatusId],[IOValue])
			(Select @EquipmentMasterId,IOStatusId,'' from IOStatus (NOLOCK) Where (',' + EquipmentTypeGroup + ',') like '%,' +  @EquipmentTypeGroup  + ',%')
			
		End try
		
		Begin catch
			Declare @ReturnMessage as varchar(255)
			set @ReturnMessage = dbo.RemoveSpecialChars(ERROR_MESSAGE());
		End catch
	
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentIOStatus_ListData] I,'DC'
CREATE PROCEDURE [dbo].[EquipmentIOStatus_ListData]
	@IOType as nvarchar(5),
	@EquipmentTypeGroup as nvarchar(5),
	@EquipmentMasterId as bigint
AS
	Set nocount on
	Begin

	Select EIOS.*,IOS.IOName from EquipmentIOStatus (NOLOCK) as EIOS
	inner join IOStatus (NOLOCK) as IOS on EIOS.IOStatusId=IOS.IOStatusId
	
	where  IOS.IOType =@IOType and  IOS.EquipmentTypeGroup like '%' + @EquipmentTypeGroup + '%'
	and EIOS.EquipmentMasterId=@EquipmentMasterId
	order by IOS.IOSrNo 
	
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentIOStatus_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentIOStatus_Sync] 3
CREATE PROCEDURE [dbo].[EquipmentIOStatus_Sync]
	@BranchId as bigint = 0
AS
	Set nocount on
	Begin
--Insert Record


SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentIOStatus ON
		insert into	ICDAS_3_0_Archive.dbo.EquipmentIOStatus
			([EquipmentIOStatusId],[EquipmentMasterId],[IOStatusId],[IOValue],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate])
		select
			SourceDBTable.[EquipmentIOStatusId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[IOStatusId] ,SourceDBTable.[IOValue]
			,SourceDBTable.[CreateDate] ,SourceDBTable.[CreatedBy],SourceDBTable.[ModifedBy] ,SourceDBTable.[ModifedDate]
		from EquipmentIOStatus (NOLOCK) SourceDBTable inner join EquipmentMaster (NOLOCK) EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentIOStatus DestinationDBTable
						 where DestinationDBTable.EquipmentIOStatusId = SourceDBTable.EquipmentIOStatusId)
SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentIOStatus OFF
			
--Update Record			

	update  ICDAS_3_0_Archive.dbo.EquipmentIOStatus 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[IOStatusId]=SourceDBTable.[IOStatusId],[IOValue]=SourceDBTable.[IOValue],[CreateDate]=SourceDBTable.[CreateDate] ,[CreatedBy]=SourceDBTable.[CreatedBy],[ModifedBy]=SourceDBTable.[ModifedBy] ,[ModifedDate]=SourceDBTable.[ModifedDate]
	from	ICDAS_3_0_Archive.dbo.EquipmentIOStatus DestinationDBTable,
			(
				select	max(TableName) as TableName,[EquipmentIOStatusId],[EquipmentMasterId],[IOStatusId],[IOValue],[BranchId],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
				from
					(
						select	'SourceTableName' as TableName,[EquipmentIOStatusId],SourceTableName.[EquipmentMasterId],[IOStatusId],[IOValue],[BranchId],SourceTableName.[CreateDate] ,SourceTableName.[CreatedBy],SourceTableName.[ModifedBy] ,SourceTableName.[ModifedDate]
						from EquipmentIOStatus SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName, [EquipmentIOStatusId],DestinationTableName.[EquipmentMasterId],[IOStatusId],[IOValue],[BranchId],DestinationTableName.[CreateDate] ,DestinationTableName.[CreatedBy],DestinationTableName.[ModifedBy] ,DestinationTableName.[ModifedDate]
						from ICDAS_3_0_Archive.dbo.EquipmentIOStatus (NOLOCK) DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EquipmentIOStatusId],[EquipmentMasterId],[IOStatusId],[IOValue],[BranchId],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.EquipmentIOStatusId = SourceDBTable.EquipmentIOStatusId and SourceDBTable.BranchId=@BranchId
			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_CheckActiveEquipment]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMaster_CheckActiveEquipment] 1, 0, 1
CREATE PROCEDURE [dbo].[EquipmentMaster_CheckActiveEquipment] 
	@hdnBranchId as bigint = 0
	
AS
	Set nocount on
	Begin
		SELECT Count(EquipmentMasterId) as ActiveEquipment
		FROM EquipmentMaster (NOLOCK) as EM
		where EquipmentStatus=0 and BranchId=@hdnBranchId
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMaster_Delete] 1,25,''
CREATE Procedure [dbo].[EquipmentMaster_Delete]
 @RecordKeyIds  as nvarchar(max),
 @ReturnMessage as NVARCHAR(500)=''  output
As 
SET nocount on;
BEGIN

		DECLARE @RecordKeyId AS nvarchar(20),@strQuery as Nvarchar(max),@TotalCount as int,@DeletedCount as int
	

		Set @DeletedCount=0
		Set @TotalCount=0
		SET @ReturnMessage= ''

		WHILE LEN(@RecordKeyIds) > 0
		BEGIN
			BEGIN TRY  
				SET @TotalCount=@TotalCount+1

				SET @RecordKeyId = LEFT(@RecordKeyIds, ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds) - 1, -1),LEN(@RecordKeyIds)))
				SET @RecordKeyIds = SUBSTRING(@RecordKeyIds,ISNULL(NULLIF(CHARINDEX(',', @RecordKeyIds), 0),LEN(@RecordKeyIds)) + 1, LEN(@RecordKeyIds))

					SET @strQuery = 'DELETE FROM EquipmentMaster WHERE EquipmentMasterId = ''' + @RecordKeyId + ''''

				EXEC sp_executesql @strQuery

				IF  @@RowCount > 0
					SET @DeletedCount=@DeletedCount+1

			END TRY  
			BEGIN CATCH  
				IF @ReturnMessage = ''
					SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
			END CATCH; 

		END --WHILE LEN(@RecordKeyIds) > 0

		IF @ReturnMessage <> '' 
			SET @ReturnMessage= 'Record Deleted Successfully'
		ELSE
			SET @ReturnMessage= 'Record Deletion Failed'
		
		print(@ReturnMessage)
	
End
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_DemoApp_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[EquipmentMaster_DemoApp_Update]
@hdnRecordKeyId AS BIGINT=0,	
@TempratureSetValue as nvarchar(10) = '',
@comments as nvarchar(100)='',
@username as varchar(100)='',
@ReturnMessage AS VARCHAR(100)=''  OUTPUT,
@ReturnId AS BIGINT =0 OUTPUT

as
SET NOCOUNT ON;
BEGIN
	begin try
	 
		declare @EquipmentName as nvarchar(100),@TempratureSetValueOLD as nvarchar(10),@EquipmentTypeGroup as nvarchar(20)

		Select @EquipmentTypeGroup = EquipmentTypeGroup from EquipmentMaster EM inner join EquipmentType ET on EM.EquipmentType = ET.EquipmentType 
		Where EM.EquipmentMasterId = @hdnRecordKeyId

		select 
		@EquipmentName = EquipmentName,
		@TempratureSetValueOLD=TempratureSetValue
		from EquipmentMaster (NoLock)
		where EquipmentMasterId=@hdnRecordKeyId	
		
		begin try
			update EquipmentMaster 
			set TempratureSetValue=@TempratureSetValue
			where EquipmentMasterId=@hdnRecordKeyId

			if @@ROWCOUNT>0
			Begin 
				
				set @ReturnMessage='PARAMETER DETAILS UPDATED SUCCESSFULLY'
				set @ReturnId=@hdnRecordKeyId

				if @TempratureSetValueOLD<>@TempratureSetValue
				Begin		
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN	
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1SetValue',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
					ELSE IF (@EquipmentTypeGroup = 'TC')
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TemperatureSetValue1',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureSetValue',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
				End
			end
		end try
		begin catch
			set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
			print @ReturnMessage
		end catch
	
	end try
	begin catch
		set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
		print @ReturnMessage
	end catch
	
end

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Department_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMaster_Department_Populate] 3
CREATE  Procedure [dbo].[EquipmentMaster_Department_Populate]
 @BranchId AS nvarchar(100)=''
As 
Begin
	SET NOCOUNT ON

	--CHAGES DONE BY PARTH ON 10-09-2018 AS TOLD BY JAIKANT
	Declare @AccessibleCompanyIds as nvarchar(100)
	--SELECT @AccessibleCompanyIds=AccessibleCompanyId FROM App_Users (NOLOCK) WHERE CompanyId=@BranchId
	

	Select  EM.EquipmentMasterId,EM.EquipmentName as [Equipment Name] From --(EM.EquipmentName + '/' + AP.CompanyName)as [Equipment Name] From 
	EquipmentMaster(NoLock) EM 
	WHERE EM.BranchId In (Select [Sid] From dbo.CSVToTable(@BranchId))
	order by EM.EquipmentName
End


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_DoorAccess_AuditTrail]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec EquipmentMasterAuditTrail_Manage 1002,'Equipment Date Time Synchronize Request Sent','',''
CREATE PROCEDURE [dbo].[EquipmentMaster_DoorAccess_AuditTrail]
@CompanyId as bigint = 0,
@EquipmentMasterId as bigint=0,
@EquipmentName as nvarchar(50),
@Parameter as nvarchar(150)='',
@EquipmentOldAccessUserName as nvarchar(max),
@EquipmentNewAccessUserName nvarchar(max), 
@EquipmentOldAccessUserCode nvarchar(max),
@EquipmentNewAccessUserCode nvarchar(max),
@Comments as  nvarchar(250)='',
@Username as nvarchar(100)='',
@ReturnMessage as NVARCHAR(255)=''  output
AS
Begin

	begin try

			Declare @AddParameter as nvarchar(100),@RemovedParameter as nvarchar(100)

			Select @AddParameter=Comments From EquipmentMasterAuditTrail_LookUp Where Code='DAA'

			Select @RemovedParameter=Comments From EquipmentMasterAuditTrail_LookUp Where Code='DAR'

		  --RECORDS ADDED
			insert into EquipmentMasterAuditTrail (CompanyId,EquipmentMasterId,EquipmentName,AuditTrailDate, Parameter,ParameterOldValue,ParameterNewValue,Comments,UserName)
			Select @CompanyId,@EquipmentMasterId,@EquipmentName,GetDate(),@AddParameter,'',[SID],@Comments,@Username
			From dbo.CSVToTable(@EquipmentNewAccessUserName) T2 
			Where [SID] Not in (Select [SID] From dbo.CSVToTable(@EquipmentOldAccessUserName))

			--RECORDS REMOVED
			insert into EquipmentMasterAuditTrail (CompanyId,EquipmentMasterId,EquipmentName,AuditTrailDate, Parameter,ParameterOldValue,ParameterNewValue,Comments,UserName)
			Select @CompanyId,@EquipmentMasterId,@EquipmentName,GetDate(),@RemovedParameter,'',[SID],@Comments,@Username
			From dbo.CSVToTable(@EquipmentOldAccessUserName) T2 
			Where [SID] Not in (Select [SID] From dbo.CSVToTable(@EquipmentNewAccessUserName))

			IF @EquipmentOldAccessUserCode = '' AND @EquipmentNewAccessUserCode=''
				RETURN

			IF @EquipmentOldAccessUserCode = @EquipmentNewAccessUserCode
				RETURN

			---IF USER NAME STRING IS NOT CHNAGED 
			if @EquipmentOldAccessUserName = @EquipmentNewAccessUserName 
			Begin
			
					Select @AddParameter=Comments From EquipmentMasterAuditTrail_LookUp (NOLOCK) Where Code='DAU'

					insert into EquipmentMasterAuditTrail (CompanyId,EquipmentMasterId,EquipmentName,AuditTrailDate, Parameter,ParameterOldValue,ParameterNewValue,Comments,UserName)
					Select @CompanyId,@EquipmentMasterId,@EquipmentName,GetDate(),@AddParameter,(TN.sID + ' User Code ' + TC.sID),(TN.sID + ' User Code ' + TCN.sID),@Comments,@Username From 
						(
							Select ROW_NUMBER() OVER(ORDER BY (SELECT 100)) as TNR, Tn.[sID] From dbo.CSVToTable(@EquipmentOldAccessUserName) TN
						) TN
					Outer Apply
					(
						Select * From 
						(
							Select  ROW_NUMBER() OVER(ORDER BY (SELECT 100)) as TCR, TC.[sID] From dbo.CSVToTable(@EquipmentOldAccessUserCode) TC
						)TC1
						Where TC1.TCR= TN.TNR 
					)TC
					Outer Apply
					(
						Select * From 
						(
							Select  ROW_NUMBER() OVER(ORDER BY (SELECT 100)) as TCR, TC.[sID] From dbo.CSVToTable(@EquipmentNewAccessUserCode) TC
						)TC2
						Where TC2.TCR= TN.TNR 
					)TCN
					Where TC.sID <> TCN.sID
		
			END	--if @EquipmentOldAccessUserName = @EquipmentNewAccessUserName			
	end try
	begin catch
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	end catch;	
	
	
End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_GetEquipmentType]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec EquipmentMaster_GetEquipmentType 1002
CREATE PROCEDURE [dbo].[EquipmentMaster_GetEquipmentType]
@EquipmentMasterId as bigint
AS
BEGIN
	SELECT EquipmentType,EquipmentTypeId,[Version] FROM EquipmentMaster (NOLOCK) WHERE EquipmentMasterId=@EquipmentMasterId
END
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_HomePage_Display]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMaster_HomePage_Display 3
CREATE PROCEDURE [dbo].[EquipmentMaster_HomePage_Display] 
	@BranchId as bigint = 0	
AS
	Set nocount on
	Begin
	
		DECLARE @strQuery AS NVARCHAR(4000)
		
		Select EM.EquipmentMasterId,em.EquipmentName,EM.EquipmentOnlineStatus,isnull(RIGHT('00000'+ CONVERT(VARCHAR(10),EMAL.ALCount),4),0) as ALCount ,EMAL.ALCount,ECH.HealthCount,
		(Case isnull(EMR.MAXReviewLogDateTime,'') When '' Then 'ALL RECORDS' Else CONVERT(VARCHAR(10), EMR.MAXReviewLogDateTime, 105) + ' '  + convert(VARCHAR(5), EMR.MAXReviewLogDateTime, 14) End) as MAXReviewLogDateTime,
		(Case isnull(EMA.MAXApproveLogDateTime,'') When '' Then 'ALL RECORDS' Else CONVERT(VARCHAR(10), EMA.MAXApproveLogDateTime, 105) + ' '  + convert(VARCHAR(5), EMA.MAXApproveLogDateTime, 14) End) as MAXApproveLogDateTime

		FROM EquipmentMaster(NOLOCK) as EM		
		Outer Apply
		(
			Select MAX(ToDateTime) as MAXReviewLogDateTime
			from EquipmentMasterLogReviewApprove (NOLOCK) EML Where EML.EquipmentMasterId=EM.EquipmentMasterId
			And EML.ReviewedApproved='R'
		)EMR
			Outer Apply
		(
			Select MAX(ToDateTime) as MAXApproveLogDateTime 
			from EquipmentMasterLogReviewApprove (NOLOCK) EML Where EML.EquipmentMasterId=EM.EquipmentMasterId
			And EML.ReviewedApproved='A'
		)EMA
		Outer Apply
		(
			Select COUNT(EquipmentMasterAlarmAuditTrailId) As ALCount from EquipmentMasterAlarmAuditTrail (NOLOCK) EMA
			Where AckUserId IS NULL  and EMA.EquipmentMasterId=EM.EquipmentMasterId
						
		)EMAL
		Outer Apply
		(
			select count(EquipmentMasterId) as [HealthCount] from EquipmentComponentRunningHours as ECH 
			where SetRunHours < RunHours and ECH.EquipmentMasterId=EM.EquipmentMasterId
						
		)ECH
		Where EquipmentStatus=0 and (@BranchId = 0 or EM.BranchId = @BranchId)		
		
	

	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMaster_List 68,0,1
CREATE Procedure [dbo].[EquipmentMaster_List]
 @RecordKeyId as bigint=0,
 @BranchId as bigint = 0,
 @EquipmentStatus as tinyint=2
As 
Begin
	SET NOCOUNT ON;
	if @EquipmentStatus =2 
	begin			
		SELECT EM.*,EquipmentMasterId,EquipmentName as [Equipment Name],BranchId,AC.GroupId,EquipmentId as [IP Address],ActiveChannel,EquipmentSrNo,EM.EquipmentTypeId,EM.EquipmentType,EM.BranchId,AC.CompanyName,			
		CASE WHEN EquipmentOnlineStatus =0 THEN 'Online' ELSE 'Offline' END AS StatusOnline,EquipmentLastLogDateTime,
		(Case When DoorAccessType='P' Then 'PLC' When DoorAccessType='B' Then 'BIOMETRIC' When DoorAccessType='N' Then 'NONE' Else EM.DoorAccessType End) as DoorAccessType,
		(Case EquipmentStatus when 0 Then 'Active' Else 'Not Active' End) as RecordStatus,
		dbo.GetLastModifedDate(LastModifedDate) as ModifedDate,
		ET.EquipmentTypeGroup,ET.EquipmentTypeName,ET.ParameterLowLimit,ET.ParameterHighLimit,ET.ParameterNo,dbo.GetLastModifedDetails(EM.ModifedBy,LastModifedDate) as LastModifed
		FROM EquipmentMaster (NoLock) as EM 
		left outer join EquipmentType (nolock) as ET on EM.EquipmentTypeId = ET.EquipmentTypeId
		inner join App_Company (nolock) as AC on EM.BranchId = AC.CompanyId	
		Where (@RecordKeyId=0 Or EquipmentMasterId=@RecordKeyId) AND (@BranchId = 0 or BranchId = @BranchId)
	end      
	else
	begin					
		SELECT EM.*,EquipmentMasterId,EquipmentName as [Equipment Name],BranchId,AC.GroupId,EquipmentId as [IP Address],ActiveChannel,EquipmentSrNo,EM.EquipmentTypeId,EM.EquipmentType,EM.BranchId,AC.CompanyName,			
		CASE WHEN EquipmentOnlineStatus =1 THEN 'Online' ELSE 'OFFLINE' END AS StatusOnline,(Case EquipmentStatus when 0 Then 'Active' Else 'Not Active' End) as RecordStatus,
		(Case When DoorAccessType='P' Then 'PLC' When DoorAccessType='B' Then 'BIOMETRIC' When DoorAccessType='N' Then 'NONE' Else EM.DoorAccessType End) as DoorAccessType,
		 EquipmentLastLogDateTime,
		dbo.GetLastModifedDate(LastModifedDate) as ModifedDate,
		ET.EquipmentTypeGroup,ET.EquipmentTypeName,ET.ParameterLowLimit,ET.ParameterHighLimit,ET.ParameterNo,dbo.GetLastModifedDetails(EM.ModifedBy,LastModifedDate) as LastModifed
		FROM EquipmentMaster (NoLock) as EM 
		left outer join EquipmentType (nolock) as ET on EM.EquipmentTypeId = ET.EquipmentTypeId
		inner join App_Company (nolock) as AC on EM.BranchId = AC.CompanyId	
		Where (@RecordKeyId=0 Or EquipmentMasterId=@RecordKeyId) AND (@BranchId = 0 or BranchId = @BranchId) and EquipmentStatus=@EquipmentStatus	      
	end	
End

--select *from App_Company
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_List_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec EquipmentMaster_List_Service '1001','68'
CREATE Procedure [dbo].[EquipmentMaster_List_Service]
 @CompanyId as bigint=0,
 @EquipmentMasterId as Bigint=0
As 
Begin
	SET NOCOUNT ON;
           
    SELECT -- EquipmentMasterId,BranchId,EquipmentId,EquipmentName,ActiveChannel,EquipmentSrNo,EquipmentType,EquipmentTypeId,
	*,dbo.GetLastModifedDetails(ModifedBy,LastModifedDate) as LastModifed
	FROM EquipmentMaster as EM (NoLock)
	outer apply
	(select * from EquipmentType as ET where ET.EquipmentTypeId=EM.EquipmentTypeId
	)ET1
	Where (@CompanyId=0 Or CompanyCode =@CompanyId) and EquipmentStatus=0 
	And (@EquipmentMasterId = 0 or EM.EquipmentMasterId=@EquipmentMasterId)
	and ET1.EquipmentType is Not Null

End

--select *from equipmentmaster
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--EquipmentMaster_Manage '258','136','Eq Live','192.168.1.221','25','16','','0','P','1','Administrator','test','','0'
--EquipmentMaster_Manage '0','3','equipment name 100','111.133.35.55','0','0','COT1H1','0','amar,,,,,','1111,,,,,','132.32.33.12','biometric text','0','B','0','Administrator','OLD Entry','1','','0'
CREATE Procedure [dbo].[EquipmentMaster_Manage]
	@hdnRecordKeyId as Bigint ,
	@BranchId AS BIGINT=0,	
	@EquipmentName as NVARCHAR(100)='',
	@EquipmentId as nvarchar(50)='',
	@EquipmnetLogRate as smallint=0,
	@ActiveChannel as tinyint=0,
	@EquipmentType as nvarchar(20)='',
	@EquipmentTypeId as tinyint=0,	
	@DoorAccessType as nvarchar(5)='N',
	@EquipmentStatus as tinyint = 0,
	@UserName as nvarchar(100)='',
	@hdnLoginComments as nvarchar(255)='',	
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
	--@RecordStatus as tinyint = 0 
As 
SET NOCOUNT ON;
Begin	

	IF @EquipmentTypeId=0	
		SET @EquipmentTypeId = NULL

	IF @EquipmentType=''	
		SET @EquipmentType = NULL

	Declare @Validation as nvarchar(10),@EquipmentTypeGroup as nvarchar(20),@intCount as bigint,@EquipmentMaxValue as bigint
	Set @Validation='True'
	
	SET @EquipmentMaxValue = 0

	SELECT EquipmentMasterId FROM EquipmentMaster (NOLOCK) WHERE EquipmentName = rtrim(ltrim(@EquipmentName))  
	and BranchId=@BranchId
	and (@hdnRecordKeyId = 0 or EquipmentMasterId <> @hdnRecordKeyId) and EquipmentStatus = @EquipmentStatus
	IF  @@rowcount > 0 
		BEGIN
			SET @ReturnMessage = 'EQUIPMENT NAME ALREADY EXIST'
			SET @ReturnId = 0
			Set @Validation='False'
		END
							
	SELECT EquipmentMasterId FROM EquipmentMaster (NOLOCK)
	WHERE ( EquipmentId = rtrim(ltrim(@EquipmentId)) or BiometricIPAddress = rtrim(ltrim(@EquipmentId)) )
	and EquipmentStatus <> 2 and BranchId=@BranchId
	and (@hdnRecordKeyId =0 or EquipmentMasterId <> @hdnRecordKeyId) and EquipmentStatus = @EquipmentStatus  
	
	IF  @@rowcount > 0 
		BEGIN
			SET @ReturnMessage = 'EQUIPMENT IP ADDRESS ALREADY EXIST'
			SET @ReturnId = 0
			Set @Validation='False'
		END
				
--check equipment count is greater than 16 or not
	Select @intCount = count(EM.EquipmentMasterId) from EquipmentMaster (NOLOCK) EM	inner join App_Company CMP on EM.BranchId=CMP.CompanyId		
	where CMP.CompanyId = @BranchId and EquipmentStatus=0
	if @intCount > 1000
		Begin
			SET @ReturnMessage = 'CANNOT ADD MORE THAN 16 EQUIPMENTS'
			SET @ReturnId = 0
			Set @Validation='False'
		END
	--Declare @LogEvent as nvarchar(200)
	if @Validation = 'True'	
		begin 
			begin try
				
				if @hdnRecordKeyId = 0 	
					
					BEGIN		
						
						DECLARE @CompanyCode AS BIGINT
						
						SELECT @CompanyCode=CompanyCode from App_Company(NOLOCK) WHERE CompanyId = (SELECT GroupId from App_Company WHERE CompanyId=@BranchId)									
						Select @EquipmentTypeGroup=EquipmentTypeGroup,@ActiveChannel=ParameterNo  from EquipmentType (NOLOCK) Where EquipmentType=@EquipmentType
						
						INSERT INTO EquipmentMaster (CompanyCode,BranchId,EquipmentName,EquipmentId,EquipmnetLogRate,
									ActiveChannel,EquipmentType,EquipmentTypeId,EquipmentStatus,
									DoorAccessType,CreateDate,CreatedBy,ModifedBy)

							values (@CompanyCode,@BranchId,@EquipmentName,@EquipmentId,@EquipmnetLogRate,
									@ActiveChannel,@EquipmentType,@EquipmentTypeId,@EquipmentStatus,
									@DoorAccessType,GetDate(),@UserName,@UserName)						
						
						IF @@ROWCOUNT > 0
							BEGIN	
								
								SET @ReturnMessage = 'EQUIPMENT ' + @EquipmentName + ' ADDED SUCCESSFULLY'
								SET @ReturnId = @@IDENTITY
								--Set @LogEvent = 'OLD EQUIPMENT Added ADDED SUCCESSFULLY !!!'
								
								EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'NEWE','','',@hdnLoginComments,@UserName
								EXEC EquipmentMasterLog_CreateTable @ReturnId					
								Exec EquipmentMasterParameter_CreateList @ReturnId,@EquipmentType
								Exec EquipmentComponentRunningHours_Insert @ReturnId,@EquipmentTypeGroup
								Exec EquipmentIOStatus_Insert @ReturnId,@EquipmentTypeGroup
								
							END
						ELSE
							BEGIN 
								SET @ReturnMessage = 'EQUIPMENT ADDITION FAILED' 
								SET @ReturnId = 0
							END													
					END
				ELSE
					BEGIN 
						BEGIN TRY
							Declare @EquipmentNameOLD as nvarchar(100),@EquipmentIdOLD as nvarchar(50),@ActiveChannelOLD as tinyint,@EquipmnetLogRateOLD as smallint
							,@EquipmentStatusOLD as tinyint,@OldEquipmentStatusLabelOLD as nvarchar(50),@NEWEquipmentStatusLabelOLD as nvarchar(50),@EquipmentAccessUserNameOLD as nvarchar(1000)
							,@PARAMETEROLD AS NVARCHAR(200),@PARAMETERNEW AS NVARCHAR(200)
							,@AccessUserCodeOLD as nvarchar(1000),@BiometricIPAddressOLD as nvarchar(50),@DoorAccessTypeOLD as nvarchar(5),@BiometricBannerTextOLD as nvarchar(50),@DoorAccessUserNameDisplayOLD as tinyint
						
							Select	@EquipmentNameOLD=EquipmentName,@EquipmentIdOLD=EquipmentId,@ActiveChannelOLD=ActiveChannel,@EquipmentStatusOLD=EquipmentStatus,
							@EquipmnetLogRateOLD=EquipmnetLogRate,@EquipmentAccessUserNameOLD=EquipmentAccessUserName
							,@AccessUserCodeOLD=EquipmentAccessUserCode,@BiometricIPAddressOLD=BiometricIPAddress,@DoorAccessTypeOLD=DoorAccessType
							,@BiometricBannerTextOLD=BiometricBannerText,@DoorAccessUserNameDisplayOLD=DoorAccessUserNameDisplay
							From EquipmentMaster (nolock) Where EquipmentMasterId=@hdnRecordKeyId
							
							UPDATE EquipmentMaster SET 							
							EquipmentName=@EquipmentName,EquipmentId=@EquipmentId,
							EquipmentType=@EquipmentType,EquipmentTypeId=@EquipmentTypeId,								
							EquipmentStatus=@EquipmentStatus,EquipmnetLogRate=@EquipmnetLogRate,
							DoorAccessType=@DoorAccessType,ModifedBy=@UserName,LastModifedDate=GETDATE()
							WHERE EquipmentMasterId = @hdnRecordKeyId

							IF @@rowcount > 0 
								begin 
								print 'success'
									
									SET @ReturnMessage = 'EQUIPMENT DETAILS UPDATED SUCCESSFULLY' 
									SET @ReturnId = @hdnRecordKeyId

									IF @EquipmentNameOLD<>@EquipmentName
									BEGIN
										EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPN',@EquipmentNameOLD,@EquipmentName,@hdnLoginComments,@UserName
									END

									IF @EquipmentIdOLD<>@EquipmentId
									BEGIN
										EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPID',@EquipmentIdOLD,@EquipmentId,@hdnLoginComments,@UserName
									END
									
									IF @EquipmentStatusOLD<>@EquipmentStatus
									BEGIN			
										IF @EquipmentStatus = '1'															
											EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPS','ACTIVE','NOT ACTIVE',@hdnLoginComments,@UserName										
										ELSE
											EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPS','NOT ACTIVE','ACTIVE',@hdnLoginComments,@UserName
									END

									IF @EquipmnetLogRateOLD<>@EquipmnetLogRate
									BEGIN
										 SET @PARAMETERNEW = 'LOG RATE-'+CAST(@EquipmnetLogRate AS NVARCHAR(100))
										 SET @PARAMETEROLD = 'LOG RATE-'+CAST(@EquipmnetLogRateOLD AS NVARCHAR(100))
										 EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPLG',@PARAMETEROLD,@PARAMETERNEW,@hdnLoginComments,@UserName
									END

									IF @DoorAccessTypeOLD<>@DoorAccessType
									BEGIN										
										SET	@PARAMETERNEW = 'DOOR ACCESS TYPE-'+(SELECT CASE  WHEN @DoorAccessType='N' THEN 'NONE' WHEN @DoorAccessType='B' THEN 'BIMETRIC' ELSE 'PLC' END)										
										SET	@PARAMETEROLD = 'DOOR ACCESS TYPE-'+(SELECT CASE WHEN @DoorAccessTypeOLD='N' THEN 'NONE' WHEN @DoorAccessTypeOLD='B' THEN 'BIMETRIC' ELSE 'PLC' END)
										EXEC EquipmentMasterAuditTrail_Manage @hdnRecordKeyId,@EquipmentName,'EQUPDA',@PARAMETEROLD,@PARAMETERNEW,@hdnLoginComments,@UserName
									END
									
								end
						END TRY
						BEGIN CATCH
							set @ReturnMessage=dbo.RemoveSpecialChars(ERROR_MESSAGE())
						END CATCH;
					END
			END TRY		
			BEGIN CATCH
				set @ReturnMessage=dbo.RemoveSpecialChars(Error_Message())
			END CATCH;
		END	
END

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMaster_Populate 0,163
CREATE PROCEDURE [dbo].[EquipmentMaster_Populate]
@EquipmentStatus AS TINYINT=2,
@BranchId as bigint = 0
AS
SET NOCOUNT ON;
BEGIN
	SELECT EquipmentMasterId,EquipmentName FROM  EquipmentMaster (NOLOCK)
	WHERE (@EquipmentStatus=2 OR EquipmentStatus=@EquipmentStatus)
	AND (@BranchId = 0 or BranchId = @BranchId)
	order By EquipmentName
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_RealTimeSummary]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- exec [EquipmentMaster_RealTimeSummary] 0,3
CREATE PROCEDURE [dbo].[EquipmentMaster_RealTimeSummary] 
	@EquipmentMasterId as BIGINT =0,
	@BranchId as bigint = 0
	
AS
Set nocount on;
BEGIN
--SELECT *FROM EquipmentMaster
SELECT EM.*,EquipmentTypeGroup,CH1.*,CH2.*
FROM EquipmentMaster (NOLOCK) AS EM 
INNER JOIN EquipmentType as ET on EM.EquipmentTypeId = ET.EquipmentTypeId
Outer Apply
(
Select Top 1 EquipmentMasterParameterId as ParameterId1,ParameterName as ParameterName1,ParameterType as ParameterType1,
CASE ISNUMERIC(ParameterRealValue) WHEN 1 THEN CAST(ParameterRealValue AS DECIMAL(18,1)) ELSE -99.9 END as ParameterRealValue1 
From EquipmentMasterParameter (NOLOCK) Where EquipmentMasterId=EM.EquipmentMasterId and ParameterAxis=0
			 
) as CH1
Outer Apply
(
Select Top 1 EquipmentMasterParameterId as ParameterId2,ParameterName as ParameterName2,ParameterType as ParameterType2,
CASE ISNUMERIC(ParameterRealValue) WHEN 1 THEN CAST(ParameterRealValue AS DECIMAL(18,1)) ELSE -99.9 END as ParameterRealValue2 
From EquipmentMasterParameter (NOLOCK) Where EquipmentMasterId=EM.EquipmentMasterId and ParameterAxis=1
			
) as CH2
Where EquipmentStatus=0 and (@BranchId = 0 or EM.BranchId = @BranchId)
AND	(@EquipmentMasterId=0 or EM.EquipmentMasterId=@EquipmentMasterId)



End

Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Reset_Request]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec EquipmentMaster_Reset_Request '100','Test_3','0','0','','gv','admin','','0'
CREATE PROCEDURE [dbo].[EquipmentMaster_Reset_Request]
	@EquipmentMasterId as BIGINT= 0,	
	@EquipmentName as nvarchar(100)='',		
	@SettingParameterType as nvarchar(10)='',
	@SettingParameterLabel as nvarchar(500)='',	
	@Status as nvarchar(10)='P',
	@hdnLoginComments  as NVARCHAR(255)='',
	@LoginName as nvarchar(100)='',		
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
AS
	Set nocount on
	Begin
		Declare @ModbusAddress as nvarchar(100),@Result as nvarchar(255)
		
		if @Status='P'
			SET @Status='PENDING'
		IF @Status='C'
			SET @Status = 'CANCELED'
												
		select @ModbusAddress=ModbusAddress from ModbusLookup(NOLOCK) where ModbusEvent=@SettingParameterType
		
		EXEC EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,@SettingParameterType,'',@Status,@hdnLoginComments,@LoginName,''
		
		SET @ReturnMessage = @ModbusAddress
		SET @ReturnId = @EquipmentMasterId
		print @ReturnMessage
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Search]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMaster_Search  2,25,'','','2','',3
--EquipmentMaster_Search 1,25,'','','','',3,''
CREATE  Procedure [dbo].[EquipmentMaster_Search]
 @PageIndex INT = 1,
 @PageSize Bigint = 10,
 @SearchText as NVARCHAR(50)='',
 @DoorAccessType as NVARCHAR(50)='',
 @EquipmentStatus as tinyint=2,
 @EquipmentType as nvarchar(20)='',
 @BranchId as bigint=0,
 @SelectedRecord as NVARCHAR(100)=''
As  
Begin
	SET NOCOUNT ON;
	Declare @RecordCount as Bigint
	
	--if @PageIndex=1
	begin
		if @EquipmentStatus=2
			begin	
			
			PRINT ('1')			
				SELECT ROW_NUMBER() OVER (ORDER BY EquipmentName ASC)AS RowNumber
				,EquipmentMasterId,EquipmentName as [Equipment Name] ,EquipmentId as [IP Address],BiometricIPAddress,ActiveChannel,EquipmentSrNo,EM.EquipmentTypeId,EM.EquipmentType,EM.BranchId,AC.CompanyName,
				CASE WHEN EquipmentOnlineStatus =1 THEN 'Online' ELSE 'OFFLINE' END AS StatusOnline,
				(Case When DoorAccessType='P' Then 'PLC' When DoorAccessType='B' Then 'BIOMETRIC' When DoorAccessType='N' Then 'NONE' Else EM.DoorAccessType End) as DoorAccessType,
				AC.GroupId,
				EquipmentLastLogDateTime,
				(Case EquipmentStatus when 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,EM.ModifedBy,
				dbo.GetLastModifedDate(LastModifedDate) as ModifedDate,EquipmnetLogRate
				INTO #Results FROM EquipmentMaster EM (NoLock) 				
				inner join App_Company AS AC on EM.BranchId=AC.CompanyId 
				Where (EquipmentName like ('%' + @SearchText + '%') Or EM.ModifedBy like ('%' + @SearchText + '%'))
				and (@BranchId = 0 or BranchId=@BranchId) 
				and (@SelectedRecord = '') OR EquipmentMasterId in (Select * from dbo.CSVToTable(@SelectedRecord))
						
				Set @RecordCount = @@ROWCOUNT    			
				SELECT EquipmentMasterId,@RecordCount as RecordCount,[Equipment Name], [IP Address],DoorAccessType,RecordStatus,EquipmentLastLogDateTime,StatusOnline,ModifedBy,ModifedDate,EquipmentTypeId,EquipmentType,CompanyName,BranchId,GroupId,BiometricIPAddress,ActiveChannel,EquipmnetLogRate
				FROM #Results 
				WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 	
				DROP TABLE #Results
			end
		else
			begin	
			PRINT ('2')	
									
				if @DoorAccessType = 'B'				
					begin
					
						SELECT ROW_NUMBER() OVER (ORDER BY EquipmentName ASC)AS RowNumber
						,EquipmentMasterId,EquipmentName,EquipmentId as [IP Address],BiometricIPAddress as [BIOMetric IP Address],ActiveChannel,BranchId,EquipmentSrNo,EquipmentId ,ET.EquipmentType,ET.EquipmentTypeId,DoorAccessType,
						(Case When EquipmentStatus = 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,EquipmentStatus,EM.ModifedBy,EquipmentLastLogDateTime,
						CASE WHEN EquipmentOnlineStatus =1 THEN 'Online' ELSE 'OFFLINE' END AS StatusOnline,AC.CompanyName,AC.GroupId,
						(Case When DoorAccessType='P' Then 'PLC' When DoorAccessType='B' Then 'BIOMETRIC' When DoorAccessType='N' Then 'NONE' Else EM.DoorAccessType End) as [DoorAccess Type],
						dbo.GetLastModifedDate(LastModifedDate) as ModifedDate
						INTO #Results2 FROM EquipmentMaster EM (NoLock)
						inner join EquipmentType (NOLOCK) ET on EM.EquipmentTypeId = ET.EquipmentTypeId
						inner join App_Company (NOLOCK) AC on AC.CompanyId=EM.BranchId
						Where (EquipmentName like ('%' + @SearchText + '%') Or EM.ModifedBy like ('%' + @SearchText + '%'))  and BranchId=@BranchId
						and EquipmentStatus=@EquipmentStatus and DoorAccessType=@DoorAccessType  and EM.EquipmentType like '%'+@EquipmentType+'%'

						Set @RecordCount = @@ROWCOUNT
	    	
						SELECT EquipmentMasterId,@RecordCount as RecordCount,EquipmentName, [IP Address],[BIOMetric IP Address],RecordStatus
						FROM #Results2
						WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 	
						DROP TABLE #Results2
					end
				else 
					begin 
						SELECT ROW_NUMBER() OVER (ORDER BY EquipmentName ASC)AS RowNumber
						,EquipmentMasterId,EquipmentName as [Equipment Name] ,EquipmentId as [IP Address],ActiveChannel,EquipmentSrNo,EM.EquipmentTypeId,EM.EquipmentType,EM.BranchId,AC.CompanyName,BIOMetricIPAddress,
						CASE WHEN EquipmentOnlineStatus =1 THEN 'Online' ELSE 'OFFLINE' END AS StatusOnline,
						(Case When DoorAccessType='P' Then 'PLC' When DoorAccessType='B' Then 'BIOMETRIC' When DoorAccessType='N' Then 'NONE' Else EM.DoorAccessType End) as DoorAccessType,
						AC.GroupId,
						EquipmentLastLogDateTime,EquipmnetLogRate as [EquipmnetLogRate],
						(Case EquipmentStatus when 0 Then 'Active' Else 'Not Active' End) as RecordStatus ,EM.ModifedBy,
						dbo.GetLastModifedDate(LastModifedDate) as ModifedDate
						INTO #Results1 FROM EquipmentMaster EM (NoLock) 				
						inner join App_Company (NOLOCK) AS AC on EM.BranchId=AC.CompanyId 
						Where (EquipmentName like ('%' + @SearchText + '%') Or EM.ModifedBy like ('%' + @SearchText + '%'))
						AND EM.EquipmentType LIKE '%'+@EquipmentType+'%' 
						and BranchId=@BranchId and EquipmentStatus=@EquipmentStatus 
						and (@DoorAccessType='' or DoorAccessType<>'N')

						Set @RecordCount = @@ROWCOUNT
	    			
						SELECT EquipmentMasterId,@RecordCount as RecordCount,[Equipment Name], [IP Address],DoorAccessType,RecordStatus,EquipmentLastLogDateTime,StatusOnline,ModifedBy,ModifedDate,BiometricIPAddress,EquipmentTypeId,EquipmentType,CompanyName,BranchId,GroupId,EquipmnetLogRate,ActiveChannel
						FROM #Results1 
						WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 	
						DROP TABLE #Results1
				end
		end			
	end
	--else if @PageIndex=3
	--begin	
	--	select * from EquipmentMaster
	--end
End
	

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMaster_Sync] 3,'2016-01-01 23:59:00.00'
CREATE PROCEDURE [dbo].[EquipmentMaster_Sync]
	@CompanyId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
	
--Create EquipmentMasterLog

		DECLARE @List nvarchar(1000)
		DECLARE @ListItem nvarchar(1000)  -- amend this to a length that will
		DECLARE @Pos int

		SET @List = ''
		

	SELECT @List=SUBSTRING(	(SELECT ',' + CAST(SourceDBTable.[EquipmentMasterId] AS VARCHAR(50)) from EquipmentMaster SourceDBTable
							where BranchId = @CompanyId AND
							not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMaster DestinationDBTable
							where DestinationDBTable.EquipmentMasterId = SourceDBTable.EquipmentMasterId) 
							ORDER BY SourceDBTable.EquipmentName FOR XML PATH(''))
							 ,2,200000)
	
		WHILE LEN(@List) > 0
		Begin
			   SET @Pos = CHARINDEX(',', @List)
			   IF @Pos = 0
				   Begin
						   SET @ListItem = @List
				   End
			   ELSE
				   Begin
						   SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
				   End
			   
			   EXEC ICDAS_3_0_Archive.dbo.EquipmentMasterLog_CreateTable @ListItem
			   
			   
			   IF @Pos = 0
				   Begin
						   SET @List = ''
				   End
			   ELSE
				   Begin
							SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
				   End
		End
		
--Update EquipmentMasterLog Record

		SET @List =''
		SET @ListItem =''
		SET @Pos =0

	SELECT @List=SUBSTRING(	(SELECT ',' + CAST(SourceDBTable.[EquipmentMasterId] AS VARCHAR(50)) from EquipmentMaster SourceDBTable
	where BranchId=@CompanyId
	ORDER BY SourceDBTable.EquipmentName FOR XML PATH(''))
	 ,2,200000)
	 
	 
		WHILE LEN(@List) > 0
		Begin
			   SET @Pos = CHARINDEX(',', @List)
			   IF @Pos = 0
				   Begin
						   SET @ListItem = @List
				   End
			   ELSE
				   Begin
						   SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
				   End
			  
			   EXEC EquipmentMasterLog_Sync @LogDateTime,@ListItem
			   
			   
			   
			   IF @Pos = 0
				   Begin
						   SET @List = ''
				   End
			   ELSE
				   Begin
							SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
				   End
		End	
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMaster
			([EquipmentMasterId],[CompanyCode],[BranchId],[EquipmentId],[EquipmentName],[ActiveChannel],[EquipmentSrNo],[EquipmentType],[EquipmentTypeId]
           ,[EquipmnetLogRate],[EquipmentDetails],[EquipmentStatus],[EquipmentOnlineStatus],[EquipmentLastLogDateTime]
           ,[EquipmentAccessUserName]
           ,[EquipmentAccessUserCode],[DoorAccessType],[BiometricBannerText],[DoorAccessUserNameDisplay],[BiometricIPAddress]
           ,[TempraturePIDKP],[TempraturePIDTS],[TempraturePIDTI]
           ,[TempraturePIDCycleTime],[TempraturePIDTD],[TempraturePIDOutputPower],[TempratureCooling]
           ,[HumidityPIDKP],[HumidityPIDTS],[HumidityPIDTI],[HumidityPIDCycleTime],[HumidityPIDTD],[HumidityPIDOutputPower]
           ,[HumidityCooling],[SetLuxValue],[SetUVValue],[MeasuredLUXIntensity],[MeasuredUVIntensity],[TempratureLowerLowerLimit]
           ,[TempratureLowerLimit],[TempratureSetValue],[TempratureUpperLimit],[TempratureUpperUpperLimit],[HumidityLowerLowerLimit]
           ,[HumidityLowerLimit],[HumiditySetValue],[HumidityUpperLimit],[HumidityUpperUpperLimit],[Version]
           ,[TempratureLowerLimit2],[TempratureSetValue2],[TempratureUpperLimit2]
           ,[TempratureLowerLimit3],[TempratureSetValue3],[TempratureUpperLimit3]
           ,[TempratureLowerLimit4],[TempratureSetValue4],[TempratureUpperLimit4]
           ,[SoakTime1],[SoakTime2],[SoakTime3],[SoakTime4]
           ,[RampTime1],[RampTime2],[RampTime3],[RampTime4]
           ,[LowerRange],[HigherRange]
           ,[SetSCHSpeed],[SetSCHTime],[SetSCHLowAlarm],[SetSCHHighAlarm]
           ,[CO2SetValue],[CO2LowerLimit],[CO2HigherLimit]
           ,[O2SetValue],[O2LowerLimit],[O2HigherLimit]
           ,[SterilizationSetValue],[SterilizationSetTime]
           ,[CO2HidePanel]
           ,[NoOfCycles]
           ,[CreateDate],[CreatedBy],[ModifedBy],[LastModifedDate]
           )
		select
			SourceDBTable.[EquipmentMasterId],SourceDBTable.[CompanyCode],SourceDBTable.[BranchId],SourceDBTable.[EquipmentId] ,SourceDBTable.[EquipmentName],SourceDBTable.[ActiveChannel],SourceDBTable.[EquipmentSrNo]
           ,SourceDBTable.[EquipmentType],SourceDBTable.[EquipmentTypeId],SourceDBTable.[EquipmnetLogRate],SourceDBTable.[EquipmentDetails],SourceDBTable.[EquipmentStatus],SourceDBTable.[EquipmentOnlineStatus]
           ,SourceDBTable.[EquipmentLastLogDateTime]
           ,SourceDBTable.[EquipmentAccessUserName]
           ,SourceDBTable.[EquipmentAccessUserCode],SourceDBTable.[DoorAccessType],SourceDBTable.[BiometricBannerText],SourceDBTable.[DoorAccessUserNameDisplay],SourceDBTable.[BiometricIPAddress]
           ,SourceDBTable.[TempraturePIDKP],SourceDBTable.[TempraturePIDTS],SourceDBTable.[TempraturePIDTI]
           ,SourceDBTable.[TempraturePIDCycleTime],SourceDBTable.[TempraturePIDTD],SourceDBTable.[TempraturePIDOutputPower],SourceDBTable.[TempratureCooling]
           ,SourceDBTable.[HumidityPIDKP],SourceDBTable.[HumidityPIDTS],SourceDBTable.[HumidityPIDTI],SourceDBTable.[HumidityPIDCycleTime],SourceDBTable.[HumidityPIDTD],SourceDBTable.[HumidityPIDOutputPower]
           ,SourceDBTable.[HumidityCooling],SourceDBTable.[SetLuxValue],SourceDBTable.[SetUVValue],SourceDBTable.[MeasuredLUXIntensity],SourceDBTable.[MeasuredUVIntensity],SourceDBTable.[TempratureLowerLowerLimit]
           ,SourceDBTable.[TempratureLowerLimit],SourceDBTable.[TempratureSetValue],SourceDBTable.[TempratureUpperLimit],SourceDBTable.[TempratureUpperUpperLimit],SourceDBTable.[HumidityLowerLowerLimit]
           ,SourceDBTable.[HumidityLowerLimit],SourceDBTable.[HumiditySetValue],SourceDBTable.[HumidityUpperLimit],SourceDBTable.[HumidityUpperUpperLimit],SourceDBTable.[Version]
           ,SourceDBTable.[TempratureLowerLimit2],SourceDBTable.[TempratureSetValue2],SourceDBTable.[TempratureUpperLimit2]
           ,SourceDBTable.[TempratureLowerLimit3],SourceDBTable.[TempratureSetValue3],SourceDBTable.[TempratureUpperLimit3]
           ,SourceDBTable.[TempratureLowerLimit4],SourceDBTable.[TempratureSetValue4],SourceDBTable.[TempratureUpperLimit4]
           ,SourceDBTable.[SoakTime1],SourceDBTable.[SoakTime2],SourceDBTable.[SoakTime3],SourceDBTable.[SoakTime4]
           ,SourceDBTable.[RampTime1],SourceDBTable.[RampTime2],SourceDBTable.[RampTime3],SourceDBTable.[RampTime4]
           ,SourceDBTable.[LowerRange],SourceDBTable.[HigherRange]
           ,SourceDBTable.[SetSCHSpeed],SourceDBTable.[SetSCHTime],SourceDBTable.[SetSCHLowAlarm],SourceDBTable.[SetSCHHighAlarm]
           ,SourceDBTable.[CO2SetValue],SourceDBTable.[CO2LowerLimit],SourceDBTable.[CO2HigherLimit]
           ,SourceDBTable.[O2SetValue],SourceDBTable.[O2LowerLimit],SourceDBTable.[O2HigherLimit]
           ,SourceDBTable.[SterilizationSetValue],SourceDBTable.[SterilizationSetTime]
           ,SourceDBTable.[CO2HidePanel]
           ,SourceDBTable.[NoOfCycles]
           ,SourceDBTable.[CreateDate],SourceDBTable.[CreatedBy],SourceDBTable.[ModifedBy],SourceDBTable.[LastModifedDate]
		from EquipmentMaster SourceDBTable
		where BranchId=@CompanyId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMaster DestinationDBTable
						 where DestinationDBTable.EquipmentMasterId = SourceDBTable.EquipmentMasterId)
						 
	
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.EquipmentMaster 
	set    [BranchId]=SourceDBTable.[BranchId],[EquipmentId]=SourceDBTable.[EquipmentId],[EquipmentName]=SourceDBTable.[EquipmentName]
		   ,[ActiveChannel]=SourceDBTable.[ActiveChannel],[EquipmentSrNo]=SourceDBTable.[EquipmentSrNo],[EquipmentType]=SourceDBTable.[EquipmentType],[EquipmentTypeId]=SourceDBTable.[EquipmentTypeId]
		   ,[EquipmnetLogRate]=SourceDBTable.[EquipmnetLogRate],[EquipmentDetails]=SourceDBTable.[EquipmentDetails],[EquipmentStatus]=SourceDBTable.[EquipmentStatus]
		   ,[EquipmentOnlineStatus]=SourceDBTable.[EquipmentOnlineStatus],[EquipmentLastLogDateTime]=SourceDBTable.[EquipmentLastLogDateTime]
		   ,[EquipmentAccessUserName] = SourceDBTable.[EquipmentAccessUserName]
		   
		   ,[EquipmentAccessUserCode]= SourceDBTable.[EquipmentAccessUserCode],[DoorAccessType]= SourceDBTable.[DoorAccessType],[BiometricBannerText]= SourceDBTable.[BiometricBannerText],[DoorAccessUserNameDisplay]= SourceDBTable.[DoorAccessUserNameDisplay],[BiometricIPAddress]= SourceDBTable.[BiometricIPAddress]
		   
		   ,[TempraturePIDKP] = SourceDBTable.[TempraturePIDKP],[TempraturePIDTS] = SourceDBTable.[TempraturePIDTS],[TempraturePIDTI] = SourceDBTable.[TempraturePIDTI]
           ,[TempraturePIDCycleTime] = SourceDBTable.[TempraturePIDCycleTime],[TempraturePIDTD] = SourceDBTable.[TempraturePIDTD],[TempraturePIDOutputPower] = SourceDBTable.[TempraturePIDOutputPower],[TempratureCooling] = SourceDBTable.[TempratureCooling]
           ,[HumidityPIDKP] = SourceDBTable.[HumidityPIDKP],[HumidityPIDTS] = SourceDBTable.[HumidityPIDTS],[HumidityPIDTI] = SourceDBTable.[HumidityPIDTI],[HumidityPIDCycleTime] = SourceDBTable.[HumidityPIDCycleTime],[HumidityPIDTD] = SourceDBTable.[HumidityPIDTD],[HumidityPIDOutputPower] = SourceDBTable.[HumidityPIDOutputPower]
           ,[HumidityCooling] = SourceDBTable.[HumidityCooling],[SetLuxValue] = SourceDBTable.[SetLuxValue],[SetUVValue] = SourceDBTable.[SetUVValue],[MeasuredLUXIntensity] = SourceDBTable.[MeasuredLUXIntensity],[MeasuredUVIntensity] =		SourceDBTable.[MeasuredUVIntensity],[TempratureLowerLowerLimit] = SourceDBTable.[TempratureLowerLowerLimit]
           ,[TempratureLowerLimit] = SourceDBTable.[TempratureLowerLimit],[TempratureSetValue] = SourceDBTable.[TempratureSetValue],[TempratureUpperLimit] = SourceDBTable.[TempratureUpperLimit],[TempratureUpperUpperLimit] = SourceDBTable.[TempratureUpperUpperLimit],[HumidityLowerLowerLimit] = SourceDBTable.[HumidityLowerLowerLimit]
           ,[HumidityLowerLimit] = SourceDBTable.[HumidityLowerLimit],[HumiditySetValue] = SourceDBTable.[HumiditySetValue],[HumidityUpperLimit] = SourceDBTable.[HumidityUpperLimit],[HumidityUpperUpperLimit] = SourceDBTable.[HumidityUpperUpperLimit],[Version] = SourceDBTable.[Version]
		   
		   ,[TempratureLowerLimit2]=SourceDBTable.[TempratureLowerLimit2],[TempratureSetValue2]=SourceDBTable.[TempratureSetValue2],[TempratureUpperLimit2]=SourceDBTable.[TempratureUpperLimit2]
           ,[TempratureLowerLimit3]=SourceDBTable.[TempratureLowerLimit3],[TempratureSetValue3]=SourceDBTable.[TempratureSetValue3],[TempratureUpperLimit3]=SourceDBTable.[TempratureUpperLimit3]
           ,[TempratureLowerLimit4]=SourceDBTable.[TempratureLowerLimit4],[TempratureSetValue4]=SourceDBTable.[TempratureSetValue4],[TempratureUpperLimit4]=SourceDBTable.[TempratureUpperLimit4]
           ,[SoakTime1]=SourceDBTable.[SoakTime1],[SoakTime2]=SourceDBTable.[SoakTime2],[SoakTime3]=SourceDBTable.[SoakTime3],[SoakTime4]=SourceDBTable.[SoakTime4]
           ,[RampTime1]=SourceDBTable.[RampTime1],[RampTime2]=SourceDBTable.[RampTime2],[RampTime3]=SourceDBTable.[RampTime3],[RampTime4]=SourceDBTable.[RampTime4]
           ,[LowerRange] = SourceDBTable.[LowerRange],[HigherRange]=SourceDBTable.[HigherRange]
           ,[SetSCHSpeed] = SourceDBTable.[SetSCHSpeed],[SetSCHTime] = SourceDBTable.[SetSCHTime],[SetSCHLowAlarm] = SourceDBTable.[SetSCHLowAlarm]
           ,[SetSCHHighAlarm] = SourceDBTable.[SetSCHHighAlarm]
           ,[CO2SetValue] = SourceDBTable.[CO2SetValue],[CO2LowerLimit] = SourceDBTable.[CO2LowerLimit],[CO2HigherLimit] = SourceDBTable.[CO2HigherLimit]
           ,[O2SetValue] = SourceDBTable.[O2SetValue],[O2LowerLimit] = SourceDBTable.[O2LowerLimit],[O2HigherLimit] = SourceDBTable.[O2HigherLimit]
           ,[SterilizationSetValue] = SourceDBTable.[SterilizationSetValue],[SterilizationSetTime] = SourceDBTable.[SterilizationSetTime]
           ,[CO2HidePanel] = SourceDBTable.[CO2HidePanel]
           ,[CreateDate] = SourceDBTable.[CreateDate],[CreatedBy] = SourceDBTable.[CreatedBy],[ModifedBy] = SourceDBTable.[ModifedBy],[LastModifedDate] = SourceDBTable.[LastModifedDate]
		   
	from	ICDAS_3_0_Archive.dbo.EquipmentMaster DestinationDBTable,
			(
				select	max(TableName) as TableName, [EquipmentMasterId],[BranchId],[EquipmentId],[EquipmentName],[ActiveChannel],[EquipmentSrNo],[EquipmentType],[EquipmentTypeId]
				   ,[EquipmnetLogRate],[EquipmentDetails],[EquipmentStatus],[EquipmentOnlineStatus],[EquipmentLastLogDateTime]
				   ,[EquipmentAccessUserName]
				   ,[EquipmentAccessUserCode],[DoorAccessType],[BiometricBannerText],[DoorAccessUserNameDisplay],[BiometricIPAddress]
				   ,[TempraturePIDKP],[TempraturePIDTS],[TempraturePIDTI]
				   ,[TempraturePIDCycleTime],[TempraturePIDTD],[TempraturePIDOutputPower],[TempratureCooling]
                   ,[HumidityPIDKP],[HumidityPIDTS],[HumidityPIDTI],[HumidityPIDCycleTime],[HumidityPIDTD],[HumidityPIDOutputPower]
                   ,[HumidityCooling],[SetLuxValue],[SetUVValue],[MeasuredLUXIntensity],[MeasuredUVIntensity],[TempratureLowerLowerLimit]
                   ,[TempratureLowerLimit],[TempratureSetValue],[TempratureUpperLimit],[TempratureUpperUpperLimit],[HumidityLowerLowerLimit]
                   ,[HumidityLowerLimit],[HumiditySetValue],[HumidityUpperLimit],[HumidityUpperUpperLimit],[Version]
                   ,[TempratureLowerLimit2],[TempratureSetValue2],[TempratureUpperLimit2]
				   ,[TempratureLowerLimit3],[TempratureSetValue3],[TempratureUpperLimit3]
				   ,[TempratureLowerLimit4],[TempratureSetValue4],[TempratureUpperLimit4]
				   ,[SoakTime1],[SoakTime2],[SoakTime3],[SoakTime4]
				   ,[RampTime1],[RampTime2],[RampTime3],[RampTime4]
				   ,[LowerRange],[HigherRange]
				   ,[SetSCHSpeed],[SetSCHTime],[SetSCHLowAlarm],[SetSCHHighAlarm]
				   ,[CO2SetValue],[CO2LowerLimit],[CO2HigherLimit]
				   ,[O2SetValue],[O2LowerLimit],[O2HigherLimit]
				   ,[SterilizationSetValue],[SterilizationSetTime]
				   ,[CO2HidePanel]
				   ,[NoOfCycles]
				   ,[CreateDate],[CreatedBy],[ModifedBy],[LastModifedDate]
				from
					(
						select	'SourceTableName' as TableName, [EquipmentMasterId],[BranchId],[EquipmentId],[EquipmentName],[ActiveChannel],[EquipmentSrNo],[EquipmentType],[EquipmentTypeId]
						   ,[EquipmnetLogRate],[EquipmentDetails],[EquipmentStatus],[EquipmentOnlineStatus],[EquipmentLastLogDateTime]
						   ,[EquipmentAccessUserName]
						   ,[EquipmentAccessUserCode],[DoorAccessType],[BiometricBannerText],[DoorAccessUserNameDisplay],[BiometricIPAddress]
           				   ,[TempraturePIDKP],[TempraturePIDTS],[TempraturePIDTI]
                           ,[TempraturePIDCycleTime],[TempraturePIDTD],[TempraturePIDOutputPower],[TempratureCooling]
                           ,[HumidityPIDKP],[HumidityPIDTS],[HumidityPIDTI],[HumidityPIDCycleTime],[HumidityPIDTD],[HumidityPIDOutputPower]
                           ,[HumidityCooling],[SetLuxValue],[SetUVValue],[MeasuredLUXIntensity],[MeasuredUVIntensity],[TempratureLowerLowerLimit]
                           ,[TempratureLowerLimit],[TempratureSetValue],[TempratureUpperLimit],[TempratureUpperUpperLimit],[HumidityLowerLowerLimit]
                           ,[HumidityLowerLimit],[HumiditySetValue],[HumidityUpperLimit],[HumidityUpperUpperLimit],[Version]
                           ,[TempratureLowerLimit2],[TempratureSetValue2],[TempratureUpperLimit2]
						   ,[TempratureLowerLimit3],[TempratureSetValue3],[TempratureUpperLimit3]
						   ,[TempratureLowerLimit4],[TempratureSetValue4],[TempratureUpperLimit4]
						   ,[SoakTime1],[SoakTime2],[SoakTime3],[SoakTime4]
						   ,[RampTime1],[RampTime2],[RampTime3],[RampTime4]
						   ,[LowerRange],[HigherRange]
						   ,[SetSCHSpeed],[SetSCHTime],[SetSCHLowAlarm],[SetSCHHighAlarm]
						   ,[CO2SetValue],[CO2LowerLimit],[CO2HigherLimit]
						   ,[O2SetValue],[O2LowerLimit],[O2HigherLimit]
						   ,[SterilizationSetValue],[SterilizationSetTime]
						   ,[CO2HidePanel]
						   ,[NoOfCycles]
						   ,[CreateDate],[CreatedBy],[ModifedBy],[LastModifedDate]
						from EquipmentMaster SourceTableName
						
						union all
						
						select	'DestinationiTableName' as TableName, [EquipmentMasterId],[BranchId],[EquipmentId],[EquipmentName],[ActiveChannel],[EquipmentSrNo],[EquipmentType],[EquipmentTypeId]
						   ,[EquipmnetLogRate],[EquipmentDetails],[EquipmentStatus],[EquipmentOnlineStatus],[EquipmentLastLogDateTime]
						   ,[EquipmentAccessUserName]
						   ,[EquipmentAccessUserCode],[DoorAccessType],[BiometricBannerText],[DoorAccessUserNameDisplay],[BiometricIPAddress]
						   ,[TempraturePIDKP],[TempraturePIDTS],[TempraturePIDTI]
                           ,[TempraturePIDCycleTime],[TempraturePIDTD],[TempraturePIDOutputPower],[TempratureCooling]
                           ,[HumidityPIDKP],[HumidityPIDTS],[HumidityPIDTI],[HumidityPIDCycleTime],[HumidityPIDTD],[HumidityPIDOutputPower]
                           ,[HumidityCooling],[SetLuxValue],[SetUVValue],[MeasuredLUXIntensity],[MeasuredUVIntensity],[TempratureLowerLowerLimit]
                           ,[TempratureLowerLimit],[TempratureSetValue],[TempratureUpperLimit],[TempratureUpperUpperLimit],[HumidityLowerLowerLimit]
                           ,[HumidityLowerLimit],[HumiditySetValue],[HumidityUpperLimit],[HumidityUpperUpperLimit],[Version]
						   ,[TempratureLowerLimit2],[TempratureSetValue2],[TempratureUpperLimit2]
						   ,[TempratureLowerLimit3],[TempratureSetValue3],[TempratureUpperLimit3]
						   ,[TempratureLowerLimit4],[TempratureSetValue4],[TempratureUpperLimit4]
						   ,[SoakTime1],[SoakTime2],[SoakTime3],[SoakTime4]
						   ,[RampTime1],[RampTime2],[RampTime3],[RampTime4]
						   ,[LowerRange],[HigherRange]
						   ,[SetSCHSpeed],[SetSCHTime],[SetSCHLowAlarm],[SetSCHHighAlarm]
						   ,[CO2SetValue],[CO2LowerLimit],[CO2HigherLimit]
						   ,[O2SetValue],[O2LowerLimit],[O2HigherLimit]
						   ,[SterilizationSetValue],[SterilizationSetTime]
						   ,[CO2HidePanel]
						   ,[NoOfCycles]
						   ,[CreateDate],[CreatedBy],[ModifedBy],[LastModifedDate]
						   
						from ICDAS_3_0_Archive.dbo.EquipmentMaster DestinationTableName
					) AliasName
					
					group by [EquipmentMasterId],[BranchId],[EquipmentId],[EquipmentName],[ActiveChannel],[EquipmentSrNo],[EquipmentType],[EquipmentTypeId]
						   ,[EquipmnetLogRate],[EquipmentDetails],[EquipmentStatus],[EquipmentOnlineStatus],[EquipmentLastLogDateTime]
						   ,[EquipmentAccessUserName]
						   ,[EquipmentAccessUserCode],[DoorAccessType],[BiometricBannerText],[DoorAccessUserNameDisplay],[BiometricIPAddress]
           				   ,[TempraturePIDKP],[TempraturePIDTS],[TempraturePIDTI]
                           ,[TempraturePIDCycleTime],[TempraturePIDTD],[TempraturePIDOutputPower],[TempratureCooling]
                           ,[HumidityPIDKP],[HumidityPIDTS],[HumidityPIDTI],[HumidityPIDCycleTime],[HumidityPIDTD],[HumidityPIDOutputPower]
                           ,[HumidityCooling],[SetLuxValue],[SetUVValue],[MeasuredLUXIntensity],[MeasuredUVIntensity],[TempratureLowerLowerLimit]
                           ,[TempratureLowerLimit],[TempratureSetValue],[TempratureUpperLimit],[TempratureUpperUpperLimit],[HumidityLowerLowerLimit]
                           ,[HumidityLowerLimit],[HumiditySetValue],[HumidityUpperLimit],[HumidityUpperUpperLimit],[Version]
                           ,[TempratureLowerLimit2],[TempratureSetValue2],[TempratureUpperLimit2]
						   ,[TempratureLowerLimit3],[TempratureSetValue3],[TempratureUpperLimit3]
						   ,[TempratureLowerLimit4],[TempratureSetValue4],[TempratureUpperLimit4]
						   ,[SoakTime1],[SoakTime2],[SoakTime3],[SoakTime4]
						   ,[RampTime1],[RampTime2],[RampTime3],[RampTime4]
						   ,[LowerRange],[HigherRange]
						   ,[SetSCHSpeed],[SetSCHTime],[SetSCHLowAlarm],[SetSCHHighAlarm]
						   ,[CO2SetValue],[CO2LowerLimit],[CO2HigherLimit]
						   ,[O2SetValue],[O2LowerLimit],[O2HigherLimit]
						   ,[SterilizationSetValue],[SterilizationSetTime]
						   ,[CO2HidePanel]
						   ,[NoOfCycles]
						   ,[CreateDate],[CreatedBy],[ModifedBy],[LastModifedDate]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable
	where DestinationDBTable.EquipmentMasterId = SourceDBTable.EquipmentMasterId and SourceDBTable.BranchId = @CompanyId
			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_SyncDate_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec EquipmentMaster_SyncDate_Manage '113','Newtronic Lifecare Equipment Pvt .Ltd.','0','LuxT','LuxT Timer','1','P','comments','Administrator','LuxUV Timer','LuxT','','0'
CREATE PROCEDURE [dbo].[EquipmentMaster_SyncDate_Manage]
	@hdnRecordIds as NVARCHAR(4000) = '',
	@hdnCompanyId as Bigint,		
	@EquipmentMasterParameterNo as Tinyint,
	@SettingParameterType as nvarchar(10)='',
	@SettingParameterLabel as nvarchar(500)='',
	@SettingParameterValue as nvarchar(100)='',
	@Status as nvarchar(10)='P',
	@hdnLoginComments  as NVARCHAR(255)='',
	@Username as nvarchar(100)='',	
	@PageHead AS nVARCHAR(255)='',
	@LookUpParamaterCode as nvarchar(50)='',
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
AS
	Set nocount on
	Begin
		Declare @LogEvent as nvarchar(100),@EquipmentMasterId as nvarchar(10),@i as bigint,@LoopCount as bigint,@EquipmentName as nvarchar(50),@Result as nvarchar(255)
		declare @ID as bigint
		Set @i=1
		
		--SET @LoopCount = 0
			
		Select @LoopCount = len(@hdnRecordIds)-len(replace(@hdnRecordIds,',','')) + 2
			
		While @i<=@LoopCount
			
			Begin
				
				Set @EquipmentMasterId = dbo.SplitString(@hdnRecordIds,',',@i)
			
				if isnull(@EquipmentMasterId,'') <> ''
					Begin
						set @EquipmentName = (select Equipmentname from EquipmentMaster where EquipmentMasterId=@EquipmentMasterId)						
						SET @ID = 0

						Execute EquipmentMasterWrite_Manage @hdnCompanyId,@EquipmentMasterId,@EquipmentMasterParameterNo,@SettingParameterType,@SettingParameterLabel,@SettingParameterValue,@Status,@hdnLoginComments, @ID output						
						EXEC EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,@LookUpParamaterCode,'','','','',@hdnLoginComments,@Username,''
						

					End
				Else
					Begin
						set @ReturnId=@i 
						Set @ReturnMessage= @PageHead+' Date Time Synchronize Request Sent!!' 						
						break
					End
				Set @i=@i+1
			End		
			set @ReturnId = @ID
						
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_SynDate_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[EquipmentMaster_ListData] 0, 0, 0,0
CREATE PROCEDURE [dbo].[EquipmentMaster_SynDate_ListData] 
	@EquipmentMasterId as bigint = 0,
	@BranchId as bigint = 0,
	@EquipmentStatus as bigint=2
AS
	Set nocount on
	Begin
		SELECT EM.*,ET.EquipmentTypeName,ET.EquipmentTypeId,ET.EquipmentTypeGroup,ET.ParameterLowLimit,ET.ParameterHighLimit,ET.ParameterNo
		FROM EquipmentMaster as EM
		INNER JOIN EquipmentType AS ET ON EM.EquipmentType=ET.EquipmentType
		INNER JOIN App_Company AS BM ON EM.BranchId=BM.CompanyId 
		Where (@EquipmentMasterId = 0 or EM.EquipmentMasterId = @EquipmentMasterId)
		AND (@BranchId = 0 or EM.BranchId = @BranchId)
		AND (@EquipmentStatus = 2 or EM.EquipmentStatus = @EquipmentStatus)
		order By EM.EquipmentName
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_TimerProcess]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--EXECUTE EquipmentMaster_TimerProcess '27','3','HCO','CIT8','admin','Comments','',0
CREATE Procedure [dbo].[EquipmentMaster_TimerProcess]
	@hdnRecordKeyId as Bigint ,
	@BranchId AS BIGINT=0,	
	@EquipmentName as NVARCHAR(100)='',	
	@EquipmentType as nvarchar(20)='',
	@UserName as nvarchar(100)='',
	@hdnLoginComments as nvarchar(255)='',	
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
As 
	SET NOCOUNT ON;
Begin	

			Declare @EquipmentTypeGroup as nvarchar(20)			
			begin try
				if @hdnRecordKeyId <> 0 
				
					Select @EquipmentTypeGroup=EquipmentTypeGroup from EquipmentType Where EquipmentType=@EquipmentType
				
					EXEC EquipmentMasterLog_CreateTable @hdnRecordKeyId					
					Exec EquipmentMasterParameter_CreateList @hdnRecordKeyId,@EquipmentType
					Exec EquipmentComponentRunningHours_Insert @hdnRecordKeyId,@EquipmentTypeGroup
					Exec EquipmentIOStatus_Insert @hdnRecordKeyId,@EquipmentTypeGroup
						
					SET @ReturnMessage = 'New Equipment ' + @EquipmentName + ' Added Successfully !!!'
					SET @ReturnId = @hdnRecordKeyId
					
					PRINT @ReturnId

			END TRY		
			BEGIN CATCH
				set @ReturnMessage=dbo.RemoveSpecialChars(Error_Message())
			END CATCH;

END

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--select * from EquipmentMaster
-- Execute EquipmentMaster_Update '0','1110.0','0.0','100.00','20.00','10.0','5.00','1','500','0','400','10','1','5','','0','0.0','0','0.0','0.0','31.0','90.0','40.0','0.0','0.0','60.0','10.1','90.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0:0','0:0','0:0','0:0','0','0','0','0','0.0','0.0','0','0','0','0','0.0','3030.9','26.0','0.0','0.0','0.0','298.8','0','0','vd','admin','','0'
CREATE PROCEDURE [dbo].[EquipmentMaster_Update]
@hdnRecordKeyId AS BIGINT=0,	

@TempraturePIDKP as nvarchar(10) = '',
@TempraturePIDTS as nvarchar(10) = '',
@TempraturePIDTI as nvarchar(10) = '',
@TempraturePIDCycleTime as nvarchar(10) = '',
@TempraturePIDTD as nvarchar(10) = '',
@TempraturePIDOutputPower as nvarchar(10) = '',
@TempratureCooling as nvarchar(10) = '',

@HumidityPIDKP as nvarchar(10) = '',
@HumidityPIDTS as nvarchar(10) = '',
@HumidityPIDTI as nvarchar(10) = '',
@HumidityPIDCycleTime as nvarchar(10) = '',
@HumidityPIDTD as nvarchar(10) = '',
@HumidityPIDOutputPower as nvarchar(10) = '',
@HumidityCooling as nvarchar(10) = '',

@SetLuxValue as nvarchar(10) = '',
@SetUVValue as nvarchar(10) = '',

@MeasuredLUXIntensity as nvarchar(10) = '',
@MeasuredUVIntensity as nvarchar(10) = '',

@TempratureLowerLowerLimit as nvarchar(10) = '',
@TempratureLowerLimit as nvarchar(10) = '',
@TempratureSetValue as nvarchar(10) = '',
@TempratureUpperLimit as nvarchar(10) = '',
@TempratureUpperUpperLimit as nvarchar(10) = '',

@HumidityLowerLowerLimit as nvarchar(10) = '',
@HumidityLowerLimit as nvarchar(10) = '',
@HumiditySetValue as nvarchar(10) = '',
@HumidityUpperLimit as nvarchar(10) = '',
@HumidityUpperUpperLimit as nvarchar(10) = '',

@TempratureLowerLimit2 as nvarchar(10) = '',
@TempratureSetValue2 as nvarchar(10) = '',
@TempratureUpperLimit2 as nvarchar(10) = '',
@TempratureLowerLimit3 as nvarchar(10) = '',
@TempratureSetValue3 as nvarchar(10) = '',
@TempratureUpperLimit3 as nvarchar(10) = '',
@TempratureLowerLimit4 as nvarchar(10) = '',
@TempratureSetValue4 as nvarchar(10) = '',
@TempratureUpperLimit4 as nvarchar(10) = '',

@SoakTime1 as nvarchar(10) = '',
@SoakTime2 as nvarchar(10) = '',
@SoakTime3 as nvarchar(10) = '',
@SoakTime4 as nvarchar(10) = '',

@RampTime1 as nvarchar(10) = '',
@RampTime2 as nvarchar(10) = '',
@RampTime3 as nvarchar(10) = '',
@RampTime4 as nvarchar(10) = '',

@LowerRange as nvarchar(10) = '',
@HigherRange as nvarchar(10) = '',

@SetSCHSpeed as nvarchar(10) = '',
@SetSCHTime as nvarchar(10) = '',
@SetSCHLowAlarm as nvarchar(10) = '',
@SetSCHHighAlarm as nvarchar(10) = '',

@CO2SetValue as nvarchar(10) = '',
@CO2LowerLimit as nvarchar(10) = '',
@CO2HigherLimit as nvarchar(10) = '',

@O2SetValue as nvarchar(10) = '',
@O2LowerLimit as nvarchar(10) = '',
@O2HigherLimit as nvarchar(10) = '',

@SterilizationSetValue as nvarchar(10) = '',
@SterilizationSetTime as nvarchar(10) = '',

@CO2HidePanel as nvarchar(10) = '',	
@NoOfCycles as nvarchar(10) = '',
	
@comments as nvarchar(255)='',
@username as varchar(100)='',
@ReturnMessage AS VARCHAR(100)=''  OUTPUT,
@ReturnId AS BIGINT =0 OUTPUT

as
SET NOCOUNT ON;
BEGIN
	begin try
		print 1
		if @TempraturePIDKP = NULL
		SET @TempraturePIDKP=''

		if @TempraturePIDTS = NULL
		SET @TempraturePIDTS=''

		if @TempraturePIDTI = NULL
		SET @TempraturePIDTI=''

		if @TempraturePIDCycleTime = NULL
		SET @TempraturePIDCycleTime=''

		if @TempraturePIDTD = NULL
		SET @TempraturePIDTD=''

		if @TempraturePIDOutputPower = NULL
		SET @TempraturePIDOutputPower=''

		if @TempratureCooling = NULL
		SET @TempratureCooling=''

		if @HumidityPIDKP = NULL
		SET @HumidityPIDKP=''

		if @HumidityPIDTS = NULL
		SET @HumidityPIDTS=''

		if @HumidityPIDTI = NULL
		SET @HumidityPIDTI=''

		if @HumidityPIDCycleTime = NULL
		SET @HumidityPIDCycleTime=''
		 
		if @HumidityPIDTD = NULL
		SET @HumidityPIDTD=''

		if @HumidityPIDOutputPower = NULL
		SET @HumidityPIDOutputPower=''

		if @HumidityCooling = NULL
		SET @HumidityCooling=''

		if @SetLuxValue = NULL
		SET @SetLuxValue=''

		if @SetUVValue = NULL
		SET @SetUVValue=''

		if @MeasuredLUXIntensity = NULL
		SET @MeasuredLUXIntensity=''

		if @MeasuredUVIntensity = NULL
		SET @MeasuredUVIntensity=''

		if @TempratureLowerLowerLimit = NULL
		SET @TempratureLowerLowerLimit='0:0'

		if @TempratureLowerLimit = NULL
		SET @TempratureLowerLimit='0:0'

		if @TempratureSetValue = NULL
		SET @TempratureSetValue='0:0'

		if @TempratureUpperLimit = NULL
		SET @TempratureUpperLimit='0:0'

		if @TempratureUpperUpperLimit = NULL
		SET @TempratureUpperUpperLimit='0:0'

		if @HumidityLowerLowerLimit = NULL
		SET @HumidityLowerLowerLimit='0:0'

		if @HumidityLowerLimit = NULL
		SET @HumidityLowerLimit='0:0'

		if @HumiditySetValue = NULL
		SET @HumiditySetValue='0:0'

		if @HumidityUpperLimit = NULL
		SET @HumidityUpperLimit='0:0'

		if @HumidityUpperUpperLimit = NULL
		SET @HumidityUpperUpperLimit='0:0'
	
		if @TempratureLowerLimit2 = NULL
		SET @TempratureLowerLimit2='0:0'

		if @TempratureSetValue2 = NULL
		SET @TempratureSetValue2='0:0'

		if @TempratureUpperLimit2 = NULL
		SET @TempratureUpperLimit2='0:0'

		if @TempratureLowerLimit3 = NULL
		SET @TempratureLowerLimit3='0:0'

		if @TempratureSetValue3 = NULL
		SET @TempratureSetValue3='0:0'

		if @TempratureUpperLimit3 = NULL
		SET @TempratureUpperLimit3='0:0'

		if @TempratureLowerLimit4 = NULL
		SET @TempratureLowerLimit4='0:0'

		if @TempratureSetValue4 = NULL
		SET @TempratureSetValue4='0:0'

		if @TempratureUpperLimit4 = NULL
		SET @TempratureUpperLimit4='0:0'

		if @SoakTime1 = NULL
		SET @SoakTime1='0:0'

		if @SoakTime2 = NULL
		SET @SoakTime2='0:0'

		if @SoakTime3 = NULL
		SET @SoakTime3='0:0'
		
		if @SoakTime4 = NULL
		SET @SoakTime4='0:0'

		if @RampTime1 = NULL
		SET @RampTime1='0'

		if @RampTime2 = NULL
		SET @RampTime2='0'

		if @RampTime3 = NULL
		SET @RampTime3='0'

		if @RampTime4 = NULL
		SET @RampTime4='0'

		if @LowerRange = NULL
		SET @LowerRange='0:0'

		if @HigherRange = NULL
		SET @HigherRange='0:0'

		if @SetSCHSpeed = NULL
		SET @SetSCHSpeed=''

		if @SetSCHTime = NULL
		SET @SetSCHTime=''

		if @SetSCHLowAlarm = NULL
		SET @SetSCHLowAlarm=''

		if @SetSCHHighAlarm = NULL
		SET @SetSCHHighAlarm=''

		if @CO2SetValue = NULL
		SET @CO2SetValue=''

		if @CO2LowerLimit = NULL
		SET @CO2LowerLimit=''

		if @CO2HigherLimit = NULL
		SET @CO2HigherLimit=''

		if @O2SetValue = NULL
		SET @O2SetValue=''

		if @O2LowerLimit = NULL
		SET @O2LowerLimit=''

		if @O2HigherLimit = NULL
		SET @O2HigherLimit=''

		if @SterilizationSetValue = NULL
		SET @SterilizationSetValue=''

		if @SterilizationSetTime = NULL
		SET @SterilizationSetTime=''

		if @CO2HidePanel = NULL	
		SET @CO2HidePanel=''
		 	
		if @NoOfCycles = NULL
		SET @NoOfCycles='0'
	
	 
		declare @EquipmentName as nvarchar(100), @TempraturePIDKPOLD as nvarchar(10),@TempraturePIDTSOLD as nvarchar(10),@TempraturePIDTIOLD as nvarchar(10),@TempraturePIDCycleTimeOLD as nvarchar(10),@TempraturePIDTDOLD as nvarchar(10),@TempraturePIDOutputPowerOLD as nvarchar(10),@TempratureCoolingOLD as nvarchar(10),@HumidityPIDKPOLD as nvarchar(10),
		@HumidityPIDTSOLD as nvarchar(10),@HumidityPIDTIOLD as nvarchar(10),@HumidityPIDCycleTimeOLD as nvarchar(10),@HumidityPIDTDOLD as nvarchar(10),@HumidityPIDOutputPowerOLD as nvarchar(10),
		@HumidityCoolingOLD as nvarchar(10),@SetLuxValueOLD as nvarchar(10),@SetUVValueOLD as nvarchar(10),@MeasuredLUXIntensityOLD as nvarchar(10),@MeasuredUVIntensityOLD as nvarchar(10),
		@TempratureLowerLowerLimitOLD as nvarchar(10),@TempratureLowerLimitOLD as nvarchar(10),@TempratureSetValueOLD as nvarchar(10),
		@TempratureUpperLimitOLD as nvarchar(10),@TempratureUpperUpperLimitOLD as nvarchar(10),@HumidityLowerLowerLimitOLD as nvarchar(10),@HumidityLowerLimitOLD as nvarchar(10),@HumiditySetValueOLD as nvarchar(10),
		@HumidityUpperLimitOLD as nvarchar(10),@HumidityUpperUpperLimitOLD as nvarchar(10),	@TempratureLowerLimit2OLD as nvarchar(10),
		@TempratureSetValue2OLD as nvarchar(10),@TempratureUpperLimit2OLD as nvarchar(10),@TempratureLowerLimit3OLD as nvarchar(10),@TempratureSetValue3OLD as nvarchar(10),@TempratureUpperLimit3OLD as nvarchar(10),@TempratureLowerLimit4OLD as nvarchar(10),
		@TempratureSetValue4OLD as nvarchar(10),@TempratureUpperLimit4OLD as nvarchar(10),@SoakTime1OLD as nvarchar(10),@SoakTime2OLD as nvarchar(10),@SoakTime3OLD as nvarchar(10),@SoakTime4OLD as nvarchar(10),@RampTime1OLD as nvarchar(10),@RampTime2OLD as nvarchar(10),
		@RampTime3OLD as nvarchar(10),@RampTime4OLD as nvarchar(10),@LowerRangeOLD as nvarchar(10),@HigherRangeOLD as nvarchar(10),@SetSCHSpeedOLD as nvarchar(10),@SetSCHTimeOLD as nvarchar(10),
		@SetSCHLowAlarmOLD as nvarchar(10),@SetSCHHighAlarmOLD as nvarchar(10),@CO2SetValueOLD as nvarchar(10),@CO2LowerLimitOLD as nvarchar(10),@CO2HigherLimitOLD as nvarchar(10),@O2SetValueOLD as nvarchar(10),
		@O2LowerLimitOLD as nvarchar(10),@O2HigherLimitOLD as nvarchar(10),@SterilizationSetValueOLD as nvarchar(10),@SterilizationSetTimeOLD as nvarchar(10),@CO2HidePanelOLD as nvarchar(10),@Version as bigint,
		@EquipmentTypeGroup as nvarchar(20)

		Select @EquipmentTypeGroup = EquipmentTypeGroup from EquipmentMaster EM inner join EquipmentType ET on EM.EquipmentType = ET.EquipmentType 
		Where EM.EquipmentMasterId = @hdnRecordKeyId

		select 
		@EquipmentName = EquipmentName,
		@TempraturePIDKPOLD=TempraturePIDKP,
		@TempraturePIDTSOLD=TempraturePIDTS,
		@TempraturePIDTIOLD=TempraturePIDTI,
		@TempraturePIDCycleTimeOLD=TempraturePIDCycleTime,
		@TempraturePIDTDOLD=TempraturePIDTD,
		@TempraturePIDOutputPowerOLD=TempraturePIDOutputPower,
		@TempratureCoolingOLD=TempratureCooling,
		@HumidityPIDKPOLD=HumidityPIDKP,
		@HumidityPIDTSOLD=HumidityPIDTS,
		@HumidityPIDTIOLD=HumidityPIDTI,
		@HumidityPIDCycleTimeOLD=HumidityPIDCycleTime,
		@HumidityPIDTDOLD=HumidityPIDTD,
		@HumidityPIDOutputPowerOLD=HumidityPIDOutputPower,
		@HumidityCoolingOLD=HumidityCooling,
		@SetLuxValueOLD=SetLuxValue,
		@SetUVValueOLD=SetUVValue,
		@MeasuredLUXIntensityOLD=MeasuredLUXIntensity,
		@MeasuredUVIntensityOLD=MeasuredUVIntensity,
		@TempratureLowerLowerLimitOLD=TempratureLowerLowerLimit,
		@TempratureLowerLimitOLD=TempratureLowerLimit,
		@TempratureSetValueOLD=TempratureSetValue,
		@TempratureUpperLimitOLD=TempratureUpperLimit,
		@TempratureUpperUpperLimitOLD=TempratureUpperUpperLimit,
		@HumidityLowerLowerLimitOLD=HumidityLowerLowerLimit,
		@HumidityLowerLimitOLD=HumidityLowerLimit,
		@HumiditySetValueOLD=HumiditySetValue,
		@HumidityUpperLimitOLD=HumidityUpperLimit,
		@HumidityUpperUpperLimitOLD=HumidityUpperUpperLimit,	
		@TempratureLowerLimit2OLD=TempratureLowerLimit2,
		@TempratureSetValue2OLD=TempratureSetValue2,
		@TempratureUpperLimit2OLD=TempratureUpperLimit2,
		@TempratureLowerLimit3OLD=TempratureLowerLimit3,
		@TempratureSetValue3OLD=TempratureSetValue3,
		@TempratureUpperLimit3OLD=TempratureUpperLimit3,
		@TempratureLowerLimit4OLD=TempratureLowerLimit4,
		@TempratureSetValue4OLD=TempratureSetValue4,
		@TempratureUpperLimit4OLD=TempratureUpperLimit4,
		@SoakTime1OLD=SoakTime1,
		@SoakTime2OLD=SoakTime2,
		@SoakTime3OLD=SoakTime3,
		@SoakTime4OLD=SoakTime4,
		@RampTime1OLD=RampTime1,
		@RampTime2OLD=RampTime2,
		@RampTime3OLD=RampTime3,
		@RampTime4OLD=RampTime4,
		@LowerRangeOLD=LowerRange,
		@HigherRangeOLD=HigherRange,
		@SetSCHSpeedOLD=SetSCHSpeed,
		@SetSCHTimeOLD=SetSCHTime,
		@SetSCHLowAlarmOLD=SetSCHLowAlarm,
		@SetSCHHighAlarmOLD=SetSCHHighAlarm,
		@CO2SetValueOLD=CO2SetValue,
		@CO2LowerLimitOLD=CO2LowerLimit,
		@CO2HigherLimitOLD=CO2HigherLimit,
		@O2SetValueOLD=O2SetValue,
		@O2LowerLimitOLD=O2LowerLimit,
		@O2HigherLimitOLD=O2HigherLimit,
		@SterilizationSetValueOLD=SterilizationSetValue,
		@SterilizationSetTimeOLD=SterilizationSetTime,
		@Version = [Version]
		from EquipmentMaster (NoLock)
		where EquipmentMasterId=@hdnRecordKeyId	
		print 2
		begin try
			update EquipmentMaster 
			set TempraturePIDKP=@TempraturePIDKP,
			TempraturePIDTS=@TempraturePIDTS,
			TempraturePIDTI=@TempraturePIDTI,
			TempraturePIDCycleTime=@TempraturePIDCycleTime,
			TempraturePIDTD=@TempraturePIDTD,
			TempraturePIDOutputPower=@TempraturePIDOutputPower,
			TempratureCooling=@TempratureCooling,
			HumidityPIDKP=@HumidityPIDKP,
			HumidityPIDTS=@HumidityPIDTS,
			HumidityPIDTI=@HumidityPIDTI,
			HumidityPIDCycleTime=@HumidityPIDCycleTime,
			HumidityPIDTD=@HumidityPIDTD,
			HumidityPIDOutputPower=@HumidityPIDOutputPower,
			HumidityCooling=@HumidityCooling,
			SetLuxValue=@SetLuxValue,
			SetUVValue=@SetUVValue,
			MeasuredLUXIntensity=@MeasuredLUXIntensity,
			MeasuredUVIntensity=@MeasuredUVIntensity,
			TempratureLowerLowerLimit=@TempratureLowerLowerLimit,
			TempratureLowerLimit=@TempratureLowerLimit,
			TempratureSetValue=@TempratureSetValue,
			TempratureUpperLimit=@TempratureUpperLimit,
			TempratureUpperUpperLimit=@TempratureUpperUpperLimit,
			HumidityLowerLowerLimit=@HumidityLowerLowerLimit,
			HumidityLowerLimit=@HumidityLowerLimit,
			HumiditySetValue=@HumiditySetValue,
			HumidityUpperLimit=@HumidityUpperLimit,
			HumidityUpperUpperLimit=@HumidityUpperUpperLimit,	
			TempratureLowerLimit2=@TempratureLowerLimit2,
			TempratureSetValue2=@TempratureSetValue2,
			TempratureUpperLimit2=@TempratureUpperLimit2,
			TempratureLowerLimit3=@TempratureLowerLimit3,
			TempratureSetValue3=@TempratureSetValue3,
			TempratureUpperLimit3=@TempratureUpperLimit3,
			TempratureLowerLimit4=@TempratureLowerLimit4,
			TempratureSetValue4=@TempratureSetValue4,
			TempratureUpperLimit4=@TempratureUpperLimit4,
			SoakTime1=@SoakTime1,
			SoakTime2=@SoakTime2,
			SoakTime3=@SoakTime3,
			SoakTime4=@SoakTime4,
			RampTime1=@RampTime1,
			RampTime2=@RampTime2,
			RampTime3=@RampTime3,
			RampTime4=@RampTime4,
			LowerRange=@LowerRange,
			HigherRange=@HigherRange,
			SetSCHSpeed=@SetSCHSpeed,
			SetSCHTime=@SetSCHTime,
			SetSCHLowAlarm=@SetSCHLowAlarm,
			SetSCHHighAlarm=@SetSCHHighAlarm,
			CO2SetValue=@CO2SetValue,
			CO2LowerLimit=@CO2LowerLimit,
			CO2HigherLimit=@CO2HigherLimit,
			O2SetValue=@O2SetValue,
			O2LowerLimit=@O2LowerLimit,
			O2HigherLimit=@O2HigherLimit,
			NoOfCycles = @NoOfCycles,
			SterilizationSetValue=@SterilizationSetValue,
			SterilizationSetTime=@SterilizationSetTime
			where EquipmentMasterId=@hdnRecordKeyId

			if @@ROWCOUNT>0
			begin 
				print 4
				set @ReturnMessage='PARAMETER DETAILS UPDATED SUCCESSFULLY'
				set @ReturnId=@hdnRecordKeyId
				
				print @ReturnMessage

				if @TempraturePIDKPOLD<>@TempraturePIDKP
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDKP',@TempraturePIDKPOLD,@TempraturePIDKP,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDKP',@TempraturePIDKPOLD,@TempraturePIDKP,@comments,@username,''
						END
				End

				if @TempraturePIDTSOLD<>@TempraturePIDTS
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN				
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDTS',@TempraturePIDTSOLD,@TempraturePIDTS,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDTS',@TempraturePIDTSOLD,@TempraturePIDTS,@comments,@username,''
						END
				End

				if @TempraturePIDTIOLD<>@TempraturePIDTI
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDTI',@TempraturePIDTIOLD,@TempraturePIDTI,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDTI',@TempraturePIDTIOLD,@TempraturePIDTI,@comments,@username,''
						END
				End

				if @TempraturePIDCycleTimeOLD<>@TempraturePIDCycleTime
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN				
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDCycleTime',@TempraturePIDCycleTimeOLD,@TempraturePIDCycleTime,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDCycleTime',@TempraturePIDCycleTimeOLD,@TempraturePIDCycleTime,@comments,@username,''
						END
				End

				if @TempraturePIDTDOLD<>@TempraturePIDTD
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN						
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDTD',@TempraturePIDTDOLD,@TempraturePIDTD,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDTD',@TempraturePIDTDOLD,@TempraturePIDTD,@comments,@username,''
						END
				End

				if @TempraturePIDOutputPowerOLD<>@TempraturePIDOutputPower
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN					
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1PIDOutputPower',@TempraturePIDOutputPowerOLD,@TempraturePIDOutputPower,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempraturePIDOutputPower',@TempraturePIDOutputPowerOLD,@TempraturePIDOutputPower,@comments,@username,''
						END
				End

				if @TempratureCoolingOLD<>@TempratureCooling
				Begin
				
					IF @TempratureCooling = '1'
						SET @TempratureCooling = 'Yes'
					ELSE
						SET @TempratureCooling = 'No'		
						
					IF @TempratureCoolingOLD = '1'
						SET @TempratureCoolingOLD = 'Yes'
					ELSE
						SET @TempratureCoolingOLD = 'No'
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN									
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1Cooling',@TempratureCoolingOLD,@TempratureCooling,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureCooling',@TempratureCoolingOLD,@TempratureCooling,@comments,@username,''
						END
				End

				if @HumidityPIDKPOLD<>@HumidityPIDKP
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN	
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDKP',@HumidityPIDKPOLD,@HumidityPIDKP,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDKP',@HumidityPIDKPOLD,@HumidityPIDKP,@comments,@username,''
						END
				End

				if @HumidityPIDTSOLD<>@HumidityPIDTS
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN				
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDTS',@HumidityPIDTSOLD,@HumidityPIDTS,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDTS',@HumidityPIDTSOLD,@HumidityPIDTS,@comments,@username,''
						END
				End

				if @HumidityPIDTIOLD<>@HumidityPIDTI
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN										
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDTI',@TempratureCoolingOLD,@TempratureCooling,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDTI',@TempratureCoolingOLD,@TempratureCooling,@comments,@username,''
						END
				End

				if @HumidityPIDCycleTimeOLD<>@HumidityPIDCycleTime
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN	
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDCycleTime',@HumidityPIDCycleTimeOLD,@HumidityPIDCycleTime,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDCycleTime',@HumidityPIDCycleTimeOLD,@HumidityPIDCycleTime,@comments,@username,''
						END
				End

				if @HumidityPIDTDOLD<>@HumidityPIDTD
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN		
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDTD',@HumidityPIDTDOLD,@HumidityPIDTD,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDTD',@HumidityPIDTDOLD,@HumidityPIDTD,@comments,@username,''
						END
				End

				if @HumidityPIDOutputPowerOLD<>@HumidityPIDOutputPower
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN				
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2PIDOutputPower',@HumidityPIDOutputPowerOLD,@HumidityPIDOutputPower,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityPIDOutputPower',@HumidityPIDOutputPowerOLD,@HumidityPIDOutputPower,@comments,@username,''
						END
				End

				if @HumidityCoolingOLD<>@HumidityCooling
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN				
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2Cooling',@HumidityCoolingOLD,@HumidityCooling,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityCooling',@HumidityCoolingOLD,@HumidityCooling,@comments,@username,''
						END
				End

				if @SetLuxValueOLD<>@SetLuxValue
				Begin			
				EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetLuxValue',@SetLuxValueOLD,@SetLuxValue,@comments,@username,''
				End

				if @SetUVValueOLD<>@SetUVValue
				Begin			
				EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetUVValue',@SetUVValueOLD,@SetUVValue,@comments,@username,''
				End

				if @MeasuredLUXIntensityOLD<>@MeasuredLUXIntensity
				Begin			
				EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'MeasuredLUXIntensity',@MeasuredLUXIntensityOLD,@MeasuredLUXIntensity,@comments,@username,''
				End

				if @MeasuredUVIntensityOLD<>@MeasuredUVIntensity
				Begin			
				EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'MeasuredUVIntensity',@MeasuredUVIntensityOLD,@MeasuredUVIntensity,@comments,@username,''
				End

				if @TempratureLowerLowerLimitOLD<>@TempratureLowerLowerLimit
				Begin		
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1LowerLowerLimit',@TempratureLowerLowerLimitOLD,@TempratureLowerLowerLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowerLowerLimit',@TempratureLowerLowerLimitOLD,@TempratureLowerLowerLimit,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@TempratureLowerLimitOLD)<>CONVERT(decimal(18,2),@TempratureLowerLimit)
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1LowerLimit',@TempratureLowerLimitOLD,@TempratureLowerLimit,@comments,@username,''
						END
					ELSE IF (@EquipmentTypeGroup = 'TC')
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowAlarm1',@TempratureLowerLimitOLD,@TempratureLowerLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowerLimit',@TempratureLowerLimitOLD,@TempratureLowerLimit,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@TempratureSetValueOLD)<>CONVERT(decimal(18,2),@TempratureSetValue)
				Begin		
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN	
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1SetValue',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
					ELSE IF (@EquipmentTypeGroup = 'TC')
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TemperatureSetValue1',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureSetValue',@TempratureSetValueOLD,@TempratureSetValue,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@TempratureUpperLimitOLD)<>CONVERT(decimal(18,2),@TempratureUpperLimit)
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXECUTE EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1UpperLimit',@TempratureUpperLimitOLD,@TempratureUpperLimit,@comments,@username,''
						END
					ELSE IF (@EquipmentTypeGroup = 'TC')
						BEGIN
							EXECUTE EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureHighAlarm1',@TempratureUpperLimitOLD,@TempratureUpperLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXECUTE EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureUpperLimit',@TempratureUpperLimitOLD,@TempratureUpperLimit,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@TempratureUpperUpperLimitOLD)<>CONVERT(decimal(18,2),@TempratureUpperUpperLimit)
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN		
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber1UpperUpperLimit',@TempratureUpperUpperLimitOLD,@TempratureUpperUpperLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureUpperUpperLimit',@TempratureUpperUpperLimitOLD,@TempratureUpperUpperLimit,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@HumidityLowerLowerLimitOLD)<>CONVERT(decimal(18,2),@HumidityLowerLowerLimit)
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN		
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2LowerLowerLimit',@HumidityLowerLowerLimitOLD,@HumidityLowerLowerLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityLowerLowerLimit',@HumidityLowerLowerLimitOLD,@HumidityLowerLowerLimit,@comments,@username,''
						END					
				End

				if CONVERT(decimal(18,2),@HumidityLowerLimitOLD)<>CONVERT(decimal(18,2),@HumidityLowerLimit)
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2LowerLimit',@HumidityLowerLimitOLD,@HumidityLowerLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityLowerLimit',@HumidityLowerLimitOLD,@HumidityLowerLimit,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@HumiditySetValueOLD)<>CONVERT(decimal(18,2),@HumiditySetValue)
				Begin
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN			
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2SetValue',@HumiditySetValueOLD,@HumiditySetValue,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumiditySetValue',@HumiditySetValueOLD,@HumiditySetValue,@comments,@username,''
						END
				End

				if CONVERT(decimal(18,2),@HumidityUpperLimitOLD)<>CONVERT(decimal(18,2),@HumidityUpperLimit)
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN		
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2UpperLimit',@HumidityUpperLimitOLD,@HumidityUpperLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityUpperLimit',@HumidityUpperLimitOLD,@HumidityUpperLimit,@comments,@username,''
						END						
				End

				if CONVERT(decimal(18,2),@HumidityUpperUpperLimitOLD)<>CONVERT(decimal(18,2),@HumidityUpperUpperLimit)
				Begin	
					IF (@EquipmentTypeGroup = 'DC')
						BEGIN	
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Chamber2UpperUpperLimit',@HumidityUpperUpperLimitOLD,@HumidityUpperUpperLimit,@comments,@username,''
						END
					ELSE
						BEGIN
							EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HumidityUpperUpperLimit',@HumidityUpperUpperLimitOLD,@HumidityUpperUpperLimit,@comments,@username,''
						END
				End

				--if @VersionOLD<>@Version
				--Begin			
				--	EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'Version',@Version,@VersionOLD,@comments,@username,''
				--	--EXEC EquipmentMasterWrite_Manage 0,@ReturnId,
				--End

				if CONVERT(decimal(18,2),@TempratureLowerLimit2OLD)<>CONVERT(decimal(18,2),@TempratureLowerLimit2)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowerLimit2',@TempratureLowerLimit2OLD,@TempratureLowerLimit2,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureSetValue2OLD)<>CONVERT(decimal(18,2),@TempratureSetValue2)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureSetValue2',@TempratureSetValue2OLD,@TempratureSetValue2,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureUpperLimit2OLD)<>CONVERT(decimal(18,2),@TempratureUpperLimit2)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureUpperLimit2',@TempratureUpperLimit2OLD,@TempratureUpperLimit2,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureLowerLimit3OLD)<>CONVERT(decimal(18,2),@TempratureLowerLimit3)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowerLimit3',@TempratureLowerLimit3OLD,@TempratureLowerLimit3,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureSetValue3OLD)<>CONVERT(decimal(18,2),@TempratureSetValue3)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureSetValue3',@TempratureSetValue3OLD,@TempratureSetValue3,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureUpperLimit3OLD)<>CONVERT(decimal(18,2),@TempratureUpperLimit3)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureUpperLimit3',@TempratureUpperLimit3OLD,@TempratureUpperLimit3,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureLowerLimit4OLD)<>CONVERT(decimal(18,2),@TempratureLowerLimit4)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureLowerLimit4',@TempratureLowerLimit4OLD,@TempratureLowerLimit4,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureSetValue4OLD)<>CONVERT(decimal(18,2),@TempratureSetValue4)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureSetValue4',@TempratureSetValue4OLD,@TempratureSetValue4,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@TempratureUpperLimit4OLD)<>CONVERT(decimal(18,2),@TempratureUpperLimit4)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'TempratureUpperLimit4',@TempratureUpperLimit4OLD,@TempratureUpperLimit4,@comments,@username,''
				End

				if  @SoakTime1OLD<> @SoakTime1
				Begin		
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SoakTime1',@SoakTime1OLD,@SoakTime1,@comments,@username,''
				End

				if  @SoakTime2OLD<> @SoakTime2
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SoakTime2',@SoakTime2OLD,@SoakTime2,@comments,@username,''
				End

				if  @SoakTime3OLD<> @SoakTime3
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SoakTime3',@SoakTime3OLD,@SoakTime3,@comments,@username,''
				End

				if  @SoakTime4OLD<> @SoakTime4
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SoakTime4',@SoakTime4OLD,@SoakTime4,@comments,@username,''
				End

				if  @RampTime1OLD<> @RampTime1
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'RampTime1',@RampTime1OLD,@RampTime1,@comments,@username,''
				End

				if  @RampTime2OLD<> @RampTime2
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'RampTime2',@RampTime2OLD,@RampTime2,@comments,@username,''
				End

				if  @RampTime3OLD<> @RampTime3
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'RampTime3',@RampTime3OLD,@RampTime3,@comments,@username,''
				End

				if  @RampTime4OLD<> @RampTime4
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'RampTime4',@RampTime4OLD,@RampTime4,@comments,@username,''
				End

				if  @LowerRangeOLD<> @LowerRange
				Begin		
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'LowerRange',@LowerRangeOLD,@LowerRange,@comments,@username,''
				End

				if CONVERT(decimal(18,2),@HigherRangeOLD)<>CONVERT(decimal(18,2),@HigherRange)
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'HigherRange',@HigherRangeOLD,@HigherRange,@comments,@username,''
				End

				if @SetSCHSpeedOLD<>@SetSCHSpeed
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetSCHSpeed',@SetSCHSpeedOLD,@SetSCHSpeed,@comments,@username,''
				End

				if @SetSCHTimeOLD<>@SetSCHTime
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetSCHTime',@SetSCHTimeOLD,@SetSCHTime,@comments,@username,''
				End

				if @SetSCHLowAlarmOLD<>@SetSCHLowAlarm
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetSCHLowAlarm',@SetSCHLowAlarmOLD,@SetSCHLowAlarm,@comments,@username,''
				End

				if @SetSCHHighAlarmOLD<>@SetSCHHighAlarm
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SetSCHHighAlarm',@SetSCHHighAlarmOLD,@SetSCHHighAlarm,@comments,@username,''
				End

				if @CO2SetValueOLD<>@CO2SetValue
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'CO2SetValue',@CO2SetValueOLD,@CO2SetValue,@comments,@username,''
				End

				if @CO2LowerLimitOLD<>@CO2LowerLimit
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'CO2LowerLimit',@CO2LowerLimitOLD,@CO2LowerLimit,@comments,@username,''
				End

				if @CO2HigherLimitOLD<>@CO2HigherLimit
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'CO2HigherLimit',@CO2HigherLimitOLD,@CO2HigherLimit,@comments,@username,''
				End

				if @O2SetValueOLD<>@O2SetValue
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'O2SetValue',@O2SetValueOLD,@O2SetValue,@comments,@username,''
				End

				if @O2LowerLimitOLD<>@O2LowerLimit
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'O2LowerLimit',@O2LowerLimitOLD,@O2LowerLimit,@comments,@username,''
				End

				if @O2HigherLimitOLD<>@O2HigherLimit
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'O2HigherLimit',@O2HigherLimitOLD,@O2HigherLimit,@comments,@username,''
				End

				if @SterilizationSetValueOLD<>@SterilizationSetValue
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SterilizationSetValue',@SterilizationSetValueOLD,@SterilizationSetValue,@comments,@username,''
				End

				if @SterilizationSetTimeOLD<>@SterilizationSetTime
				Begin			
					EXEC EquipmentMasterAuditTrail_Manage @ReturnId,@EquipmentName,'SterilizationSetTime',@SterilizationSetTimeOLD,@SterilizationSetTime,@comments,@username,''
				End
			end

			print 'hhh'+ @ReturnMessage 
		end try
		begin catch
			set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
			print @ReturnMessage
		end catch
	
	end try
	begin catch
		set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
		print @ReturnMessage
	end catch
	
end
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMaster_Update_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--select * from EquipmentMaster
-- Execute EquipmentMaster_Update '165','0','0','0','0','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0.0','0','35','0','0.0','0.0','0','0','0','0.0','0','0','0','0','0','0','0','0','0',':',':',':',':','0','0','0','0','0','0','0','0','0','0','0','0','0','35','35','35','0','0','','53','Administrator','','0'
CREATE PROCEDURE [dbo].[EquipmentMaster_Update_Service]
	@hdnRecordKeyId AS BIGINT=0,	
	@ActiveChannel as tinyint=0,
	@EquipmnetType as nvarchar(10) = '',
	@EquipmnetLogRate as smallint=0,
	@TempraturePIDKP as nvarchar(10) = '',
	@TempraturePIDTS as nvarchar(10) = '',
	@TempraturePIDTI as nvarchar(10) = '',
	@TempraturePIDCycleTime as nvarchar(10) = '',
	@TempraturePIDTD as nvarchar(10) = '',
	@TempraturePIDOutputPower as nvarchar(10) = '',
	@TempratureCooling as nvarchar(10) = '',
	@HumidityPIDKP as nvarchar(10) = '',
	@HumidityPIDTS as nvarchar(10) = '',
	@HumidityPIDTI as nvarchar(10) = '',
	@HumidityPIDCycleTime as nvarchar(10) = '',
	@HumidityPIDTD as nvarchar(10) = '',
	@HumidityPIDOutputPower as nvarchar(10) = '',
	@HumidityCooling as nvarchar(10) = '',
	@SetLuxValue as nvarchar(10) = '',
	@SetUVValue as nvarchar(10) = '',
	@MeasuredLUXIntensity as nvarchar(10) = '',
	@MeasuredUVIntensity as nvarchar(10) = '',
	@TempratureLowerLowerLimit as nvarchar(10) = '',
	@TempratureLowerLimit as nvarchar(10) = '',
	@TempratureSetValue as nvarchar(10) = '',
	@TempratureUpperLimit as nvarchar(10) = '',
	@TempratureUpperUpperLimit as nvarchar(10) = '',
	@HumidityLowerLowerLimit as nvarchar(10) = '',
	@HumidityLowerLimit as nvarchar(10) = '',
	@HumiditySetValue as nvarchar(10) = '',
	@HumidityUpperLimit as nvarchar(10) = '',
	@HumidityUpperUpperLimit as nvarchar(10) = '',
	@TempratureLowerLimit2 as nvarchar(10) = '',
	@TempratureSetValue2 as nvarchar(10) = '',
	@TempratureUpperLimit2 as nvarchar(10) = '',
	@TempratureLowerLimit3 as nvarchar(10) = '',
	@TempratureSetValue3 as nvarchar(10) = '',
	@TempratureUpperLimit3 as nvarchar(10) = '',
	@TempratureLowerLimit4 as nvarchar(10) = '',
	@TempratureSetValue4 as nvarchar(10) = '',
	@TempratureUpperLimit4 as nvarchar(10) = '',
	@SoakTime1 as nvarchar(10) = '',
	@SoakTime2 as nvarchar(10) = '',
	@SoakTime3 as nvarchar(10) = '',
	@SoakTime4 as nvarchar(10) = '',
	@RampTime1 as nvarchar(10) = '',
	@RampTime2 as nvarchar(10) = '',
	@RampTime3 as nvarchar(10) = '',
	@RampTime4 as nvarchar(10) = '',
	@LowerRange as nvarchar(10) = '',
	@HigherRange as nvarchar(10) = '',
	@SetSCHSpeed as nvarchar(10) = '',
	@SetSCHTime as nvarchar(10) = '',
	@SetSCHLowAlarm as nvarchar(10) = '',
	@SetSCHHighAlarm as nvarchar(10) = '',
	@CO2SetValue as nvarchar(10) = '',
	@CO2LowerLimit as nvarchar(10) = '',
	@CO2HigherLimit as nvarchar(10) = '',
	@O2SetValue as nvarchar(10) = '',
	@O2LowerLimit as nvarchar(10) = '',
	@O2HigherLimit as nvarchar(10) = '',
	@SterilizationSetValue as nvarchar(10) = '',
	@SterilizationSetTime as nvarchar(10) = '',
	@NoOfCycles as nvarchar(10) = '',	
	@Version as nvarchar(10) = '',
	@EquipmentTypeId as tinyint = 0,
	@CO2HidePanel as nvarchar(10) = '',
	@username as varchar(100)='',
	@CompanyId as bigint=0,
	@EquipmnetPLCCode as nvarchar(10) = '',
	@ReturnMessage AS VARCHAR(100)=''  OUTPUT,
	@ReturnId AS BIGINT =0 OUTPUT


as
SET NOCOUNT ON;
BEGIN
	begin try
		print 1
		
			if @ActiveChannel = NULL
				SET @ActiveChannel =''
				
				
			if @EquipmnetLogRate = NULL
				SET @EquipmnetLogRate = ''
			
			if @TempraturePIDKP = NULL
				SET @TempraturePIDKP=''

			if @TempraturePIDTS = NULL
				SET @TempraturePIDTS=''

			if @TempraturePIDTI = NULL
				SET @TempraturePIDTI=''

			if @TempraturePIDCycleTime = NULL
				SET @TempraturePIDCycleTime=''

			if @TempraturePIDTD = NULL
				SET @TempraturePIDTD=''

			if @TempraturePIDOutputPower = NULL
				SET @TempraturePIDOutputPower=''

			if @TempratureCooling = NULL
				SET @TempratureCooling=''

			if @HumidityPIDKP = NULL
				SET @HumidityPIDKP=''

			if @HumidityPIDTS = NULL
				SET @HumidityPIDTS=''

			if @HumidityPIDTI = NULL
				SET @HumidityPIDTI=''

			if @HumidityPIDCycleTime = NULL
				SET @HumidityPIDCycleTime=''
		 
			if @HumidityPIDTD = NULL
				SET @HumidityPIDTD=''

			if @HumidityPIDOutputPower = NULL
				SET @HumidityPIDOutputPower=''

			if @HumidityCooling = NULL
				SET @HumidityCooling=''

			if @SetLuxValue = NULL
				SET @SetLuxValue=''

			if @SetUVValue = NULL
				SET @SetUVValue=''

			if @MeasuredLUXIntensity = NULL
				SET @MeasuredLUXIntensity=''

			if @MeasuredUVIntensity = NULL
				SET @MeasuredUVIntensity=''

			if @TempratureLowerLowerLimit = NULL
				SET @TempratureLowerLowerLimit='0:0'

			if @TempratureLowerLimit = NULL
				SET @TempratureLowerLimit='0:0'

			if @TempratureSetValue = NULL
				SET @TempratureSetValue='0:0'

			if @TempratureUpperLimit = NULL
				SET @TempratureUpperLimit='0:0'

			if @TempratureUpperUpperLimit = NULL
				SET @TempratureUpperUpperLimit='0:0'

			if @HumidityLowerLowerLimit = NULL
				SET @HumidityLowerLowerLimit='0:0'

			if @HumidityLowerLimit = NULL
				SET @HumidityLowerLimit='0:0'

			if @HumiditySetValue = NULL
				SET @HumiditySetValue='0:0'

			if @HumidityUpperLimit = NULL
				SET @HumidityUpperLimit='0:0'

			if @HumidityUpperUpperLimit = NULL
				SET @HumidityUpperUpperLimit='0:0'
	
			if @TempratureLowerLimit2 = NULL
				SET @TempratureLowerLimit2='0:0'

			if @TempratureSetValue2 = NULL
				SET @TempratureSetValue2='0:0'

			if @TempratureUpperLimit2 = NULL
				SET @TempratureUpperLimit2='0:0'

			if @TempratureLowerLimit3 = NULL
				SET @TempratureLowerLimit3='0:0'

			if @TempratureSetValue3 = NULL
				SET @TempratureSetValue3='0:0'

			if @TempratureUpperLimit3 = NULL
				SET @TempratureUpperLimit3='0:0'

			if @TempratureLowerLimit4 = NULL
				SET @TempratureLowerLimit4='0:0'

			if @TempratureSetValue4 = NULL
				SET @TempratureSetValue4='0:0'

			if @TempratureUpperLimit4 = NULL
				SET @TempratureUpperLimit4='0:0'

			if @SoakTime1 = NULL
				SET @SoakTime1='0:0'

			if @SoakTime2 = NULL
				SET @SoakTime2='0:0'

			if @SoakTime3 = NULL
				SET @SoakTime3='0:0'
		
			if @SoakTime4 = NULL
				SET @SoakTime4='0:0'

			if @RampTime1 = NULL
				SET @RampTime1='0'

			if @RampTime2 = NULL
				SET @RampTime2='0'

			if @RampTime3 = NULL
				SET @RampTime3='0'

			if @RampTime4 = NULL
				SET @RampTime4='0'

			if @LowerRange = NULL
				SET @LowerRange='0:0'

			if @HigherRange = NULL
				SET @HigherRange='0:0'

			if @SetSCHSpeed = NULL
				SET @SetSCHSpeed=''

			if @SetSCHTime = NULL
				SET @SetSCHTime=''

			if @SetSCHLowAlarm = NULL
				SET @SetSCHLowAlarm=''

			if @SetSCHHighAlarm = NULL
				SET @SetSCHHighAlarm=''

			if @CO2SetValue = NULL
				SET @CO2SetValue=''

			if @CO2LowerLimit = NULL
				SET @CO2LowerLimit=''

			if @CO2HigherLimit = NULL
				SET @CO2HigherLimit=''

			if @O2SetValue = NULL
				SET @O2SetValue=''

			if @O2LowerLimit = NULL
				SET @O2LowerLimit=''

			if @O2HigherLimit = NULL
				SET @O2HigherLimit=''

			if @SterilizationSetValue = NULL
				SET @SterilizationSetValue=''

			if @SterilizationSetTime = NULL
				SET @SterilizationSetTime=''
		 	
			if @NoOfCycles = NULL
				SET @NoOfCycles='0'
				
			if @Version = NULL
				SET @Version = '0'
				
			if @EquipmentTypeId = NULL
				SET @EquipmentTypeId = '0'
				
			if @CO2HidePanel = NULL
				SET @CO2HidePanel = '0'
	
	
	begin try
	
	Select @EquipmentTypeId = EquipmentTypeId,@EquipmnetType = EquipmentType From EquipmentType where EquipmentPLCCode = @EquipmnetPLCCode 
	
		update EquipmentMaster 
		set ActiveChannel =@ActiveChannel ,
		EquipmentType = @EquipmnetType,
		EquipmnetLogRate = @EquipmnetLogRate,
		TempraturePIDKP=@TempraturePIDKP,
		TempraturePIDTS=@TempraturePIDTS,
		TempraturePIDTI=@TempraturePIDTI,
		TempraturePIDCycleTime=@TempraturePIDCycleTime,
		TempraturePIDTD=@TempraturePIDTD,
		TempraturePIDOutputPower=@TempraturePIDOutputPower,
		TempratureCooling=@TempratureCooling,
		HumidityPIDKP=@HumidityPIDKP,
		HumidityPIDTS=@HumidityPIDTS,
		HumidityPIDTI=@HumidityPIDTI,
		HumidityPIDCycleTime=@HumidityPIDCycleTime,
		HumidityPIDTD=@HumidityPIDTD,
		HumidityPIDOutputPower=@HumidityPIDOutputPower,
		HumidityCooling=@HumidityCooling,
		SetLuxValue=@SetLuxValue,
		SetUVValue=@SetUVValue,
		MeasuredLUXIntensity=@MeasuredLUXIntensity,
		MeasuredUVIntensity=@MeasuredUVIntensity,
		TempratureLowerLowerLimit=@TempratureLowerLowerLimit,
		TempratureLowerLimit=@TempratureLowerLimit,
		TempratureSetValue=@TempratureSetValue,
		TempratureUpperLimit=@TempratureUpperLimit,
		TempratureUpperUpperLimit=@TempratureUpperUpperLimit,
		HumidityLowerLowerLimit=@HumidityLowerLowerLimit,
		HumidityLowerLimit=@HumidityLowerLimit,
		HumiditySetValue=@HumiditySetValue,
		HumidityUpperLimit=@HumidityUpperLimit,
		HumidityUpperUpperLimit=@HumidityUpperUpperLimit,	
		TempratureLowerLimit2=@TempratureLowerLimit2,
		TempratureSetValue2=@TempratureSetValue2,
		TempratureUpperLimit2=@TempratureUpperLimit2,
		TempratureLowerLimit3=@TempratureLowerLimit3,
		TempratureSetValue3=@TempratureSetValue3,
		TempratureUpperLimit3=@TempratureUpperLimit3,
		TempratureLowerLimit4=@TempratureLowerLimit4,
		TempratureSetValue4=@TempratureSetValue4,
		TempratureUpperLimit4=@TempratureUpperLimit4,
		SoakTime1=@SoakTime1,
		SoakTime2=@SoakTime2,
		SoakTime3=@SoakTime3,
		SoakTime4=@SoakTime4,
		RampTime1=@RampTime1,
		RampTime2=@RampTime2,
		RampTime3=@RampTime3,
		RampTime4=@RampTime4,
		LowerRange=@LowerRange,
		HigherRange=@HigherRange,
		SetSCHSpeed=@SetSCHSpeed,
		SetSCHTime=@SetSCHTime,
		SetSCHLowAlarm=@SetSCHLowAlarm,
		SetSCHHighAlarm=@SetSCHHighAlarm,
		CO2SetValue=@CO2SetValue,
		CO2LowerLimit=@CO2LowerLimit,
		CO2HigherLimit=@CO2HigherLimit,
		O2SetValue=@O2SetValue,
		O2LowerLimit=@O2LowerLimit,
		O2HigherLimit=@O2HigherLimit,
		NoOfCycles = @NoOfCycles,
		SterilizationSetValue=@SterilizationSetValue,
		SterilizationSetTime=@SterilizationSetTime,
		Version =@Version,
		EquipmentTypeId = @EquipmentTypeId ,
		CO2HidePanel = @CO2HidePanel 
		where EquipmentMasterId=@hdnRecordKeyId



	if @@ROWCOUNT>0
	begin 
	print 4
		set @ReturnMessage='Update Successful'
		set @ReturnId=@hdnRecordKeyId
		exec EquipmentMaster_List_Service @CompanyId,@hdnRecordKeyId
		print @ReturnMessage
	end
	end try
	begin catch
		set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
		print @ReturnMessage
	end catch
	
	end try
	begin catch
		set @ReturnMessage = ERROR_MESSAGE() + ERROR_LINE()
		print @ReturnMessage
	end catch
	
end

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMasterAlarmAuditTrail_List 68,3,'','2019/01/01 00:00','2019/01/31 23:59'
CREATE Procedure [dbo].[EquipmentMasterAlarmAuditTrail_List]
 @RecordKeyId as bigint=0,
 @BranchId as bigint = 0,
 @AlarmType as nvarchar(5) = '',
 @ReportFromDate as Datetime ='',
 @ReportToDate as Datetime=''
As 
Begin
	SET NOCOUNT ON;	
	begin			
		select EquipmentMasterAlarmAuditTrailId,
		(Convert(varchar, AlarmLogDateTime, 105) + ' ' + substring(convert(varchar(8), AlarmLogDateTime, 108), 0, 9)) As AlarmLogDateTime
		,AlarmEvent,
		(CASE WHEN AlarmType = 'A' THEN 'ALARM' 
		     WHEN AlarmType = 'N' THEN 'NOTIFICATION'
			 WHEN AlarmType = 'E' THEN 'EVENT' END) AS AlarmType
		 from EquipmentMasterAlarmAuditTrail (NOLOCK) AS EAT 
		INNER JOIN EquipmentMaster (NOLOCK) AS EM ON EAT.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId = @BranchId 
		AND EAT.EquipmentMasterId = @RecordKeyId 
		AND EAT.AlarmLogDateTime BETWEEN @ReportFromDate AND @ReportToDate
		and [AckUserId] is null
		and (@AlarmType = '' or AlarmType=@AlarmType)
	end	
End

--select *from EquipmentMasterAlarmAuditTrail
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

--Exec [AlarmAuditTrail_rpt] '2009-10-17','00','00','2014-10-17','23','57','1,2'
--Exec [EquipmentMasterAlarmAuditTrail_ListData] 64,3
CREATE PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_ListData]
	@EquipmentMasterId as bigint=0
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @strQuery AS VARCHAR(4000)
	
	SET @strQuery=' SELECT DML.EquipmentMasterAlarmAuditTrailId,DML.EquipmentMasterId,AlarmLogDateTime
	,AlarmEvent,ReviewedApprovedStatus,DM.EquipmentName ,DML.AckDatetime,DML.AckComments,DML.AckUserId as UserId
	FROM EquipmentMasterAlarmAuditTrail AS DML inner join EquipmentMaster as DM on DM.EquipmentMasterId=DML.EquipmentMasterId 
	WHERE DML.EquipmentMasterAlarmAuditTrailId >0 '
	
	
	IF @EquipmentMasterId<>0
		BEGIN
			SET @strQuery = @strQuery + ' AND  DML.EquipmentMasterId in (select * from CSVTOTable('''+cast(@EquipmentMasterId as varchar(4000))+''')) '
		END

	
	SET @strQuery = @strQuery +' And AckUserId IS NULL ORDER BY  DML.AlarmLogDateTime '
	PRINT(@strQuery)
	exec(@strQuery)
	
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterAlarmAuditTrail_Sync] 3,'2016-01-01 00:00:00.000'
CREATE PROCEDURE [dbo].[EquipmentMasterAlarmAuditTrail_Sync]
	@BranchId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record

--SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterAlarmAuditTrail ON
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMasterAlarmAuditTrail
			([EquipmentMasterAlarmAuditTrailId],[EquipmentMasterId],[EquipmentName],[AlarmLogDateTime],[AlarmEvent],[AckDatetime],[AckComments],[ReviewedApprovedStatus],[EmailStatus],[SMSStatus],[AlarmType],[AckUserId],[AlarmInfo])
		select
			SourceDBTable.[EquipmentMasterAlarmAuditTrailId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[EquipmentName],SourceDBTable.[AlarmLogDateTime] ,SourceDBTable.[AlarmEvent]
			,SourceDBTable.[AckDatetime],SourceDBTable.[AckComments] ,SourceDBTable.[ReviewedApprovedStatus],SourceDBTable.[EmailStatus],SourceDBTable.[SMSStatus]
			,SourceDBTable.[AlarmType],SourceDBTable.[AckUserId],SourceDBTable.[AlarmInfo]
		from EquipmentMasterAlarmAuditTrail(NOLOCK) SourceDBTable inner join EquipmentMaster(NOLOCK) EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND AlarmLogDateTime <= @LogDateTime 
		AND not exists	(
			 select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterAlarmAuditTrail(NOLOCK) DestinationDBTable
						 where DestinationDBTable.EquipmentMasterAlarmAuditTrailId = SourceDBTable.EquipmentMasterAlarmAuditTrailId
						 )
						 
--SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterAlarmAuditTrail OFF

						 
--Delete Record	
		
		Delete From EquipmentMasterAlarmAuditTrail Where AlarmLogDateTime<=@LogDateTime
		And EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@BranchId )
		
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmAuditTrail_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMasterAlarmAuditTrail_Update 2,'Administrator','','',0
CREATE Procedure [dbo].[EquipmentMasterAlarmAuditTrail_Update]
 @EquipmentMasterAlarmAuditTrailId as bigint=0,
 @AckUserId AS NVARCHAR(100) ='',
 @AckComments AS NVARCHAR(255)='',
 @ReturnMessage AS NVARCHAR(1000)='' OUTPUT,
 @ReturnId AS BIGINT=0 OUTPUT
As 
Begin
	SET NOCOUNT ON;	
	begin			
		UPDATE EquipmentMasterAlarmAuditTrail SET AckUserId=@AckUserId ,AckComments=@AckComments ,AckDatetime=GETDATE() 
		WHERE EquipmentMasterAlarmAuditTrailId=@EquipmentMasterAlarmAuditTrailId
		IF @@ROWCOUNT>0		
		BEGIN
		
			SET @ReturnMessage='ALARM LOG ACKNOWLEDGED SUCCESSFULLY !!'
			SET @ReturnId = @EquipmentMasterAlarmAuditTrailId
		END
		ELSE		
			SET @ReturnMessage='ALARM LOG ACKNOWLEDGED FAILED !!'
			SET @ReturnId = 0
	end	
End

--select *from EquipmentMasterAlarmAuditTrail
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLog_LastLogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC EquipmentMasterLog_LastLogDateTime 68
CREATE Procedure [dbo].[EquipmentMasterAlarmLog_LastLogDateTime]
 @EquipmentMasterId as bigint = 0
As 
Begin
	SET NOCOUNT ON;
    
    select top 1 AlarmLogDateTime from EquipmentMasterAlarmAuditTrail 
    where EquipmentMasterId = @EquipmentMasterId
    order by AlarmLogDateTime desc
End



GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLogManage_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [EquipmentMasterAlarmLogManage_Service] '5','<AlarmLog><AlarmLog><EquipmentMasterId>5</EquipmentMasterId><EquipmentName>Equipment_175</EquipmentName><AlarmLogDateTime>2018/09/12 12:13</AlarmLogDateTime><AlarmEvent>TEMP 1 HIGH ALARM</AlarmEvent><AlarmCode>1</AlarmCode><ParameterNo>1</ParameterNo><AlarmType>A</AlarmType></AlarmLog></AlarmLog>'

CREATE PROCEDURE [dbo].[EquipmentMasterAlarmLogManage_Service]

@EquipmentMasterId nvarchar(10),
@xml XML,
@ReturnId AS BIGINT =0 OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
	  Declare @strQuery as Varchar(max), @strQuery1 as Varchar(max),
	  @EmailSystem as nvarchar(5),@SMSSystem as nvarchar(5)
	  
	  Select @EmailSystem=EmailSystem,@SMSSystem=SMSSystem From App_ApplicationSetup

	  Delete From EquipmentMasterAlarmAuditTrail_Temp where EquipmentMasterId=@EquipmentMasterId
	  Begin try	 
	  INSERT INTO EquipmentMasterAlarmAuditTrail_Temp  (EquipmentMasterId,EquipmentName,AlarmLogDateTime,AlarmEvent,AlarmType,AlarmCode,ParameterNo)
      SELECT
      DataLog.value('(EquipmentMasterId/text())[1]','BigInt') AS EquipmentMasterId,
      DataLog.value('(EquipmentName/text())[1]','nvarchar(255)') AS EquipmentName,
      DataLog.value('(AlarmLogDateTime/text())[1]','DateTime') AS AlarmLogDateTime,
	  DataLog.value('(AlarmEvent/text())[1]','nvarchar(255)') AS AlarmEvent,
	  DataLog.value('(AlarmType/text())[1]','nvarchar(255)') AS AlarmType,
	  DataLog.value('(AlarmCode/text())[1]','nchar(10)') AS AlarmCode,
	  DataLog.value('(ParameterNo/text())[1]','nchar(10)') AS ParameterNo
      FROM
      @xml.nodes('/AlarmLog/AlarmLog')AS TEMPTABLE(DataLog)


		Set @strQuery = 'INSERT INTO EquipmentMasterAlarmAuditTrail(EquipmentMasterId,EquipmentName,AlarmLogDateTime,AlarmEvent,AlarmType,AlarmInfo,EmailStatus,SMSStatus)
		SELECT  ET.EquipmentMasterId,ET.EquipmentName,ET.AlarmLogDateTime,ET.AlarmEvent,ET.AlarmType,AI.AlarmInfo,
		Case When ' + @EmailSystem + ' = 1 Then 3 Else Case When EM.EquipmentAlarmConfigId Is NULL Then 3 Else 0 End End,
		Case When ' + @SMSSystem + ' = 1 Then 3 Else Case When SM.EquipmentAlarmConfigId Is NULL Then 3 Else 0 End End
		FROM EquipmentMasterAlarmAuditTrail_Temp(nolock) ET 
		Outer Apply
		(
			Select EquipmentAlarmConfigId From EquipmentAlarmConfig EAC
			Inner Join AlarmCodeLookUp ACL ON ACL.AlarmCodeLookUpId=EAC.AlarmCodeLookUpId
			Where ACL.AlarmCode=ET.AlarmCode AND AlarmType=''E''
		)EM
		Outer Apply
		(
			Select EquipmentAlarmConfigId From EquipmentAlarmConfig EAC
			Inner Join AlarmCodeLookUp ACL ON ACL.AlarmCodeLookUpId=EAC.AlarmCodeLookUpId
			Where ACL.AlarmCode=ET.AlarmCode AND AlarmType=''S''
		)SM
		Outer Apply
		(
			Select (CASE WHEN CHARINDEX(ET.AlarmEvent,''CHAMBER 1'') > 0 THEN ''~Chamber 1~SV='' + EM.TempratureSetValue + ''~PV1='' + ET.ParameterNo
						WHEN CHARINDEX(ET.AlarmEvent,''CHAMBER 2'') > 0 THEN ''~Chamber 2~SV='' + EM.HumiditySetValue + ''~PV2='' + ET.ParameterNo
						WHEN CHARINDEX(ET.AlarmEvent,''RH'') > 0 THEN ''~Humidity~SV='' + EM.HumiditySetValue + ''~PV2='' + ET.ParameterNo
					ELSE ''~Temperature~SV='' + EM.TempratureSetValue + ''~PV1='' + ET.ParameterNo END) As AlarmInfo
			From  EquipmentMaster EM
			Where EM.EquipmentMasterId=ET.EquipmentMasterId
		)AI
		Where  
		not exists (
			select EquipmentMasterAlarmAuditTrailId from EquipmentMasterAlarmAuditTrail(nolock) EAT 
			Where EAT.EquipmentMasterId = ET.EquipmentMasterId 
			And EAT.AlarmLogDateTime= ET.AlarmLogDateTime
			AND EAT.AlarmEvent = ET.AlarmEvent
		)
		AND ET.EquipmentMasterId =' + @EquipmentMasterId + ' Order by ET.AlarmLogDateTime ASC' 

      --Set @strQuery = 'INSERT INTO EquipmentMasterAlarmAuditTrail(EquipmentMasterId,AlarmLogDateTime,AlarmEvent)'
      --Set @strQuery1= 'SELECT Distinct ET.EquipmentMasterId,ET.AlarmLogDateTime,ET.AlarmEvent 
						--				from EquipmentMasterAlarmAuditTrail_Temp(nolock) ET Where Not Exists (Select AlarmLogDateTime From EquipmentMasterAlarmAuditTrail (NoLock) E where E.AlarmEvent = ET.AlarmEvent) and EquipmentMasterId = ' + @EquipmentMasterId + ' Order by AlarmLogDateTime ASC'
	   exec (@strQuery)
	    if @@ROWCOUNT > 0
		   Begin
			   Set @ReturnId=@@Rowcount
			   print @ReturnId
		   End
	   else
		   Begin
			   Set @ReturnId=0
			   print @ReturnId
		   End
	   end try
		begin catch
			Set @ReturnId=0
			print @ReturnId
		end catch
	   

  
END




GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAlarmLookUp_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[EquipmentMasterAlarmLookUp_Service] 'DC','1001'
CREATE PROCEDURE [dbo].[EquipmentMasterAlarmLookUp_Service]
@EquipmentTypeGroup nvarchar(5)= '',
@CompanyCode nvarchar(10)= ''
AS
SET nocount on;
BEGIN	
	Declare @CompanyId as nvarchar(10),@AlarmLookUpId as nvarchar(10)

	Select @CompanyId= BranchId from EquipmentMaster where CompanyCode = @CompanyCode

	Select AC.AlarmCodeLookUpId,AC.AlarmDescription,AC.EquipmentTypeGroup,Ac.AlarmCode ,ACE .AlarmType,Ac.ParameterNo  from AlarmCodeLookUp AC (NOLOCK)
	inner join App_Company_AlarmEvent ACE on  ACE.AlarmCodeLookUpId = AC.AlarmCodeLookUpId 
	where ((',' + AC.EquipmentTypeGroup + ',') like '%,' + @EquipmentTypeGroup + ',%') 
	and CompanyId = @CompanyId
	print(@CompanyId)

	

END
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_LookUp_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[App_UserGroup_Populate] 1
CREATE  Procedure [dbo].[EquipmentMasterAuditTrail_LookUp_Populate]
As 
Begin
	SET NOCOUNT ON;
           
    SELECT Code,Replace (Comments ,'{Name}','') as Comments
	FROM EquipmentMasterAuditTrail_LookUp (NoLock)
	Order By Comments

End


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec EquipmentMasterAuditTrail_Manage 24,'EQUIPMENT - HCT','NEWE','','','','TEST','admin'
CREATE PROCEDURE [dbo].[EquipmentMasterAuditTrail_Manage]
@EquipmentMasterId as bigint=0,
@EquipmentName as nvarchar(50),
@Parameter as nvarchar(150)='',
@ParameterOldValue as  nvarchar(255)='',
@ParameterNewValue as  nvarchar(255)='',
@Comments as  nvarchar(250)='',
@Username as nvarchar(100)='',
@ReturnMessage as NVARCHAR(255)=''  output
AS
Begin

	begin try		
		DECLARE @CompanyId as bigint,@LookUpComments as nvarchar(500)
		
		SELECT @CompanyId = BranchId FROM EquipmentMaster(NOLOCK) where EquipmentMasterId = @EquipmentMasterId
		SELECT @LookUpComments=Comments FROM  EquipmentMasterAuditTrail_LookUp(NOLOCK) WHERE Code like @Parameter
		
		if @@ROWCOUNT>0
			BEGIN			
				insert into EquipmentMasterAuditTrail (CompanyId,EquipmentMasterId,EquipmentName,AuditTrailDate, Parameter,ParameterOldValue,ParameterNewValue,Comments,UserName)
				VALUES
				( @CompanyId,@EquipmentMasterId ,@EquipmentName,GetDate(),@LookUpComments,@ParameterOldValue,@ParameterNewValue,@Comments,@Username) 
			END
		ELSE
			BEGIN			
				insert into EquipmentMasterAuditTrail (CompanyId,EquipmentMasterId,EquipmentName,AuditTrailDate, Parameter,ParameterOldValue,ParameterNewValue,Comments,UserName)
				VALUES(@CompanyId,@EquipmentMasterId ,@EquipmentName,GetDate(),@Parameter,@ParameterOldValue,@ParameterNewValue,@Comments,@Username) 
			END
		
	end try
	begin catch
		SET @ReturnMessage = dbo.RemoveSpecialChars(Error_Message())
	end catch;	
	
	
End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
	
--EXECUTE  [EquipmentMasterAuditTrail_Rpt]  3,36,'2019/12/09 00:00','2019/12/09 23:59','','','EQUIPMENT STATUS UPDATED SUCCESSFULLY',0,0
CREATE PROCEDURE [dbo].[EquipmentMasterAuditTrail_Rpt] 
	@CompanyId as nvarchar(100)='',
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@UserList AS varchar(4000)='',
	@EquipmentList AS varchar(4000)='',
	@FilterParameter AS varchar(4000)='',	
	@OrderBy as tinyint=0,
	@GroupBy as tinyint = 0
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @strQuery AS VARCHAR(8000)

	SET @strQuery = ' SELECT ROW_NUMBER() OVER (ORDER BY CASE ' + CAST(@OrderBy AS NVARCHAR(25)) + ' WHEN 0 THEN AuditTrailDate ELSE EquipmentMasterId END ASC) AS [Sr No], 
	Convert(varchar, AuditTrailDate, 105) As [Log Date],substring(convert(varchar(8), AuditTrailDate, 108), 0, 6) As [Log Time],EquipmentName as [Equipment Name]
	,UserName as [Login Name],Parameter as [Parameter],ParameterOldValue as [Old Status] , ParameterNewValue as [New Status],Comments AS [Comments]  	
	FROM EquipmentMasterAuditTrail (NOLOCK) '
	
	SET @strQuery = @strQuery + ' WHERE CompanyId IN (select * from dbo.CSVToTable(''' + CAST(@CompanyId AS NVARCHAR(100)) + '''))'
	
	SET @strQuery = @strQuery + ' AND (AuditTrailDate BETWEEN ''' + CAST(@ReportFromDate AS NVARCHAR(25)) + ''' AND ''' +  CAST(@ReportToDate AS NVARCHAR(25)) + ''') '
	
	IF @UserList <> '' 
		BEGIN
			SET @strQuery = @strQuery + ' AND UserName IN (select * from dbo.CSVToTable(''' + @UserList + '''))'
		END
	IF @EquipmentList <> '' 
		BEGIN
			SET @strQuery = @strQuery + ' AND EquipmentMasterId IN (select * from dbo.CSVToTable(''' + @EquipmentList + '''))'
		END
	IF @FilterParameter <> ''
		BEGIN
			SET @strQuery = @strQuery + ' AND Parameter IN (select * from dbo.CSVToTable( ''' + @FilterParameter + '''))'
		END
	
	PRINT(@strQuery)
	EXEC(@strQuery)

END
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterAuditTrail_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterAuditTrail_Sync] 1,'2014-09-03 00:00:00.000'
CREATE PROCEDURE [dbo].[EquipmentMasterAuditTrail_Sync]
	@BranchId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMasterAuditTrail
			([EquipmentMasterAuditTrailId],[EquipmentMasterId],[AuditTrailDate],[Parameter],[ParameterOldValue]
           ,[ParameterNewValue],[Comments],[CompanyId],[EquipmentName],[UserName])
		select
			SourceDBTable.[EquipmentMasterAuditTrailId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[AuditTrailDate] ,SourceDBTable.[Parameter]
			,SourceDBTable.[ParameterOldValue],SourceDBTable.[ParameterNewValue],SourceDBTable.[Comments]
			,SourceDBTable.[CompanyId],SourceDBTable.[EquipmentName],SourceDBTable.[UserName]
		from EquipmentMasterAuditTrail(NOLOCK) SourceDBTable inner join EquipmentMaster EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND AuditTrailDate<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterAuditTrail DestinationDBTable
						 where DestinationDBTable.EquipmentMasterAuditTrailId = SourceDBTable.EquipmentMasterAuditTrailId)
						 
--Delete Record	
		
		Delete From EquipmentMasterAuditTrail Where AuditTrailDate<=@LogDateTime 
		And EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@BranchId )
		
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterHourlyLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [EquipmentMasterHourlyLog_CreateTable] '1'
CREATE PROCEDURE [dbo].[EquipmentMasterHourlyLog_CreateTable]
	@EquipmentMasterId as nvarchar(10)
AS
	SET NOCOUNT ON

BEGIN

	Declare @strQuery as varchar(max),@strQuery1 as varchar(max),@strQuery2 as varchar(max),@strQuery3 as varchar(max)
	
	Set @strQuery = 'CREATE TABLE EquipmentMasterHourlyLog_' + @EquipmentMasterId + '(
	[EquipmentMasterHourlyLogId_' + @EquipmentMasterId + '] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentMasterId] [bigint] NULL,
	[LogDateTime] [datetime] NULL UNIQUE,
	[Min1] [nvarchar](10) NULL,	[Avg1] [nvarchar](10) NULL,	[Max1] [nvarchar](10) NULL,	[Min2] [nvarchar](10) NULL,	[Avg2] [nvarchar](10) NULL,	[Max2] [nvarchar](10) NULL,
	[Min3] [nvarchar](10) NULL,	[Avg3] [nvarchar](10) NULL,	[Max3] [nvarchar](10) NULL,	[Min4] [nvarchar](10) NULL,	[Avg4] [nvarchar](10) NULL,	[Max4] [nvarchar](10) NULL,
	[Min5] [nvarchar](10) NULL,	[Avg5] [nvarchar](10) NULL,	[Max5] [nvarchar](10) NULL,	[Min6] [nvarchar](10) NULL,	[Avg6] [nvarchar](10) NULL,	[Max6] [nvarchar](10) NULL,
	[Min7] [nvarchar](10) NULL,	[Avg7] [nvarchar](10) NULL,	[Max7] [nvarchar](10) NULL,	[Min8] [nvarchar](10) NULL,	[Avg8] [nvarchar](10) NULL,	[Max8] [nvarchar](10) NULL,
	[Min9] [nvarchar](10) NULL,	[Avg9] [nvarchar](10) NULL,	[Max9] [nvarchar](10) NULL,	[Min10] [nvarchar](10) NULL,	[Avg10] [nvarchar](10) NULL,	[Max10] [nvarchar](10) NULL,'
	
	Set @strQuery1 = '[Min11] [nvarchar](10) NULL,	[Avg11] [nvarchar](10) NULL,	[Max11] [nvarchar](10) NULL,	[Min12] [nvarchar](10) NULL,	[Avg12] [nvarchar](10) NULL,	[Max12] [nvarchar](10) NULL,
	[Min13] [nvarchar](10) NULL,	[Avg13] [nvarchar](10) NULL,	[Max13] [nvarchar](10) NULL,	[Min14] [nvarchar](10) NULL,	[Avg14] [nvarchar](10) NULL,	[Max14] [nvarchar](10) NULL,
	[Min15] [nvarchar](10) NULL,	[Avg15] [nvarchar](10) NULL,	[Max15] [nvarchar](10) NULL,	[Min16] [nvarchar](10) NULL,	[Avg16] [nvarchar](10) NULL,	[Max16] [nvarchar](10) NULL,
	[Min17] [nvarchar](10) NULL,	[Avg17] [nvarchar](10) NULL,	[Max17] [nvarchar](10) NULL,	[Min18] [nvarchar](10) NULL,	[Avg18] [nvarchar](10) NULL,	[Max18] [nvarchar](10) NULL,
	[Min19] [nvarchar](10) NULL,	[Avg19] [nvarchar](10) NULL,	[Max19] [nvarchar](10) NULL,	[Min20] [nvarchar](10) NULL,	[Avg20] [nvarchar](10) NULL,	[Max20] [nvarchar](10) NULL'
	
	
	Set @strQuery2 = ' CONSTRAINT [PK_EquipmentMasterHourlyLog_' + @EquipmentMasterId + '] PRIMARY KEY CLUSTERED 
	(
	[EquipmentMasterHourlyLogId_' + @EquipmentMasterId + '] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
	'
	Execute(@strQuery + @strQuery1 + @strQuery2 )
	
	
	Execute ('ALTER TABLE [EquipmentMasterHourlyLog_' + @EquipmentMasterId + ']  WITH CHECK ADD  CONSTRAINT [FK_EquipmentMasterHourlyLog_' + @EquipmentMasterId + '_EquipmentMaster] FOREIGN KEY([EquipmentMasterId])
	REFERENCES [EquipmentMaster] ([EquipmentMasterId])')
	 
	Execute ('ALTER TABLE [EquipmentMasterHourlyLog_' + @EquipmentMasterId + '] CHECK CONSTRAINT [FK_EquipmentMasterHourlyLog_' + @EquipmentMasterId + '_EquipmentMaster]')
	
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- EquipmentMasterLog_CreateTable '2'
CREATE PROCEDURE [dbo].[EquipmentMasterLog_CreateTable]
	@EquipmentMasterId as nvarchar(10)
AS
	SET NOCOUNT ON

BEGIN

	Declare @strQuery as varchar(max),@strQuery1 as varchar(max),@strQuery2 as varchar(max),@strQuery3 as varchar(max)
	
	Set @strQuery = 'CREATE TABLE EquipmentMasterLog_' + @EquipmentMasterId + '(
	[EquipmentMasterLogId_' + @EquipmentMasterId + '] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentMasterId] [bigint] NULL,
	[LogDateTime] [datetime] NULL UNIQUE,[ReviewedApprovedStatus] [tinyint] NULL,
	[SensorLowerLowerValue1] [nvarchar](10) NULL,[SensorLowerValue1] [nvarchar](10) NULL,[SensorValue1] [nvarchar](10) NULL,[SensorUpperValue1] [nvarchar](10) NULL,[SensorUpperUpperValue1] [nvarchar](10) NULL,[SensorType1] [nvarchar](5) NULL,[SensorSetValue1] [nvarchar](10) NULL,
	[SensorLowerLowerValue2] [nvarchar](10) NULL,[SensorLowerValue2] [nvarchar](10) NULL,[SensorValue2] [nvarchar](10) NULL,[SensorUpperValue2] [nvarchar](10) NULL,[SensorUpperUpperValue2] [nvarchar](10) NULL,[SensorType2] [nvarchar](5) NULL,[SensorSetValue2] [nvarchar](10) NULL,
	[SensorLowerLowerValue3] [nvarchar](10) NULL,[SensorLowerValue3] [nvarchar](10) NULL,[SensorValue3] [nvarchar](10) NULL,[SensorUpperValue3] [nvarchar](10) NULL,[SensorUpperUpperValue3] [nvarchar](10) NULL,[SensorType3] [nvarchar](5) NULL,[SensorSetValue3] [nvarchar](10) NULL,
	[SensorLowerLowerValue4] [nvarchar](10) NULL,[SensorLowerValue4] [nvarchar](10) NULL,[SensorValue4] [nvarchar](10) NULL,[SensorUpperValue4] [nvarchar](10) NULL,[SensorUpperUpperValue4] [nvarchar](10) NULL,[SensorType4] [nvarchar](5) NULL,[SensorSetValue4] [nvarchar](10) NULL,
	[SensorLowerLowerValue5] [nvarchar](10) NULL,[SensorLowerValue5] [nvarchar](10) NULL,[SensorValue5] [nvarchar](10) NULL,[SensorUpperValue5] [nvarchar](10) NULL,[SensorUpperUpperValue5] [nvarchar](10) NULL,[SensorType5] [nvarchar](5) NULL,[SensorSetValue5] [nvarchar](10) NULL,
	[SensorLowerLowerValue6] [nvarchar](10) NULL,[SensorLowerValue6] [nvarchar](10) NULL,[SensorValue6] [nvarchar](10) NULL,[SensorUpperValue6] [nvarchar](10) NULL,[SensorUpperUpperValue6] [nvarchar](10) NULL,[SensorType6] [nvarchar](5) NULL,[SensorSetValue6] [nvarchar](10) NULL,
	[SensorLowerLowerValue7] [nvarchar](10) NULL,[SensorLowerValue7] [nvarchar](10) NULL,[SensorValue7] [nvarchar](10) NULL,[SensorUpperValue7] [nvarchar](10) NULL,[SensorUpperUpperValue7] [nvarchar](10) NULL,[SensorType7] [nvarchar](5) NULL,[SensorSetValue7] [nvarchar](10) NULL,
	[SensorLowerLowerValue8] [nvarchar](10) NULL,[SensorLowerValue8] [nvarchar](10) NULL,[SensorValue8] [nvarchar](10) NULL,[SensorUpperValue8] [nvarchar](10) NULL,[SensorUpperUpperValue8] [nvarchar](10) NULL,[SensorType8] [nvarchar](5) NULL,[SensorSetValue8] [nvarchar](10) NULL,
	[SensorLowerLowerValue9] [nvarchar](10) NULL,[SensorLowerValue9] [nvarchar](10) NULL,[SensorValue9] [nvarchar](10) NULL,[SensorUpperValue9] [nvarchar](10) NULL,[SensorUpperUpperValue9] [nvarchar](10) NULL,[SensorType9] [nvarchar](5) NULL,[SensorSetValue9] [nvarchar](10) NULL,
	[SensorLowerLowerValue10] [nvarchar](10) NULL,[SensorLowerValue10] [nvarchar](10) NULL,[SensorValue10] [nvarchar](10) NULL,[SensorUpperValue10] [nvarchar](10) NULL,[SensorUpperUpperValue10] [nvarchar](10) NULL,[SensorType10] [nvarchar](5) NULL,[SensorSetValue10] [nvarchar](10) NULL,
	[SensorLowerLowerValue11] [nvarchar](10) NULL,[SensorLowerValue11] [nvarchar](10) NULL,[SensorValue11] [nvarchar](10) NULL,[SensorUpperValue11] [nvarchar](10) NULL,[SensorUpperUpperValue11] [nvarchar](10) NULL,[SensorType11] [nvarchar](5) NULL,[SensorSetValue11] [nvarchar](10) NULL,'
	
	Set @strQuery1 = '[SensorLowerLowerValue12] [nvarchar](10) NULL,[SensorLowerValue12] [nvarchar](10) NULL,[SensorValue12] [nvarchar](10) NULL,[SensorUpperValue12] [nvarchar](10) NULL,[SensorUpperUpperValue12] [nvarchar](10) NULL,[SensorType12] [nvarchar](5) NULL,[SensorSetValue12] [nvarchar](10) NULL,
	[SensorLowerLowerValue13] [nvarchar](10) NULL,[SensorLowerValue13] [nvarchar](10) NULL,[SensorValue13] [nvarchar](10) NULL,[SensorUpperValue13] [nvarchar](10) NULL,[SensorUpperUpperValue13] [nvarchar](10) NULL,[SensorType13] [nvarchar](5) NULL,[SensorSetValue13] [nvarchar](10) NULL,
	[SensorLowerLowerValue14] [nvarchar](10) NULL,[SensorLowerValue14] [nvarchar](10) NULL,[SensorValue14] [nvarchar](10) NULL,[SensorUpperValue14] [nvarchar](10) NULL,[SensorUpperUpperValue14] [nvarchar](10) NULL,[SensorType14] [nvarchar](5) NULL,[SensorSetValue14] [nvarchar](10) NULL,
	[SensorLowerLowerValue15] [nvarchar](10) NULL,[SensorLowerValue15] [nvarchar](10) NULL,[SensorValue15] [nvarchar](10) NULL,[SensorUpperValue15] [nvarchar](10) NULL,[SensorUpperUpperValue15] [nvarchar](10) NULL,[SensorType15] [nvarchar](5) NULL,[SensorSetValue15] [nvarchar](10) NULL,
	[SensorLowerLowerValue16] [nvarchar](10) NULL,[SensorLowerValue16] [nvarchar](10) NULL,[SensorValue16] [nvarchar](10) NULL,[SensorUpperValue16] [nvarchar](10) NULL,[SensorUpperUpperValue16] [nvarchar](10) NULL,[SensorType16] [nvarchar](5) NULL,[SensorSetValue16] [nvarchar](10) NULL,
	[SensorLowerLowerValue17] [nvarchar](10) NULL,[SensorLowerValue17] [nvarchar](10) NULL,[SensorValue17] [nvarchar](10) NULL,[SensorUpperValue17] [nvarchar](10) NULL,[SensorUpperUpperValue17] [nvarchar](10) NULL,[SensorType17] [nvarchar](5) NULL,[SensorSetValue17] [nvarchar](10) NULL,
	[SensorLowerLowerValue18] [nvarchar](10) NULL,[SensorLowerValue18] [nvarchar](10) NULL,[SensorValue18] [nvarchar](10) NULL,[SensorUpperValue18] [nvarchar](10) NULL,[SensorUpperUpperValue18] [nvarchar](10) NULL,[SensorType18] [nvarchar](5) NULL,[SensorSetValue18] [nvarchar](10) NULL,
	[SensorLowerLowerValue19] [nvarchar](10) NULL,[SensorLowerValue19] [nvarchar](10) NULL,[SensorValue19] [nvarchar](10) NULL,[SensorUpperValue19] [nvarchar](10) NULL,[SensorUpperUpperValue19] [nvarchar](10) NULL,[SensorType19] [nvarchar](5) NULL,[SensorSetValue19] [nvarchar](10) NULL,
	[SensorLowerLowerValue20] [nvarchar](10) NULL,[SensorLowerValue20] [nvarchar](10) NULL,[SensorValue20] [nvarchar](10) NULL,[SensorUpperValue20] [nvarchar](10) NULL,[SensorUpperUpperValue20] [nvarchar](10) NULL,[SensorType20] [nvarchar](5) NULL,[SensorSetValue20] [nvarchar](10) NULL,
	[MKTStatus] [tinyint] default 0 NULL,[MovingMKTStatus] [tinyint] default 0 NULL'
	
	
	Set @strQuery2 = ' CONSTRAINT [PK_EquipmentMasterLog_' + @EquipmentMasterId + '] PRIMARY KEY CLUSTERED 
	(
	[EquipmentMasterLogId_' + @EquipmentMasterId + '] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
	'
	print(@strQuery + @strQuery1 + @strQuery2 )
	Execute(@strQuery + @strQuery1 + @strQuery2 )

	
	--Set @strQuery2= 'GO;
	
	Execute ('ALTER TABLE [EquipmentMasterLog_' + @EquipmentMasterId + ']  WITH CHECK ADD  CONSTRAINT [FK_EquipmentMasterLog_' + @EquipmentMasterId + '_EquipmentMaster] FOREIGN KEY([EquipmentMasterId])
	REFERENCES [EquipmentMaster] ([EquipmentMasterId])')
	 
	Execute ('ALTER TABLE [EquipmentMasterLog_' + @EquipmentMasterId + '] CHECK CONSTRAINT [FK_EquipmentMasterLog_' + @EquipmentMasterId + '_EquipmentMaster]')
	

END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_LastLogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC EquipmentMasterLog_LastLogDateTime 68
CREATE Procedure [dbo].[EquipmentMasterLog_LastLogDateTime]
 @EquipmentMasterId as bigint = 0
As 
Begin
	SET NOCOUNT ON;
    
    Declare @strQuery as nvarchar(500)
    
    SET @strQuery = 'select top 1 LogDateTime from EquipmentMasterLog_' + cast(@EquipmentMasterId as nvarchar(50)) + ' order by LogDateTime desc'    
    
    Execute(@strQuery)

End



GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_LogDateTime_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec EquipmentMasterLog_LogDateTime_Populate 75,0
CREATE PROCEDURE [dbo].[EquipmentMasterLog_LogDateTime_Populate]   
	@EquipmentMasterId as BIGINT =0,  
	@ReviewedApprovedStatus as tinyint=0  
AS  
Set nocount on;  
BEGIN    
	Declare @strIdQuery as varchar(4000),@EquipmentLogRate as integer  
   
	Select @EquipmentLogRate = EquipmnetLogRate from EquipmentMaster where EquipmentMasterId = @EquipmentMasterId  
   
	IF @ReviewedApprovedStatus = 0   
		Begin  
   
			Set @strIdQuery = ' Select EM.EquipmentMasterId,ISNULL(EMR1.MAXLogDateTime, EM.CreateDate) as MINLogDateTime
				from EquipmentMaster(NOLOCK) as EM 
				Outer Apply 
				( 
					Select MIN(LogDateTime) as MAXLogDateTime from EquipmentMasterLog_' + Convert(Varchar, @EquipmentMasterId) + ' EMRA1 
					(NOLOCK) Where  EMRA1.EquipmentMasterId = EM.EquipmentMasterId 
					 And (ReviewedApprovedStatus = ' + Convert(Varchar, @ReviewedApprovedStatus) + ') 
				) AS EMR1 
				Where EM.EquipmentMasterId= ' + Convert(Varchar, @EquipmentMasterId)
			
			print @strIdQuery
			exec(@strIdQuery) 
		
		END  
	ELSE  
		Begin  
     
			SELECT Top 1 EMR.EquipmentMasterId,EMR.FromDateTime as MINLogDateTime,EMR.ToDateTime as MAXLogDateTime,EMA.FromDateTime,EMA.ToDateTime  
			FROM EquipmentMasterLogReviewApprove(NOLOCK) AS EMR   
			Outer Apply  
			(  
			Select EMA.EquipmentMasterId,EMA.FromDateTime,EMA.ToDateTime from  
			EquipmentMasterLogReviewApprove(NOLOCK) EMA Where  
			EMA.EquipmentMasterId=EMR.EquipmentMasterId  
			And EMR.FromDateTime = EMA.FromDateTime AND EMR.ToDateTime = EMA.ToDateTime  
			AND EMA.ReviewedApproved = 'A'   
			)EMA  
  
			where EMR.EquipmentMasterId = @EquipmentMasterId AND EMR.ReviewedApproved = 'R'   
			And EMA.FromDateTime is null   
			Order BY EMR.FromDateTime ASC  
    
		END
		
		SELECT ET.EquipmentTypeGroup AS [EquipmentType] FROM EquipmentMaster EM INNER JOIN EquipmentType ET ON ET.EquipmentTypeId = EM.EquipmentTypeId  WHERE EM.EquipmentMasterId = @EquipmentMasterId   
End  
Set nocount off;  

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Exec EquipmentMasterLog_rpt '2018/10/16 10:07', '2018/10/16 13:10', '68', '','05', '1', '0'
CREATE PROCEDURE [dbo].[EquipmentMasterLog_rpt]    
@ReportFromDate AS DATETIME='',    
@ReportToDate AS DATETIME='',    
@EquipmentName AS varchar(10)='',    
@FilterParameter AS varchar(100)='',    
@Duration as varchar(10)='0',    
@ReviewApproveType INTEGER=0,    
@OrderBy as tinyint =0    
    --select * from EquipmentMasterLog_101
AS    
SET NOCOUNT ON;     
BEGIN    
	DECLARE @paraNo AS nvarchar(10),@StrQuerySelect as varchar(8000),@StrQueryWhere as varchar(8000),@EquipmentType AS NVARCHAR(20),@Version AS BIGINT,
			@TempHighAlert as nvarchar(10),@TempLowAlert as nvarchar(10),@HumidHighAlert as nvarchar(10),@HumidLowAlert as nvarchar(10)
	DECLARE @strCh as varchar(8000),@strLL as varchar(8000),@strHL as varchar(8000),
		    @strAL as varchar(8000),@strChType as varchar(8000),@strParamter as varchar(8000),@i as int,@j as int    
	
	DECLARE @StrQueryReviewApprove as varchar(8000),@strEquipmnetParameter as varchar(8000),@LogType AS varchar(3)
	
	SELECT @paraNo=ActiveChannel,@EquipmentType = ET.EquipmentTypeGroup ,@Version = EM.[Version],
			@TempHighAlert = TempratureUpperUpperLimit,@TempLowAlert = TempratureLowerLowerLimit,@HumidHighAlert = HumidityUpperUpperLimit,@HumidLowAlert = HumidityLowerLowerLimit 
	FROM EquipmentMaster EM inner join EquipmentType ET on em.EquipmentTypeId=et.EquipmentTypeId WHERE EquipmentMasterId=@EquipmentName      
	
	Set @strCh=''    
	Set @strLL=''    
	Set @strHL=''    
	Set @strAL=''
	Set @strChType='' 
	
	SET  @LogType = (CASE WHEN @ReviewApproveType = 1 THEN 'R' WHEN  @ReviewApproveType = 2 THEN 'A' ELSE 'D' END)
	--set @strMaxMinAvg=''
	 
	Set @i=1    
	Set @j=1    
	     
	While @i<=@paraNo  
	BEGIN 
		BEGIN 
		Set @strCh=@strCh+ ',(CASE WHEN SensorValue'+Cast(@i as varchar(2))+' = ''Open'' THEN CAST(0.0  AS NUMERIC(18,1)) ELSE CAST(SensorValue'+Cast(@i as varchar(2))+' AS NUMERIC(18,1)) END) AS SensorValue'+Cast(@i as varchar(2))
		Set @strLL=@strLL+ ',(CASE WHEN SensorLowerValue'+Cast(@i as varchar(2))+' = ''Open'' THEN CAST(0.0  AS NUMERIC(18,1)) ELSE CAST(SensorLowerValue'+Cast(@i as varchar(2))+' AS NUMERIC(18,1)) END) AS SensorLowerValue'+Cast(@i as varchar(2))
		Set @strHL=@strHL+ ',(CASE WHEN SensorUpperValue'+Cast(@i as varchar(2))+' = ''Open'' THEN CAST(0.0  AS NUMERIC(18,1)) ELSE CAST(SensorUpperValue'+Cast(@i as varchar(2))+' AS NUMERIC(18,1)) END) AS SensorUpperValue'+Cast(@i as varchar(2))
		Set @strChType = @strChType + ',SensorType'+Cast(@i as varchar(2))+' AS SensorType'+Cast(@j as varchar(2))
		Set @j = @j+1    	      	     
		Set @i = @i+1  
		END  
	END  	
	Set @StrQuerySelect= 'SELECT EML.EquipmentMasterLogId_'+Cast(@EquipmentName as varchar(10))+' as EquipmentMasterLogId,EML.EquipmentMasterId,EML.LogDateTime    
		,Cast('''+Cast(@paraNo as varchar(10))+''' as numeric(18)) as ParameterNo,Cast('''+cast(@EquipmentType as varchar(20))+''' as varchar(20)) as [Equipment Type] ,Cast('''+cast(@Version as varchar(20))+''' as varchar(20)) as [Version] ,
		Cast('''+cast(@TempHighAlert as varchar(20))+''' as varchar(20)) as [TempHighAlert] ,Cast('''+cast(@TempLowAlert as varchar(20))+''' as varchar(20)) as [TempLowAlert] ,
		Cast('''+cast(@HumidHighAlert as varchar(20))+''' as varchar(20)) as [HumidHighAlert] ,Cast('''+cast(@HumidLowAlert as varchar(20))+''' as varchar(20)) as [HumidLowAlert] '  
		
	Set @StrQueryWhere= ' FROM EquipmentMasterLog_' + Cast(@EquipmentName as varchar(10)) + ' (NOLOCK) AS EML    
		WHERE (EML.LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''')	     
		AND EML.ReviewedApprovedStatus='+Cast(@ReviewApproveType as varchar(3))+' '  
	   	
	IF @EquipmentName<>'' and @EquipmentName<>'0'    
	BEGIN    
		SET @StrQueryWhere = @StrQueryWhere + ' AND  EML.EquipmentMasterId in (select * from CSVTOTable('''+cast(@EquipmentName as varchar(4000))+''')) '    
	END    
	
	if @Duration <> '0'    
	begin    
		Set @StrQueryWhere = @StrQueryWhere + ' AND (CONVERT(VARCHAR(23),EML.LogDateTime,121) = CONVERT(VARCHAR(23),dbo.F_START_OF_30_MIN(CONVERT(VARCHAR(23),EML.LogDateTime,121),''' + Cast(@Duration as varchar(10)) + ''' ),121))  '    
	End    
	
	IF @FilterParameter<>''    
	BEGIN    
		SET @StrQueryWhere = @StrQueryWhere + ' '    
	END    
	     
	SET @StrQueryWhere = @StrQueryWhere +' order by Case ' + cast(@OrderBy as varchar) + ' When 0 Then EML.LogDateTime Else EML.EquipmentMasterLogId_'+Cast(@EquipmentName as varchar(10))+' end '       
	
	DECLARE @strFixedParameter as varchar(8000)
	set @strFixedParameter=',ReviewedApprovedStatus,sensorsetvalue1 as [SetTemp] ,sensorsetvalue2 as [SetRH],SensorLowerLowerValue1,SensorUpperUpperValue1,SensorLowerLowerValue2,SensorUpperUpperValue2 '

	if @EquipmentType like 'TC%'
	begin
		set @strFixedParameter = ',ReviewedApprovedStatus,sensorsetvalue1 as [SetTemp] ,sensorsetvalue2 as [SetRH],(SensorValue7 +'':''+ SensorValue9) as SoakTime ,(SensorValue8 +'':''+ SensorValue10) as ElaspsedTime,SensorLowerLowerValue1,SensorUpperUpperValue1,SensorLowerLowerValue2,SensorUpperUpperValue2 '
	end

	if @EquipmentType like 'PS%'
	begin
		set @strFixedParameter = ',ReviewedApprovedStatus,sensorsetvalue1 as [SetTemp] ,sensorsetvalue2 as [SetRH],SensorValue9,SensorValue10,SensorValue19,SensorValue20,SensorLowerLowerValue1,SensorUpperUpperValue1,SensorLowerLowerValue2,SensorUpperUpperValue2 '
	end

	if @EquipmentType like 'CO%'
	begin
		set @strFixedParameter = ',ReviewedApprovedStatus,sensorsetvalue1 as [SetTemp] ,sensorsetvalue2 as [SetRH],SensorValue9,SensorValue10,SensorValue19,SensorValue20,SensorLowerLowerValue1,SensorUpperUpperValue1,SensorLowerLowerValue2,SensorUpperUpperValue2 '
	end

	if @EquipmentType like 'SH%'
	begin
		set @strFixedParameter = ',ReviewedApprovedStatus,sensorsetvalue1 as [SetTemp] ,sensorsetvalue2 as [SetRH],SensorValue9,SensorValue10,SensorValue19,SensorValue20,SensorLowerLowerValue1,SensorUpperUpperValue1,SensorLowerLowerValue2,SensorUpperUpperValue2 '
	end

	SET @StrQueryReviewApprove = 'BEGIN 
									  SELECT * FROM EquipmentMasterLogReviewApprove(NOLOCK) 
									  WHERE EquipmentMasterId in (select * from CSVTOTable(''' + cast(@EquipmentName as varchar(4000)) + ''')) 
									  AND FromDateTime BETWEEN ''' + CAST(@ReportFromDate as varchar(25)) + ''' AND ''' + Cast(@ReportToDate as varchar(25)) + ''' 
									  AND ToDateTime BETWEEN ''' + CAST(@ReportFromDate as varchar(25)) + ''' AND ''' + Cast(@ReportToDate as varchar(25)) + ''' 
									  AND ReviewedApproved = ''' + CAST(@LogType as varchar(3)) + '''
								  END '
	
	SET @strEquipmnetParameter = ' BEGIN SELECT EquipmentMasterId,ParameterName,ParameterColor,ParameterColorCode FROM EquipmentMasterParameter(NOLOCK) WHERE EquipmentMasterId = ' + @EquipmentName + ' END '
	
	Exec (@StrQuerySelect + @strCh + @strLL + @strHL + @strChType+ @strFixedParameter + @StrQueryWhere +  @StrQueryReviewApprove + @strEquipmnetParameter)	 	     
END    
SET NOCOUNT OFF
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_rpt1]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec [EquipmentMasterLog_rpt] '21/08/2013','31/08/2013','2','','1',0,',1,2,3,4,'

--Exec [EquipmentMasterLog_rpt] '12-Aug-2015 00:00','12-Aug-2015 15:59','1002','','5',0,',1,2,3,4,5,6,7,8,'

--Exec [EquipmentMasterLog_rpt] '12-Aug-2015 00:00','12-Aug-2015 15:59','1002','','5',0,'1,3,5,7'

--Exec [EquipmentMasterLog_rpt1] '2018/06/20 00:00', ' 2018/07/05 23:59', '101', '','5', '0', '0'

CREATE PROCEDURE [dbo].[EquipmentMasterLog_rpt1]
	@qsrReportFromDate AS DATETIME='',
	@qsrReportToDate AS DATETIME='',
	@qsrEquipmentName AS varchar(20)='',
	@qsrFilterParameter AS varchar(100)='',
	@qsrDuration as varchar(10)='0',
	@qsrReviewApproveType INTEGER=0,
	@qsrChannel AS varchar(4000)=''

AS
SET NOCOUNT ON;
BEGIN
	DECLARE @paraNo AS nvarchar(10) ,@StrQuery as varchar(8000),@VersionNo AS nvarchar(10) 
	DECLARE @strCh as varchar(4000),@strLL as varchar(4000),@strHL as varchar(4000),@strLLV as varchar(4000),@strHLV as varchar(4000),@strSV as varchar(4000),@i as int,@j as int
	SELECT @paraNo=ActiveChannel,@VersionNo=[Version] FROM EquipmentMaster WHERE EquipmentMasterId=@qsrEquipmentName
	print (@paraNo)
	Set @strCh=''
	Set @strLL=''
	Set @strHL=''
	Set @strSV=''
	Set @strLLV=''
	Set @strHLV=''
	
	Set @i=1
	Set @j=1
	
	While @i<= 20
	
	Begin
	
		if CHARINDEX(','+ Cast(@i as varchar(2))+',',@qsrChannel)>0
			Begin
				print (@i)
				Set @strCh=@strCh+ ',SensorValue'+Cast(@i as varchar(2))+' AS SensorValue'++Cast(@j as varchar(2))
				Set @strLL=@strLL+ ',SensorLowerValue'+Cast(@i as varchar(2))+' AS SensorLowerValue'++Cast(@j as varchar(2))
				Set @strHL=@strHL+ ',SensorUpperValue'+Cast(@i as varchar(2))+' AS SensorUpperValue'++Cast(@j as varchar(2))
				Set @strSV=@strSV+ ',SensorSetValue'+Cast(@i as varchar(2))+' AS SensorSetValue'++Cast(@j as varchar(2))
				Set @strLLV=@strLLV+ ',SensorLowerLowerValue'+Cast(@i as varchar(2))+' AS SensorLowerLowerValue'++Cast(@j as varchar(2))
				Set @strHLV=@strHLV+ ',SensorUpperUpperValue'+Cast(@i as varchar(2))+' AS SensorUpperUpperValue'++Cast(@j as varchar(2))
				Set @j = @j+1
			End
	
		Set @i = @i+1
	End

	While @j<=20
	Begin
	
		Set @strCh=@strCh+ ',SensorValue'++Cast(@j as varchar(2))
		Set @strLL=@strLL+ ',SensorLowerValue'++Cast(@j as varchar(2))
		Set @strHL=@strHL+ ',SensorUpperValue'++Cast(@j as varchar(2))
		Set @strSV=@strSV+ ',SensorSetValue'++Cast(@j as varchar(2))
		Set @strLLV=@strLLV+ ',SensorLowerLowerValue'++Cast(@j as varchar(2))
		Set @strHLV=@strHLV+ ',SensorUpperUpperValue'++Cast(@j as varchar(2))
		
		Set @j = @j+1
	End
	Set @StrQuery='
	SELECT EML.EquipmentMasterLogId_'+Cast(@qsrEquipmentName as varchar(10))+' as EquipmentMasterLogId,EML.EquipmentMasterId,EML.EquipmentMasterId as EMID, EML.LogDateTime
	,Cast('''+Cast(@paraNo as varchar(10))+''' as numeric(18)) as ParameterNo,Cast('''+Cast(@VersionNo as varchar(10))+''' as numeric(18)) as VersionNo
	'+ @strCh + @strLL + @strHL + @strSV + @strLLV + @strHLV +'
				
	,ReviewedApprovedStatus	
	FROM EquipmentMasterLog_'+Cast(@qsrEquipmentName as varchar(10))+' AS EML
	WHERE (EML.LogDateTime BETWEEN '''+cast(@qsrReportFromDate as varchar(50))+''' AND '''+cast(@qsrReportToDate as varchar(50))+''') 
	
	AND EML.ReviewedApprovedStatus='+Cast(@qsrReviewApproveType as varchar(3))+' '
	
	PRINT(@strQuery)
	
	IF @qsrEquipmentName<>'' and @qsrEquipmentName<>'0'
		BEGIN
			SET @strQuery = @strQuery + ' AND  EML.EquipmentMasterId in (select * from CSVTOTable('''+cast(@qsrEquipmentName as varchar(4000))+''')) '
		END
		PRINT(@strQuery)
	if @qsrDuration <> '0'
			begin
				Set @strQuery = @strQuery + ' AND (CONVERT(VARCHAR(23),EML.LogDateTime,121) = CONVERT(VARCHAR(23),dbo.F_START_OF_30_MIN(CONVERT(VARCHAR(23),EML.LogDateTime,121),''' + Cast(@qsrDuration as varchar(10)) + ''' ),121))  '
			End
			PRINT(@strQuery)
	IF @qsrFilterParameter<>''
		BEGIN
			SET @strQuery = @strQuery + ' '
		END
	
	SET @strQuery = @strQuery +' ORDER BY EML.LogDateTime '
	
	PRINT(@strQuery)
	
Exec (@StrQuery)	
	
END
SET NOCOUNT OFF


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----[EquipmentMasterLog_Sync] '2016-01-01 23:59:00.000',76
CREATE PROCEDURE [dbo].[EquipmentMasterLog_Sync]
	@LogDateTime as Datetime,
	@EquipmentMasterId AS VARCHAR(10)=0
AS
	Set nocount on
	Begin
--Insert Record
		
		DECLARE @StrQuery as varchar(8000),@StrQuery1 as varchar(8000),@StrDeleteQuery as varchar(100)

		SET  @StrQuery=' insert into ICDAS_3_0_Archive.dbo.EquipmentMasterLog_'+ @EquipmentMasterId +'
			([EquipmentMasterLogId_'+ @EquipmentMasterId +'],[EquipmentMasterId],[LogDateTime],[ReviewedApprovedStatus]
			,[SensorLowerLowerValue1],[SensorLowerValue1],[SensorValue1],[SensorUpperValue1],[SensorUpperUpperValue1],[SensorType1],[SensorSetValue1]
			,[SensorLowerLowerValue2],[SensorLowerValue2],[SensorValue2],[SensorUpperValue2],[SensorUpperUpperValue2],[SensorType2],[SensorSetValue2]
			,[SensorLowerLowerValue3],[SensorLowerValue3],[SensorValue3],[SensorUpperValue3],[SensorUpperUpperValue3],[SensorType3],[SensorSetValue3]
			,[SensorLowerLowerValue4],[SensorLowerValue4],[SensorValue4],[SensorUpperValue4],[SensorUpperUpperValue4],[SensorType4],[SensorSetValue4]
			,[SensorLowerLowerValue5],[SensorLowerValue5],[SensorValue5],[SensorUpperValue5],[SensorUpperUpperValue5],[SensorType5],[SensorSetValue5]
			,[SensorLowerLowerValue6],[SensorLowerValue6],[SensorValue6],[SensorUpperValue6],[SensorUpperUpperValue6],[SensorType6],[SensorSetValue6]
			,[SensorLowerLowerValue7],[SensorLowerValue7],[SensorValue7],[SensorUpperValue7],[SensorUpperUpperValue7],[SensorType7],[SensorSetValue7]
			,[SensorLowerLowerValue8],[SensorLowerValue8],[SensorValue8],[SensorUpperValue8],[SensorUpperUpperValue8],[SensorType8],[SensorSetValue8]
			,[SensorLowerLowerValue9],[SensorLowerValue9],[SensorValue9],[SensorUpperValue9],[SensorUpperUpperValue9],[SensorType9],[SensorSetValue9]
			,[SensorLowerLowerValue10],[SensorLowerValue10],[SensorValue10],[SensorUpperValue10],[SensorUpperUpperValue10],[SensorType10],[SensorSetValue10]
			,[SensorLowerLowerValue11],[SensorLowerValue11],[SensorValue11],[SensorUpperValue11],[SensorUpperUpperValue11],[SensorType11],[SensorSetValue11]
			,[SensorLowerLowerValue12],[SensorLowerValue12],[SensorValue12],[SensorUpperValue12],[SensorUpperUpperValue12],[SensorType12],[SensorSetValue12]
			,[SensorLowerLowerValue13],[SensorLowerValue13],[SensorValue13],[SensorUpperValue13],[SensorUpperUpperValue13],[SensorType13],[SensorSetValue13]
			,[SensorLowerLowerValue14],[SensorLowerValue14],[SensorValue14],[SensorUpperValue14],[SensorUpperUpperValue14],[SensorType14],[SensorSetValue14]
			,[SensorLowerLowerValue15],[SensorLowerValue15],[SensorValue15],[SensorUpperValue15],[SensorUpperUpperValue15],[SensorType15],[SensorSetValue15]
			,[SensorLowerLowerValue16],[SensorLowerValue16],[SensorValue16],[SensorUpperValue16],[SensorUpperUpperValue16],[SensorType16],[SensorSetValue16]
			,[SensorLowerLowerValue17],[SensorLowerValue17],[SensorValue17],[SensorUpperValue17],[SensorUpperUpperValue17],[SensorType17],[SensorSetValue17]
			,[SensorLowerLowerValue18],[SensorLowerValue18],[SensorValue18],[SensorUpperValue18],[SensorUpperUpperValue18],[SensorType18],[SensorSetValue18]
			,[SensorLowerLowerValue19],[SensorLowerValue19],[SensorValue19],[SensorUpperValue19],[SensorUpperUpperValue19],[SensorType19],[SensorSetValue19]
			,[SensorLowerLowerValue20],[SensorLowerValue20],[SensorValue20],[SensorUpperValue20],[SensorUpperUpperValue20],[SensorType20],[SensorSetValue20],[MKTStatus],[MovingMKTStatus]) '
			
		SET  @StrQuery1='select
			SourceDBTable.[EquipmentMasterLogId_'+ @EquipmentMasterId +'],SourceDBTable.[EquipmentMasterId],SourceDBTable.[LogDateTime],SourceDBTable.[ReviewedApprovedStatus]
			,SourceDBTable.[SensorLowerLowerValue1],SourceDBTable.[SensorLowerValue1],SourceDBTable.[SensorValue1],SourceDBTable.[SensorUpperValue1],SourceDBTable.[SensorUpperUpperValue1],SourceDBTable.[SensorType1],SourceDBTable.[SensorSetValue1]
			,SourceDBTable.[SensorLowerLowerValue2],SourceDBTable.[SensorLowerValue2],SourceDBTable.[SensorValue2],SourceDBTable.[SensorUpperValue2],SourceDBTable.[SensorUpperUpperValue2],SourceDBTable.[SensorType2],SourceDBTable.[SensorSetValue2]
			,SourceDBTable.[SensorLowerLowerValue3],SourceDBTable.[SensorLowerValue3],SourceDBTable.[SensorValue3],SourceDBTable.[SensorUpperValue3],SourceDBTable.[SensorUpperUpperValue3],SourceDBTable.[SensorType3],SourceDBTable.[SensorSetValue3]
			,SourceDBTable.[SensorLowerLowerValue4],SourceDBTable.[SensorLowerValue4],SourceDBTable.[SensorValue4],SourceDBTable.[SensorUpperValue4],SourceDBTable.[SensorUpperUpperValue4],SourceDBTable.[SensorType4],SourceDBTable.[SensorSetValue4]
			,SourceDBTable.[SensorLowerLowerValue5],SourceDBTable.[SensorLowerValue5],SourceDBTable.[SensorValue5],SourceDBTable.[SensorUpperValue5],SourceDBTable.[SensorUpperUpperValue5],SourceDBTable.[SensorType5],SourceDBTable.[SensorSetValue5]
			,SourceDBTable.[SensorLowerLowerValue6],SourceDBTable.[SensorLowerValue6],SourceDBTable.[SensorValue6],SourceDBTable.[SensorUpperValue6],SourceDBTable.[SensorUpperUpperValue6],SourceDBTable.[SensorType6],SourceDBTable.[SensorSetValue6]
			,SourceDBTable.[SensorLowerLowerValue7],SourceDBTable.[SensorLowerValue7],SourceDBTable.[SensorValue7],SourceDBTable.[SensorUpperValue7],SourceDBTable.[SensorUpperUpperValue7],SourceDBTable.[SensorType7],SourceDBTable.[SensorSetValue7]
			,SourceDBTable.[SensorLowerLowerValue8],SourceDBTable.[SensorLowerValue8],SourceDBTable.[SensorValue8],SourceDBTable.[SensorUpperValue8],SourceDBTable.[SensorUpperUpperValue8],SourceDBTable.[SensorType8],SourceDBTable.[SensorSetValue8]
			,SourceDBTable.[SensorLowerLowerValue9],SourceDBTable.[SensorLowerValue9],SourceDBTable.[SensorValue9],SourceDBTable.[SensorUpperValue9],SourceDBTable.[SensorUpperUpperValue9],SourceDBTable.[SensorType9],SourceDBTable.[SensorSetValue9]
			,SourceDBTable.[SensorLowerLowerValue10],SourceDBTable.[SensorLowerValue10],SourceDBTable.[SensorValue10],SourceDBTable.[SensorUpperValue10],SourceDBTable.[SensorUpperUpperValue10],SourceDBTable.[SensorType10],SourceDBTable.[SensorSetValue10]
			,SourceDBTable.[SensorLowerLowerValue11],SourceDBTable.[SensorLowerValue11],SourceDBTable.[SensorValue11],SourceDBTable.[SensorUpperValue11],SourceDBTable.[SensorUpperUpperValue11],SourceDBTable.[SensorType11],SourceDBTable.[SensorSetValue11]
			,SourceDBTable.[SensorLowerLowerValue12],SourceDBTable.[SensorLowerValue12],SourceDBTable.[SensorValue12],SourceDBTable.[SensorUpperValue12],SourceDBTable.[SensorUpperUpperValue12],SourceDBTable.[SensorType12],SourceDBTable.[SensorSetValue12]
			,SourceDBTable.[SensorLowerLowerValue13],SourceDBTable.[SensorLowerValue13],SourceDBTable.[SensorValue13],SourceDBTable.[SensorUpperValue13],SourceDBTable.[SensorUpperUpperValue13],SourceDBTable.[SensorType13],SourceDBTable.[SensorSetValue13]
			,SourceDBTable.[SensorLowerLowerValue14],SourceDBTable.[SensorLowerValue14],SourceDBTable.[SensorValue14],SourceDBTable.[SensorUpperValue14],SourceDBTable.[SensorUpperUpperValue14],SourceDBTable.[SensorType14],SourceDBTable.[SensorSetValue14]
			,SourceDBTable.[SensorLowerLowerValue15],SourceDBTable.[SensorLowerValue15],SourceDBTable.[SensorValue15],SourceDBTable.[SensorUpperValue15],SourceDBTable.[SensorUpperUpperValue15],SourceDBTable.[SensorType15],SourceDBTable.[SensorSetValue15]
			,SourceDBTable.[SensorLowerLowerValue16],SourceDBTable.[SensorLowerValue16],SourceDBTable.[SensorValue16],SourceDBTable.[SensorUpperValue16],SourceDBTable.[SensorUpperUpperValue16],SourceDBTable.[SensorType16],SourceDBTable.[SensorSetValue16]
			,SourceDBTable.[SensorLowerLowerValue17],SourceDBTable.[SensorLowerValue17],SourceDBTable.[SensorValue17],SourceDBTable.[SensorUpperValue17],SourceDBTable.[SensorUpperUpperValue17],SourceDBTable.[SensorType17],SourceDBTable.[SensorSetValue17]
			,SourceDBTable.[SensorLowerLowerValue18],SourceDBTable.[SensorLowerValue18],SourceDBTable.[SensorValue18],SourceDBTable.[SensorUpperValue18],SourceDBTable.[SensorUpperUpperValue18],SourceDBTable.[SensorType18],SourceDBTable.[SensorSetValue18]
			,SourceDBTable.[SensorLowerLowerValue19],SourceDBTable.[SensorLowerValue19],SourceDBTable.[SensorValue19],SourceDBTable.[SensorUpperValue19],SourceDBTable.[SensorUpperUpperValue19],SourceDBTable.[SensorType19],SourceDBTable.[SensorSetValue19]
			,SourceDBTable.[SensorLowerLowerValue20],SourceDBTable.[SensorLowerValue20],SourceDBTable.[SensorValue20],SourceDBTable.[SensorUpperValue20],SourceDBTable.[SensorUpperUpperValue20],SourceDBTable.[SensorType20],SourceDBTable.[SensorSetValue20]
			,SourceDBTable.[MKTStatus],SourceDBTable.[MovingMKTStatus]  
		from EquipmentMasterLog_'+ @EquipmentMasterId +' (NOLOCK) SourceDBTable
		where LogDateTime<='''+ CAST(@LogDateTime AS VARCHAR(50)) +''' AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterLog_'+ @EquipmentMasterId +' DestinationDBTable
						 where DestinationDBTable.EquipmentMasterLogId_'+ @EquipmentMasterId +' = SourceDBTable.EquipmentMasterLogId_'+ @EquipmentMasterId +')
			'
		
		--PRINT (@StrQuery)
		--PRINT (@StrQuery1)
		EXEC (@StrQuery+@StrQuery1)
			 
--Delete Record	
		
		Set @StrDeleteQuery='Delete From EquipmentMasterLog_'+ @EquipmentMasterId +' Where LogDateTime<='''+ CAST(@LogDateTime AS VARCHAR(50)) +''''
		EXEC(@StrDeleteQuery)
		
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogManage_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [EquipmentMasterLogManage_Service] '82','<DataLog> <DataLog> <EquipmentMasterId>82</EquipmentMasterId> <LogDateTime>2018/06/16 11:25</LogDateTime> <ReviewedApprovedStatus>0</ReviewedApprovedStatus> <SensorLowerLowerValue1>0.0</SensorLowerLowerValue1> <SensorLowerValue1>70.0</SensorLowerValue1> <SensorValue1>Open</SensorValue1> <SensorUpperValue1>80.0</SensorUpperValue1> <SensorUpperUpperValue1>0.0</SensorUpperUpperValue1> <SensorType1>T</SensorType1> <SensorSetValue1>25.0</SensorSetValue1> <SensorLowerLowerValue2>0.0</SensorLowerLowerValue2> <SensorLowerValue2>70.0</SensorLowerValue2> <SensorValue2>Open</SensorValue2> <SensorUpperValue2>80.0</SensorUpperValue2> <SensorUpperUpperValue2>0.0</SensorUpperUpperValue2> <SensorType2>H</SensorType2> <SensorSetValue2>42.2</SensorSetValue2> <SensorLowerLowerValue3>0.0</SensorLowerLowerValue3> <SensorLowerValue3>70.0</SensorLowerValue3> <SensorValue3>Open</SensorValue3> <SensorUpperValue3>80.0</SensorUpperValue3> <SensorUpperUpperValue3>0.0</SensorUpperUpperValue3> <SensorType3>T</SensorType3> <SensorSetValue3>25.0</SensorSetValue3> <SensorLowerLowerValue4>0.0</SensorLowerLowerValue4> <SensorLowerValue4>70.0</SensorLowerValue4> <SensorValue4>Open</SensorValue4> <SensorUpperValue4>80.0</SensorUpperValue4> <SensorUpperUpperValue4>0.0</SensorUpperUpperValue4> <SensorType4>H</SensorType4> <SensorSetValue4>42.2</SensorSetValue4> <SensorLowerLowerValue5>0.0</SensorLowerLowerValue5> <SensorLowerValue5>70.0</SensorLowerValue5 ><SensorValue5>Open</SensorValue5> <SensorUpperValue5>80.0</SensorUpperValue5> <SensorUpperUpperValue5>0.0</SensorUpperUpperValue5> <SensorType5>T</SensorType5> <SensorSetValue5>25.0</SensorSetValue5> <SensorLowerLowerValue6>0.0</SensorLowerLowerValue6> <SensorLowerValue6>70.0</SensorLowerValue6> <SensorValue6>Open</SensorValue6> <SensorUpperValue6>80.0</SensorUpperValue6> <SensorUpperUpperValue6>0.0</SensorUpperUpperValue6> <SensorType6>H</SensorType6> <SensorSetValue6>42.2</SensorSetValue6> <SensorLowerLowerValue7>0.0</SensorLowerLowerValue7> <SensorLowerValue7>70.0</SensorLowerValue7> <SensorValue7>Open</SensorValue7> <SensorUpperValue7>80.0</SensorUpperValue7> <SensorUpperUpperValue7>0.0</SensorUpperUpperValue7> <SensorType7>T</SensorType7> <SensorSetValue7>25.0</SensorSetValue7> <SensorLowerLowerValue8>0.0</SensorLowerLowerValue8> <SensorLowerValue8>70.0</SensorLowerValue8> <SensorValue8>0.0</SensorValue8> <SensorUpperValue8>80.0</SensorUpperValue8> <SensorUpperUpperValue8>0.0</SensorUpperUpperValue8> <SensorType8>H</SensorType8> <SensorSetValue8>42.2</SensorSetValue8> <SensorLowerLowerValue9>0.0</SensorLowerLowerValue9> <SensorLowerValue9>70.0</SensorLowerValue9> <SensorValue9>0.0</SensorValue9> <SensorUpperValue9>80.0</SensorUpperValue9> <SensorUpperUpperValue9>0.0</SensorUpperUpperValue9> <SensorType9>T</SensorType9> <SensorSetValue9>25.0</SensorSetValue9> <SensorLowerLowerValue10>0.0</SensorLowerLowerValue10> <SensorLowerValue10>70.0</SensorLowerValue10> <SensorValue10>0.0</SensorValue10> <SensorUpperValue10>80.0</SensorUpperValue10> <SensorUpperUpperValue10>0.0</SensorUpperUpperValue10> <SensorType10>H</SensorType10> <SensorSetValue10>42.2</SensorSetValue10> <SensorLowerLowerValue11>0.0</SensorLowerLowerValue11> <SensorLowerValue11>70.0</SensorLowerValue11> <SensorValue11>0.0</SensorValue11> <SensorUpperValue11>80.0</SensorUpperValue11> <SensorUpperUpperValue11>0.0</SensorUpperUpperValue11> <SensorType11>T</SensorType11> <SensorSetValue11>25.0</SensorSetValue11> <SensorLowerLowerValue12>0.0</SensorLowerLowerValue12> <SensorLowerValue12>70.0</SensorLowerValue12> <SensorValue12>120.0</SensorValue12> <SensorUpperValue12>80.0</SensorUpperValue12> <SensorUpperUpperValue12>0.0</SensorUpperUpperValue12> <SensorType12>H</SensorType12> <SensorSetValue12>42.2</SensorSetValue12> <SensorLowerLowerValue13>0.0</SensorLowerLowerValue13> <SensorLowerValue13>70.0</SensorLowerValue13> <SensorValue13>0.0</SensorValue13> <SensorUpperValue13>80.0</SensorUpperValue13> <SensorUpperUpperValue13>0.0</SensorUpperUpperValue13> <SensorType13>T</SensorType13> <SensorSetValue13>25.0</SensorSetValue13> <SensorLowerLowerValue14>0.0</SensorLowerLowerValue14> <SensorLowerValue14>70.0</SensorLowerValue14> <SensorValue14>0.0</SensorValue14> <SensorUpperValue14>80.0</SensorUpperValue14> <SensorUpperUpperValue14>0.0</SensorUpperUpperValue14> <SensorType14>H</SensorType14> <SensorSetValue14>42.2</SensorSetValue14> <SensorLowerLowerValue15>0.0</SensorLowerLowerValue15> <SensorLowerValue15>70.0</SensorLowerValue15> <SensorValue15>0.0</SensorValue15> <SensorUpperValue15>80.0</SensorUpperValue15> <SensorUpperUpperValue15>0.0</SensorUpperUpperValue15> <SensorType15>T</SensorType15> <SensorSetValue15>25.0</SensorSetValue15> <SensorLowerLowerValue16>0.0</SensorLowerLowerValue16> <SensorLowerValue16>70.0</SensorLowerValue16> <SensorValue16>200.0</SensorValue16> <SensorUpperValue16>80.0</SensorUpperValue16> <SensorUpperUpperValue16>0.0</SensorUpperUpperValue16> <SensorType16>H</SensorType16> <SensorSetValue16>42.2</SensorSetValue16> <SensorLowerLowerValue17>0.0</SensorLowerLowerValue17> <SensorLowerValue17>70.0</SensorLowerValue17> <SensorValue17>120.0</SensorValue17> <SensorUpperValue17>80.0</SensorUpperValue17> <SensorUpperUpperValue17>0.0</SensorUpperUpperValue17> <SensorType17>T</SensorType17> <SensorSetValue17>25.0</SensorSetValue17> <SensorLowerLowerValue18>0.0</SensorLowerLowerValue18> <SensorLowerValue18>70.0</SensorLowerValue18> <SensorValue18>0.0</SensorValue18> <SensorUpperValue18>80.0</SensorUpperValue18> <SensorUpperUpperValue18>0.0</SensorUpperUpperValue18> <SensorType18>H</SensorType18> <SensorSetValue18>42.2</SensorSetValue18> <SensorLowerLowerValue19>0.0</SensorLowerLowerValue19> <SensorLowerValue19>70.0</SensorLowerValue19> <SensorValue19>0.0</SensorValue19> <SensorUpperValue19>80.0</SensorUpperValue19> <SensorUpperUpperValue19>0.0</SensorUpperUpperValue19> <SensorType19>T</SensorType19> <SensorSetValue19>25.0</SensorSetValue19> <SensorLowerLowerValue20>0.0</SensorLowerLowerValue20> <SensorLowerValue20>70.0</SensorLowerValue20> <SensorValue20>0.0</SensorValue20> <SensorUpperValue20>80.0</SensorUpperValue20> <SensorUpperUpperValue20>0.0</SensorUpperUpperValue20> <SensorType20>H</SensorType20> <SensorSetValue20>42.2</SensorSetValue20> </DataLog> </DataLog>'

CREATE PROCEDURE [dbo].[EquipmentMasterLogManage_Service]
@EquipmentMasterId nvarchar(10),
@xml XML,
@ReturnId AS BIGINT =0 OUTPUT

AS
BEGIN
      SET NOCOUNT ON;
	  Declare @strQuery as Varchar(max), @strQuery1 as Varchar(max)

	  Delete From EquipmentMasterLog_Temp where EquipmentMasterId=@EquipmentMasterId
	  
	  Begin try	  
	  INSERT INTO EquipmentMasterLog_Temp  (EquipmentMasterId,LogDateTime,ReviewedApprovedStatus,SensorLowerLowerValue1,SensorLowerValue1,SensorValue1,SensorUpperValue1,SensorUpperUpperValue1,SensorType1,SensorSetValue1
										,SensorLowerLowerValue2,SensorLowerValue2,SensorValue2,SensorUpperValue2,SensorUpperUpperValue2,SensorType2,SensorSetValue2
										,SensorLowerLowerValue3,SensorLowerValue3,SensorValue3,SensorUpperValue3,SensorUpperUpperValue3,SensorType3,SensorSetValue3
										,SensorLowerLowerValue4,SensorLowerValue4,SensorValue4,SensorUpperValue4,SensorUpperUpperValue4,SensorType4,SensorSetValue4
										,SensorLowerLowerValue5,SensorLowerValue5,SensorValue5,SensorUpperValue5,SensorUpperUpperValue5,SensorType5,SensorSetValue5
										,SensorLowerLowerValue6,SensorLowerValue6,SensorValue6,SensorUpperValue6,SensorUpperUpperValue6,SensorType6,SensorSetValue6
										,SensorLowerLowerValue7,SensorLowerValue7,SensorValue7,SensorUpperValue7,SensorUpperUpperValue7,SensorType7,SensorSetValue7
										,SensorLowerLowerValue8,SensorLowerValue8,SensorValue8,SensorUpperValue8,SensorUpperUpperValue8,SensorType8,SensorSetValue8
										,SensorLowerLowerValue9,SensorLowerValue9,SensorValue9,SensorUpperValue9,SensorUpperUpperValue9,SensorType9,SensorSetValue9
										,SensorLowerLowerValue10,SensorLowerValue10,SensorValue10,SensorUpperValue10,SensorUpperUpperValue10,SensorType10,SensorSetValue10
										,SensorLowerLowerValue11,SensorLowerValue11,SensorValue11,SensorUpperValue11,SensorUpperUpperValue11,SensorType11,SensorSetValue11
										,SensorLowerLowerValue12,SensorLowerValue12,SensorValue12,SensorUpperValue12,SensorUpperUpperValue12,SensorType12,SensorSetValue12
										,SensorLowerLowerValue13,SensorLowerValue13,SensorValue13,SensorUpperValue13,SensorUpperUpperValue13,SensorType13,SensorSetValue13
										,SensorLowerLowerValue14,SensorLowerValue14,SensorValue14,SensorUpperValue14,SensorUpperUpperValue14,SensorType14,SensorSetValue14
										,SensorLowerLowerValue15,SensorLowerValue15,SensorValue15,SensorUpperValue15,SensorUpperUpperValue15,SensorType15,SensorSetValue15
										,SensorLowerLowerValue16,SensorLowerValue16,SensorValue16,SensorUpperValue16,SensorUpperUpperValue16,SensorType16,SensorSetValue16
										,SensorLowerLowerValue17,SensorLowerValue17,SensorValue17,SensorUpperValue17,SensorUpperUpperValue17,SensorType17,SensorSetValue17
										,SensorLowerLowerValue18,SensorLowerValue18,SensorValue18,SensorUpperValue18,SensorUpperUpperValue18,SensorType18,SensorSetValue18
										,SensorLowerLowerValue19,SensorLowerValue19,SensorValue19,SensorUpperValue19,SensorUpperUpperValue19,SensorType19,SensorSetValue19
										,SensorLowerLowerValue20,SensorLowerValue20,SensorValue20,SensorUpperValue20,SensorUpperUpperValue20,SensorType20,SensorSetValue20)
      SELECT
      DataLog.value('(EquipmentMasterId/text())[1]','BigInt') AS EquipmentMasterId,
      DataLog.value('(LogDateTime/text())[1]','DateTime') AS LogDateTime,
	  DataLog.value('(ReviewedApprovedStatus/text())[1]','tinyint') AS ReviewedApprovedStatus,
	  DataLog.value('(SensorLowerLowerValue1/text())[1]','nvarchar(10)') AS SensorLowerLowerValue1,
	  DataLog.value('(SensorLowerValue1/text())[1]','nvarchar(10)') AS SensorLowerValue1,
	  DataLog.value('(SensorValue1/text())[1]','nvarchar(10)') AS SensorValue1,
	  DataLog.value('(SensorUpperValue1/text())[1]','nvarchar(10)') AS SensorUpperValue1,
	  DataLog.value('(SensorUpperUpperValue1/text())[1]','nvarchar(10)') AS SensorUpperUpperValue1,
	  DataLog.value('(SensorType1/text())[1]','nvarchar(10)') AS SensorType1,
	  DataLog.value('(SensorSetValue1/text())[1]','nvarchar(10)') AS SensorSetValue1,
	  DataLog.value('(SensorLowerLowerValue2/text())[1]','nvarchar(10)') AS SensorLowerLowerValue2,
	  DataLog.value('(SensorLowerValue2/text())[1]','nvarchar(10)') AS SensorLowerValue2,
	  DataLog.value('(SensorValue2/text())[1]','nvarchar(10)') AS SensorValue2,
	  DataLog.value('(SensorUpperValue2/text())[1]','nvarchar(10)') AS SensorUpperValue2,
	  DataLog.value('(SensorUpperUpperValue2/text())[1]','nvarchar(10)') AS SensorUpperUpperValue2,
	  DataLog.value('(SensorType2/text())[1]','nvarchar(10)') AS SensorType2,
	  DataLog.value('(SensorSetValue2/text())[1]','nvarchar(10)') AS SensorSetValue2,
	  DataLog.value('(SensorLowerLowerValue3/text())[1]','nvarchar(10)') AS SensorLowerLowerValue3,
	  DataLog.value('(SensorLowerValue3/text())[1]','nvarchar(10)') AS SensorLowerValue3,
	  DataLog.value('(SensorValue3/text())[1]','nvarchar(10)') AS SensorValue3,
	  DataLog.value('(SensorUpperValue3/text())[1]','nvarchar(10)') AS SensorUpperValue3,
	  DataLog.value('(SensorUpperUpperValue3/text())[1]','nvarchar(10)') AS SensorUpperUpperValue3,
	  DataLog.value('(SensorType3/text())[1]','nvarchar(10)') AS SensorType3,
	  DataLog.value('(SensorSetValue3/text())[1]','nvarchar(10)') AS SensorSetValue3,
	  DataLog.value('(SensorLowerLowerValue4/text())[1]','nvarchar(10)') AS SensorLowerLowerValue4,
	  DataLog.value('(SensorLowerValue4/text())[1]','nvarchar(10)') AS SensorLowerValue4,
	  DataLog.value('(SensorValue4/text())[1]','nvarchar(10)') AS SensorValue4,
	  DataLog.value('(SensorUpperValue4/text())[1]','nvarchar(10)') AS SensorUpperValue4,
	  DataLog.value('(SensorUpperUpperValue4/text())[1]','nvarchar(10)') AS SensorUpperUpperValue4,
	  DataLog.value('(SensorType4/text())[1]','nvarchar(10)') AS SensorType4,
	  DataLog.value('(SensorSetValue4/text())[1]','nvarchar(10)') AS SensorSetValue4,
	  DataLog.value('(SensorLowerLowerValue5/text())[1]','nvarchar(10)') AS SensorLowerLowerValue5,
	  DataLog.value('(SensorLowerValue5/text())[1]','nvarchar(10)') AS SensorLowerValue5,
	  DataLog.value('(SensorValue5/text())[1]','nvarchar(10)') AS SensorValue5,
	  DataLog.value('(SensorUpperValue5/text())[1]','nvarchar(10)') AS SensorUpperValue5,
	  DataLog.value('(SensorUpperUpperValue5/text())[1]','nvarchar(10)') AS SensorUpperUpperValue5,
	  DataLog.value('(SensorType5/text())[1]','nvarchar(10)') AS SensorType5,
	  DataLog.value('(SensorSetValue5/text())[1]','nvarchar(10)') AS SensorSetValue5,
	  DataLog.value('(SensorLowerLowerValue6/text())[1]','nvarchar(10)') AS SensorLowerLowerValue6,
	  DataLog.value('(SensorLowerValue6/text())[1]','nvarchar(10)') AS SensorLowerValue6,
	  DataLog.value('(SensorValue6/text())[1]','nvarchar(10)') AS SensorValue6,
	  DataLog.value('(SensorUpperValue6/text())[1]','nvarchar(10)') AS SensorUpperValue6,
	  DataLog.value('(SensorUpperUpperValue6/text())[1]','nvarchar(10)') AS SensorUpperUpperValue6,
	  DataLog.value('(SensorType6/text())[1]','nvarchar(10)') AS SensorType6,
	  DataLog.value('(SensorSetValue6/text())[1]','nvarchar(10)') AS SensorSetValue6,
	  DataLog.value('(SensorLowerLowerValue7/text())[1]','nvarchar(10)') AS SensorLowerLowerValue7,
	  DataLog.value('(SensorLowerValue7/text())[1]','nvarchar(10)') AS SensorLowerValue7,
	  DataLog.value('(SensorValue7/text())[1]','nvarchar(10)') AS SensorValue7,
	  DataLog.value('(SensorUpperValue7/text())[1]','nvarchar(10)') AS SensorUpperValue7,
	  DataLog.value('(SensorUpperUpperValue7/text())[1]','nvarchar(10)') AS SensorUpperUpperValue7,
	  DataLog.value('(SensorType7/text())[1]','nvarchar(10)') AS SensorType7,
	  DataLog.value('(SensorSetValue7/text())[1]','nvarchar(10)') AS SensorSetValue7,
	  DataLog.value('(SensorLowerLowerValue8/text())[1]','nvarchar(10)') AS SensorLowerLowerValue8,
	  DataLog.value('(SensorLowerValue8/text())[1]','nvarchar(10)') AS SensorLowerValue8,
	  DataLog.value('(SensorValue8/text())[1]','nvarchar(10)') AS SensorValue8,
	  DataLog.value('(SensorUpperValue8/text())[1]','nvarchar(10)') AS SensorUpperValue8,
	  DataLog.value('(SensorUpperUpperValue8/text())[1]','nvarchar(10)') AS SensorUpperUpperValue8,
	  DataLog.value('(SensorType8/text())[1]','nvarchar(10)') AS SensorType8,
	  DataLog.value('(SensorSetValue8/text())[1]','nvarchar(10)') AS SensorSetValue8,
	  DataLog.value('(SensorLowerLowerValue9/text())[1]','nvarchar(10)') AS SensorLowerLowerValue9,
	  DataLog.value('(SensorLowerValue9/text())[1]','nvarchar(10)') AS SensorLowerValue9,
	  DataLog.value('(SensorValue9/text())[1]','nvarchar(10)') AS SensorValue9,
	  DataLog.value('(SensorUpperValue9/text())[1]','nvarchar(10)') AS SensorUpperValue9,
	  DataLog.value('(SensorUpperUpperValue9/text())[1]','nvarchar(10)') AS SensorUpperUpperValue9,
	  DataLog.value('(SensorType9/text())[1]','nvarchar(10)') AS SensorType9,
	  DataLog.value('(SensorSetValue9/text())[1]','nvarchar(10)') AS SensorSetValue9,
	  DataLog.value('(SensorLowerLowerValue10/text())[1]','nvarchar(10)') AS SensorLowerLowerValue10,
	  DataLog.value('(SensorLowerValue10/text())[1]','nvarchar(10)') AS SensorLowerValue10,
	  DataLog.value('(SensorValue10/text())[1]','nvarchar(10)') AS SensorValue10,
	  DataLog.value('(SensorUpperValue10/text())[1]','nvarchar(10)') AS SensorUpperValue10,
	  DataLog.value('(SensorUpperUpperValue10/text())[1]','nvarchar(10)') AS SensorUpperUpperValue10,
	  DataLog.value('(SensorType10/text())[1]','nvarchar(10)') AS SensorType10,
	  DataLog.value('(SensorSetValue10/text())[1]','nvarchar(10)') AS SensorSetValue10,
	  DataLog.value('(SensorLowerLowerValue11/text())[1]','nvarchar(10)') AS SensorLowerLowerValue11,
	  DataLog.value('(SensorLowerValue11/text())[1]','nvarchar(10)') AS SensorLowerValue11,
	  DataLog.value('(SensorValue11/text())[1]','nvarchar(10)') AS SensorValue11,
	  DataLog.value('(SensorUpperValue11/text())[1]','nvarchar(10)') AS SensorUpperValue11,
	  DataLog.value('(SensorUpperUpperValue11/text())[1]','nvarchar(10)') AS SensorUpperUpperValue11,
	  DataLog.value('(SensorType11/text())[1]','nvarchar(10)') AS SensorType11,
	  DataLog.value('(SensorSetValue11/text())[1]','nvarchar(10)') AS SensorSetValue11,
	  DataLog.value('(SensorLowerLowerValue12/text())[1]','nvarchar(10)') AS SensorLowerLowerValue12,
	  DataLog.value('(SensorLowerValue12/text())[1]','nvarchar(10)') AS SensorLowerValue12,
	  DataLog.value('(SensorValue12/text())[1]','nvarchar(10)') AS SensorValue12,
	  DataLog.value('(SensorUpperValue12/text())[1]','nvarchar(10)') AS SensorUpperValue12,
	  DataLog.value('(SensorUpperUpperValue12/text())[1]','nvarchar(10)') AS SensorUpperUpperValue12,
	  DataLog.value('(SensorType12/text())[1]','nvarchar(10)') AS SensorType12,
	  DataLog.value('(SensorSetValue12/text())[1]','nvarchar(10)') AS SensorSetValue12,
	  DataLog.value('(SensorLowerLowerValue13/text())[1]','nvarchar(10)') AS SensorLowerLowerValue13,
	  DataLog.value('(SensorLowerValue13/text())[1]','nvarchar(10)') AS SensorLowerValue13,
	  DataLog.value('(SensorValue13/text())[1]','nvarchar(10)') AS SensorValue13,
	  DataLog.value('(SensorUpperValue13/text())[1]','nvarchar(10)') AS SensorUpperValue13,
	  DataLog.value('(SensorUpperUpperValue13/text())[1]','nvarchar(10)') AS SensorUpperUpperValue13,
	  DataLog.value('(SensorType13/text())[1]','nvarchar(10)') AS SensorType13,
	  DataLog.value('(SensorSetValue13/text())[1]','nvarchar(10)') AS SensorSetValue13,
	  DataLog.value('(SensorLowerLowerValue14/text())[1]','nvarchar(10)') AS SensorLowerLowerValue14,
	  DataLog.value('(SensorLowerValue14/text())[1]','nvarchar(10)') AS SensorLowerValue14,
	  DataLog.value('(SensorValue14/text())[1]','nvarchar(10)') AS SensorValue14,
	  DataLog.value('(SensorUpperValue14/text())[1]','nvarchar(10)') AS SensorUpperValue14,
	  DataLog.value('(SensorUpperUpperValue14/text())[1]','nvarchar(10)') AS SensorUpperUpperValue14,
	  DataLog.value('(SensorType14/text())[1]','nvarchar(10)') AS SensorType14,
	  DataLog.value('(SensorSetValue14/text())[1]','nvarchar(10)') AS SensorSetValue14,
	  DataLog.value('(SensorLowerLowerValue15/text())[1]','nvarchar(10)') AS SensorLowerLowerValue15,
	  DataLog.value('(SensorLowerValue15/text())[1]','nvarchar(10)') AS SensorLowerValue15,
	  DataLog.value('(SensorValue15/text())[1]','nvarchar(10)') AS SensorValue15,
	  DataLog.value('(SensorUpperValue15/text())[1]','nvarchar(10)') AS SensorUpperValue15,
	  DataLog.value('(SensorUpperUpperValue15/text())[1]','nvarchar(10)') AS SensorUpperUpperValue15,
	  DataLog.value('(SensorType15/text())[1]','nvarchar(10)') AS SensorType15,
	  DataLog.value('(SensorSetValue15/text())[1]','nvarchar(10)') AS SensorSetValue15,
	  DataLog.value('(SensorLowerLowerValue16/text())[1]','nvarchar(10)') AS SensorLowerLowerValue16,
	  DataLog.value('(SensorLowerValue16/text())[1]','nvarchar(10)') AS SensorLowerValue16,
	  DataLog.value('(SensorValue16/text())[1]','nvarchar(10)') AS SensorValue16,
	  DataLog.value('(SensorUpperValue16/text())[1]','nvarchar(10)') AS SensorUpperValue16,
	  DataLog.value('(SensorUpperUpperValue16/text())[1]','nvarchar(10)') AS SensorUpperUpperValue16,
	  DataLog.value('(SensorType16/text())[1]','nvarchar(10)') AS SensorType16,
	  DataLog.value('(SensorSetValue16/text())[1]','nvarchar(10)') AS SensorSetValue16,
	  DataLog.value('(SensorLowerLowerValue17/text())[1]','nvarchar(10)') AS SensorLowerLowerValue17,
	  DataLog.value('(SensorLowerValue17/text())[1]','nvarchar(10)') AS SensorLowerValue17,
	  DataLog.value('(SensorValue17/text())[1]','nvarchar(10)') AS SensorValue17,
	  DataLog.value('(SensorUpperValue17/text())[1]','nvarchar(10)') AS SensorUpperValue17,
	  DataLog.value('(SensorUpperUpperValue17/text())[1]','nvarchar(10)') AS SensorUpperUpperValue17,
	  DataLog.value('(SensorType17/text())[1]','nvarchar(10)') AS SensorType17,
	  DataLog.value('(SensorSetValue17/text())[1]','nvarchar(10)') AS SensorSetValue17,
	  DataLog.value('(SensorLowerLowerValue18/text())[1]','nvarchar(10)') AS SensorLowerLowerValue18,
	  DataLog.value('(SensorLowerValue18/text())[1]','nvarchar(10)') AS SensorLowerValue18,
	  DataLog.value('(SensorValue18/text())[1]','nvarchar(10)') AS SensorValue18,
	  DataLog.value('(SensorUpperValue18/text())[1]','nvarchar(10)') AS SensorUpperValue18,
	  DataLog.value('(SensorUpperUpperValue18/text())[1]','nvarchar(10)') AS SensorUpperUpperValue18,
	  DataLog.value('(SensorType18/text())[1]','nvarchar(10)') AS SensorType18,
	  DataLog.value('(SensorSetValue18/text())[1]','nvarchar(10)') AS SensorSetValue18,
	  DataLog.value('(SensorLowerLowerValue19/text())[1]','nvarchar(10)') AS SensorLowerLowerValue19,
	  DataLog.value('(SensorLowerValue19/text())[1]','nvarchar(10)') AS SensorLowerValue19,
	  DataLog.value('(SensorValue19/text())[1]','nvarchar(10)') AS SensorValue19,
	  DataLog.value('(SensorUpperValue19/text())[1]','nvarchar(10)') AS SensorUpperValue19,
	  DataLog.value('(SensorUpperUpperValue19/text())[1]','nvarchar(10)') AS SensorUpperUpperValue19,
	  DataLog.value('(SensorType19/text())[1]','nvarchar(10)') AS SensorType19,
	  DataLog.value('(SensorSetValue19/text())[1]','nvarchar(10)') AS SensorSetValue19,
	  DataLog.value('(SensorLowerLowerValue20/text())[1]','nvarchar(10)') AS SensorLowerLowerValue20,
	  DataLog.value('(SensorLowerValue20/text())[1]','nvarchar(10)') AS SensorLowerValue20,
	  DataLog.value('(SensorValue20/text())[1]','nvarchar(10)') AS SensorValue20,
	  DataLog.value('(SensorUpperValue20/text())[1]','nvarchar(10)') AS SensorUpperValue20,
	  DataLog.value('(SensorUpperUpperValue20/text())[1]','nvarchar(10)') AS SensorUpperUpperValue20,
	  DataLog.value('(SensorType20/text())[1]','nvarchar(10)') AS SensorType20,
	  DataLog.value('(SensorSetValue20/text())[1]','nvarchar(10)') AS SensorSetValue20

      FROM
      @xml.nodes('/DataLog/DataLog')AS TEMPTABLE(DataLog)
	

      Set @strQuery = 'INSERT INTO EquipmentMasterLog_' + @EquipmentMasterId + ' (EquipmentMasterId,LogDateTime,ReviewedApprovedStatus,SensorLowerLowerValue1,SensorLowerValue1,SensorValue1,SensorUpperValue1,SensorUpperUpperValue1,SensorType1,SensorSetValue1
										,SensorLowerLowerValue2,SensorLowerValue2,SensorValue2,SensorUpperValue2,SensorUpperUpperValue2,SensorType2,SensorSetValue2
										,SensorLowerLowerValue3,SensorLowerValue3,SensorValue3,SensorUpperValue3,SensorUpperUpperValue3,SensorType3,SensorSetValue3
										,SensorLowerLowerValue4,SensorLowerValue4,SensorValue4,SensorUpperValue4,SensorUpperUpperValue4,SensorType4,SensorSetValue4
										,SensorLowerLowerValue5,SensorLowerValue5,SensorValue5,SensorUpperValue5,SensorUpperUpperValue5,SensorType5,SensorSetValue5
										,SensorLowerLowerValue6,SensorLowerValue6,SensorValue6,SensorUpperValue6,SensorUpperUpperValue6,SensorType6,SensorSetValue6
										,SensorLowerLowerValue7,SensorLowerValue7,SensorValue7,SensorUpperValue7,SensorUpperUpperValue7,SensorType7,SensorSetValue7
										,SensorLowerLowerValue8,SensorLowerValue8,SensorValue8,SensorUpperValue8,SensorUpperUpperValue8,SensorType8,SensorSetValue8
										,SensorLowerLowerValue9,SensorLowerValue9,SensorValue9,SensorUpperValue9,SensorUpperUpperValue9,SensorType9,SensorSetValue9
										,SensorLowerLowerValue10,SensorLowerValue10,SensorValue10,SensorUpperValue10,SensorUpperUpperValue10,SensorType10,SensorSetValue10
										,SensorLowerLowerValue11,SensorLowerValue11,SensorValue11,SensorUpperValue11,SensorUpperUpperValue11,SensorType11,SensorSetValue11
										,SensorLowerLowerValue12,SensorLowerValue12,SensorValue12,SensorUpperValue12,SensorUpperUpperValue12,SensorType12,SensorSetValue12
										,SensorLowerLowerValue13,SensorLowerValue13,SensorValue13,SensorUpperValue13,SensorUpperUpperValue13,SensorType13,SensorSetValue13
										,SensorLowerLowerValue14,SensorLowerValue14,SensorValue14,SensorUpperValue14,SensorUpperUpperValue14,SensorType14,SensorSetValue14
										,SensorLowerLowerValue15,SensorLowerValue15,SensorValue15,SensorUpperValue15,SensorUpperUpperValue15,SensorType15,SensorSetValue15
										,SensorLowerLowerValue16,SensorLowerValue16,SensorValue16,SensorUpperValue16,SensorUpperUpperValue16,SensorType16,SensorSetValue16
										,SensorLowerLowerValue17,SensorLowerValue17,SensorValue17,SensorUpperValue17,SensorUpperUpperValue17,SensorType17,SensorSetValue17
										,SensorLowerLowerValue18,SensorLowerValue18,SensorValue18,SensorUpperValue18,SensorUpperUpperValue18,SensorType18,SensorSetValue18
										,SensorLowerLowerValue19,SensorLowerValue19,SensorValue19,SensorUpperValue19,SensorUpperUpperValue19,SensorType19,SensorSetValue19
										,SensorLowerLowerValue20,SensorLowerValue20,SensorValue20,SensorUpperValue20,SensorUpperUpperValue20,SensorType20,SensorSetValue20)'
      Set @strQuery1= 'SELECT Distinct EquipmentMasterId,LogDateTime,ReviewedApprovedStatus,SensorLowerLowerValue1,SensorLowerValue1,SensorValue1,SensorUpperValue1,SensorUpperUpperValue1,SensorType1,SensorSetValue1
										,SensorLowerLowerValue2,SensorLowerValue2,SensorValue2,SensorUpperValue2,SensorUpperUpperValue2,SensorType2,SensorSetValue2
										,SensorLowerLowerValue3,SensorLowerValue3,SensorValue3,SensorUpperValue3,SensorUpperUpperValue3,SensorType3,SensorSetValue3
										,SensorLowerLowerValue4,SensorLowerValue4,SensorValue4,SensorUpperValue4,SensorUpperUpperValue4,SensorType4,SensorSetValue4
										,SensorLowerLowerValue5,SensorLowerValue5,SensorValue5,SensorUpperValue5,SensorUpperUpperValue5,SensorType5,SensorSetValue5
										,SensorLowerLowerValue6,SensorLowerValue6,SensorValue6,SensorUpperValue6,SensorUpperUpperValue6,SensorType6,SensorSetValue6
										,SensorLowerLowerValue7,SensorLowerValue7,SensorValue7,SensorUpperValue7,SensorUpperUpperValue7,SensorType7,SensorSetValue7
										,SensorLowerLowerValue8,SensorLowerValue8,SensorValue8,SensorUpperValue8,SensorUpperUpperValue8,SensorType8,SensorSetValue8
										,SensorLowerLowerValue9,SensorLowerValue9,SensorValue9,SensorUpperValue9,SensorUpperUpperValue9,SensorType9,SensorSetValue9
										,SensorLowerLowerValue10,SensorLowerValue10,SensorValue10,SensorUpperValue10,SensorUpperUpperValue10,SensorType10,SensorSetValue10
										,SensorLowerLowerValue11,SensorLowerValue11,SensorValue11,SensorUpperValue11,SensorUpperUpperValue11,SensorType11,SensorSetValue11
										,SensorLowerLowerValue12,SensorLowerValue12,SensorValue12,SensorUpperValue12,SensorUpperUpperValue12,SensorType12,SensorSetValue12
										,SensorLowerLowerValue13,SensorLowerValue13,SensorValue13,SensorUpperValue13,SensorUpperUpperValue13,SensorType13,SensorSetValue13
										,SensorLowerLowerValue14,SensorLowerValue14,SensorValue14,SensorUpperValue14,SensorUpperUpperValue14,SensorType14,SensorSetValue14
										,SensorLowerLowerValue15,SensorLowerValue15,SensorValue15,SensorUpperValue15,SensorUpperUpperValue15,SensorType15,SensorSetValue15
										,SensorLowerLowerValue16,SensorLowerValue16,SensorValue16,SensorUpperValue16,SensorUpperUpperValue16,SensorType16,SensorSetValue16
										,SensorLowerLowerValue17,SensorLowerValue17,SensorValue17,SensorUpperValue17,SensorUpperUpperValue17,SensorType17,SensorSetValue17
										,SensorLowerLowerValue18,SensorLowerValue18,SensorValue18,SensorUpperValue18,SensorUpperUpperValue18,SensorType18,SensorSetValue18
										,SensorLowerLowerValue19,SensorLowerValue19,SensorValue19,SensorUpperValue19,SensorUpperUpperValue19,SensorType19,SensorSetValue19
										,SensorLowerLowerValue20,SensorLowerValue20,SensorValue20,SensorUpperValue20,SensorUpperUpperValue20,SensorType20,SensorSetValue20 
										from EquipmentMasterLog_Temp(nolock) Where LogDateTime Not In (Select LogDateTime From EquipmentMasterLog_' + @EquipmentMasterId + ' (NoLock) )
										And EquipmentMasterId= ' + @EquipmentMasterId + ' Order by LogDateTime ASC'
	   execute (@strQuery+@strQuery1)
	   
	   if @@ROWCOUNT > 0
		   Begin
			   Set @ReturnId=@@Rowcount
			   print @ReturnId
		   End
	   else
		   Begin
			   Set @ReturnId=0
			   print @ReturnId
		   End
	   end try
		begin catch
			Set @ReturnId=0
			print @ReturnId
		end catch
	   --print(@ReturnId)
	   --print (@strQuery+@strQuery1)

  
END


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_Delete]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[EquipmentMasterLogMKT_Delete]
	@UserName AS  nVarchar(50)=''
AS
SET NOCOUNT ON;
BEGIN
		Delete from EquipmentMasterMKT where UserName = @UserName
END
SET NOCOUNT OFF;


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_GetPending]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterLogMKT_GetPending] 1,'D'
CREATE PROCEDURE [dbo].[EquipmentMasterLogMKT_GetPending]
@EquipmentMasterId as bigint,
@MKTType as nvarchar(5),
@FromDateTime as datetime = '',
@ToDateTime as datetime = ''

AS
Begin

	Declare @strQuery as Varchar(5000)
	
	if @MKTType = 'D'
		Begin
			Set @strQuery = 'SELECT DISTINCT DateAdd(d,0, CONVERT(VARCHAR(10), LogDateTime, 110)) AS StartDate
			,DateAdd(d,1, CONVERT(VARCHAR(10), LogDateTime, 110)) as EndDate	
			FROM EquipmentMasterLog_' + Cast(@EquipmentMasterId as varchar(10)) + ' 
			WHERE (LogDateTime BETWEEN ''' +  cast(@FromDateTime as varchar(50)) + ''' AND ''' + cast(@ToDateTime as varchar(50)) + ''')'
		end 
	else if @MKTType = 'W'
		Begin
			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year
			,DATEPART(wk,LogDateTime) AS Week#
			,MIN(DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0)) AS StartDate
			, DateAdd(d,6, MIN(DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0))) as EndDate
			from EquipmentMasterLog_'+ Cast(@EquipmentMasterId as varchar(10)) +' 
			WHERE (LogDateTime BETWEEN ''' +  cast(@FromDateTime as varchar(50)) + ''' AND ''' + cast(@ToDateTime as varchar(50)) + ''')
			GROUP BY DATEPART(YEAR,LogDateTime),DATEPART(wk,LogDateTime) order By MIN(DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0))'
		end 
	else if @MKTType = 'M'
		Begin
			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year
			,DATEPART(m,LogDateTime) AS Week#
			,MIN(DATEADD(m, DATEDIFF(m,0,LogDateTime), 0)) AS StartDate
			,((DATEADD(s,0,Min(DATEADD(mm, DATEDIFF(m,0,LogDateTime)+1,0))) )-1) as EndDate			  
			from EquipmentMasterLog_'+ Cast(@EquipmentMasterId as varchar(10)) +' 
			WHERE (LogDateTime BETWEEN ''' +  cast(@FromDateTime as varchar(50)) + ''' AND ''' + cast(@ToDateTime as varchar(50)) + ''')
			GROUP BY DATEPART(YEAR,LogDateTime),DATEPART(m,LogDateTime) order By MIN(DATEADD(m, DATEDIFF(m,0,LogDateTime), 0))'
		end 
		
	print(@strQuery)
	exec (@strQuery)

End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterLogMKT_rpt] '2010-02-16','2018-08-22',10028,',1,3,5,7,9,11,13,15,17,19,',',Temperature1,Temperature2,Temperature3,Temperature4,Temperature5,Temperature6,Temperature7,Temperature8,Temperature9,Temperature10,','w'
--[EquipmentMasterLogMKT_rpt] '2019/08/01 00:00','2019/08/01 23:59','81','26,30','Temperature1,Temperature3','D'
CREATE PROCEDURE [dbo].[EquipmentMasterLogMKT_rpt]
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@EquipmentName AS nvarchar(100)='',
	@Parameter AS varchar(1000)='',
	@ParameterName AS varchar(4000)='',
	@ActionMode as varchar(3)='d'

AS
Begin

	Declare @strQuery as Varchar(5000),@NewParameterName as Varchar(4000)
	Declare @TempParaName as nvarchar(100)
	DECLARE @strMax as varchar(4000),@stMin as varchar(4000),@strAvg as varchar(4000),@i as int,@j as int
	
	Set @strMax=''
	Set @stMin=''
	Set @strAvg=''
	Set @NewParameterName=''
	
	Set @i=1
	Set @j=1
	Set @TempParaName=@ParameterName
	 --print (('HIafefefe'))
	While @i<=20
	Begin
		if CHARINDEX(','+ Cast(@i as varchar(2))+',',@Parameter)>0
			Begin
			
				--print ('HI'+@i)
				Set @strMax=@strMax+ ',isnull(Max'+Cast(@i as varchar(2))+',0.00) AS MaxValue'++Cast(@j as varchar(2))
				Set @stMin=@stMin+ ',isnull(Min'+Cast(@i as varchar(2))+',0.00) AS MinValue'++Cast(@j as varchar(2))
				Set @strAvg=@strAvg+ ',isnull(Avg'+Cast(@i as varchar(2))+',0.00) AS MeanValue'++Cast(@j as varchar(2))
				
				Set @TempParaName = substring(@ParameterName,CHARINDEX(',',@ParameterName,1)+1,CHARINDEX(',',@ParameterName,2)-2)
				Set @NewParameterName=@NewParameterName + ','''+ @TempParaName +''' AS ParameterName'++Cast(@j as varchar(2))
				print(@TempParaName)
				Set @ParameterName=replace(@ParameterName,','+substring(@ParameterName,CHARINDEX(',',@ParameterName,1)+1,CHARINDEX(',',@ParameterName,2)-2)+',',',')
				print(@ParameterName)
				Set @j = @j+1
			End
		Set @i = @i+1
	End

	While @j<=20
	Begin
		Set @strMax=@strMax+ ',isnull(Max'+Cast(@j as varchar(2))+',0.00) AS MaxValue'++Cast(@j as varchar(2))
		Set @stMin=@stMin+ ',isnull(Min'+Cast(@j as varchar(2))+',0.00) AS MinValue'++Cast(@j as varchar(2))
		Set @strAvg=@strAvg+ ',isnull(Avg'+Cast(@j as varchar(2))+',0.00) AS MeanValue'++Cast(@j as varchar(2))
		Set @NewParameterName=@NewParameterName+ ','''' AS ParameterName'++Cast(@j as varchar(2))
		Set @j = @j+1
	End
	

	if @ActionMode = 'D'
		Begin
		
			
			Set @strQuery = 'select LogDateTime as StartDate,LogDateTime as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT 
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''') order by logDateTime'
		end 

	if @ActionMode = 'M'
		Begin

			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year
			,DATEPART(m,LogDateTime) AS Week#,
			DATEADD(m, DATEDIFF(m,0,LogDateTime), 0) AS StartDate,
			((DATEADD(s,0,DATEADD(mm, DATEDIFF(m,0,LogDateTime)+1,0)) )-1) as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''')order by logDateTime'
						
		end 

	if @ActionMode = 'W'
		Begin

			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year,
			DATEPART(wk,LogDateTime) AS Week#,
			DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0) AS StartDate, DateAdd(d,6, DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0)) as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''') order by logDateTime'
			

		end 
	print (@strQuery)
	exec (@strQuery)

End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogMKT_rpt_old]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterLogMKT_rpt] '2010-02-16','2018-08-22',10028,',1,3,5,7,9,11,13,15,17,19,',',Temperature1,Temperature2,Temperature3,Temperature4,Temperature5,Temperature6,Temperature7,Temperature8,Temperature9,Temperature10,','w'
--[EquipmentMasterLogMKT_rpt] '2019/08/01 00:00','2019/08/01 23:59','81','26,30','Temperature1,Temperature3','D'
CREATE PROCEDURE [dbo].[EquipmentMasterLogMKT_rpt_old]
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@EquipmentName AS nvarchar(100)='',
	@Parameter AS varchar(1000)='',
	@ParameterName AS varchar(4000)='',
	@ActionMode as varchar(3)='d'

AS
Begin

	Declare @strQuery as Varchar(5000),@NewParameterName as Varchar(4000)
	Declare @TempParaName as nvarchar(100)
	DECLARE @strMax as varchar(4000),@stMin as varchar(4000),@strAvg as varchar(4000),@i as int,@j as int
	
	Set @strMax=''
	Set @stMin=''
	Set @strAvg=''
	Set @NewParameterName=''
	
	Set @i=1
	Set @j=1
	Set @TempParaName=@ParameterName
	 
	While @i<=20
	Begin
		if CHARINDEX(','+ Cast(@i as varchar(2))+',',@Parameter)>0
			Begin
			
				print (@i)
				Set @strMax=@strMax+ ',isnull(Max'+Cast(@i as varchar(2))+',0.00) AS MaxValue'++Cast(@j as varchar(2))
				Set @stMin=@stMin+ ',isnull(Min'+Cast(@i as varchar(2))+',0.00) AS MinValue'++Cast(@j as varchar(2))
				Set @strAvg=@strAvg+ ',isnull(Avg'+Cast(@i as varchar(2))+',0.00) AS MeanValue'++Cast(@j as varchar(2))
				
				Set @TempParaName = substring(@ParameterName,CHARINDEX(',',@ParameterName,1)+1,CHARINDEX(',',@ParameterName,2)-2)
				Set @NewParameterName=@NewParameterName + ','''+ @TempParaName +''' AS ParameterName'++Cast(@j as varchar(2))
				print(@TempParaName)
				Set @ParameterName=replace(@ParameterName,','+substring(@ParameterName,CHARINDEX(',',@ParameterName,1)+1,CHARINDEX(',',@ParameterName,2)-2)+',',',')
				print(@ParameterName)
				Set @j = @j+1
			End
		Set @i = @i+1
	End

	While @j<=20
	Begin
		Set @strMax=@strMax+ ',isnull(Max'+Cast(@j as varchar(2))+',0.00) AS MaxValue'++Cast(@j as varchar(2))
		Set @stMin=@stMin+ ',isnull(Min'+Cast(@j as varchar(2))+',0.00) AS MinValue'++Cast(@j as varchar(2))
		Set @strAvg=@strAvg+ ',isnull(Avg'+Cast(@j as varchar(2))+',0.00) AS MeanValue'++Cast(@j as varchar(2))
		Set @NewParameterName=@NewParameterName+ ','''' AS ParameterName'++Cast(@j as varchar(2))
		Set @j = @j+1
	End
	

	if @ActionMode = 'D'
		Begin
		
			
			Set @strQuery = 'select LogDateTime as StartDate,LogDateTime as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT 
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''') order by logDateTime'
		end 

	if @ActionMode = 'M'
		Begin

			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year
			,DATEPART(m,LogDateTime) AS Week#,
			DATEADD(m, DATEDIFF(m,0,LogDateTime), 0) AS StartDate,
			((DATEADD(s,0,DATEADD(mm, DATEDIFF(m,0,LogDateTime)+1,0)) )-1) as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''')order by logDateTime'
						
		end 

	if @ActionMode = 'W'
		Begin

			Set @strQuery = 'SELECT DATEPART(YEAR,LogDateTime) AS Year,
			DATEPART(wk,LogDateTime) AS Week#,
			DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0) AS StartDate, DateAdd(d,6, DATEADD(wk, DATEDIFF(wk,0,LogDateTime), 0)) as EndDate 
			'+ @strMax + @stMin + @strAvg + @NewParameterName + ' 
			from EquipmentMasterMKT
			where EquipmentMasterId =' + @EquipmentName + '
			and MKTType =''' + @ActionMode + '''
			And (LogDateTime BETWEEN '''+cast(@ReportFromDate as varchar(50))+''' AND '''+cast(@ReportToDate as varchar(50))+''') order by logDateTime'
			

		end 
	print (@strQuery)
	exec (@strQuery)

End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterLogReviewApprove_Manage] '2011-04-01','2012-10-01'
	CREATE PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_Manage]
	@CompanyId as bigint = 0,
	@Equipment as bigint=0,
	@LogType as varchar(3)='',
	@ReviewedApproved as varchar(5)='',
	@sssUserId as NVARCHAR(100)='',	
	@FromDate as Datetime,
	@ToDate as Datetime,
	@LoginComments as nvarchar(255)='',
	@ReturnMessage as NVARCHAR(255)=''  output,
	@ReturnId as  Bigint=0 output
AS
set nocount on;
Begin

	

	create table #t (FromDate varchar(25),ToDate varchar(25))

	Declare @FromDateTime as Varchar(25) ,@ToDateTime as varchar(25),@CombineDateTime as Varchar(70)
	
	Declare @strQuery as varchar(max)
	Declare @strSubQuery as varchar(1000)
	
	Set @FromDateTime=''
	Set @ToDateTime=''
	
	Set @strQuery = 'insert into #t(FromDate,ToDate) (Select Min(LogDateTime), Max(LogDateTime) from EquipmentMasterLog_'+Cast(@Equipment as varchar(10))+' 
	where LogDateTime between ''' +  Cast(@FromDate as varchar(25)) + ''' and ''' + Cast(@ToDate as  varchar(25)) + ''' '
	IF @ReviewedApproved='R'
		BEGIN
			Set @strQuery=@strQuery+ ' And ReviewedApprovedStatus = 0 )'
		END
	ELSE
		BEGIN
			Set @strQuery=@strQuery+ ' And ReviewedApprovedStatus = 1 )'
		END
	exec(@strQuery)

	Set @FromDateTime=''
	Set @ToDateTime=''
	Set @CombineDateTime= ''
	
	select @FromDateTime=FromDate,@ToDateTime=ToDate from #t
	Set @CombineDateTime = CONVERT(VARCHAR(10), @FromDate, 105) + ' '  + convert(VARCHAR(8), @FromDate, 14)  + ' To ' + CONVERT(VARCHAR(10), @ToDate, 105) + ' '  + convert(VARCHAR(8), @ToDate, 14)
	drop table #t
	
	if isnull(@FromDateTime,'') <> '' and isnull(@ToDateTime,'')<> ''
		BEGIN
   			insert into EquipmentMasterLogReviewApprove 
   			(EquipmentMasterId,LogType,ReviewedApproved,UserId,FromDateTime,ToDateTime,ReviewedApprovedDateTime,Comments) 
   			values(@Equipment,@LogType,@ReviewedApproved,@sssUserId,@FromDateTime,@ToDateTime,GetDate(),@LoginComments)
   			IF @@rowcount > 0 
				Begin
					set @ReturnId=1
					IF @LogType='D'
						BEGIN
							IF @ReviewedApproved='R'
								BEGIN
									Set @strSubQuery='UPDATE EquipmentMasterLog_'+Cast(@Equipment as varchar(10))+' SET ReviewedApprovedStatus = 1 
									WHERE EquipmentMasterId='+ Cast(@Equipment as  varchar(25))+' AND (LogDateTime BETWEEN ''' +  Cast(@FromDate as varchar(25)) + ''' and ''' + Cast(@ToDate as  varchar(25)) + ''')'
									Exec (@strSubQuery)

									SET @ReturnMessage = 'DATA LOG REVIEWED SUCCESSFULLY'
									EXECUTE App_UserMaster_AuditTrail @CompanyId,@sssUserId,@CombineDateTime,'DATALOGREVIEW',''
									set @ReturnId=@Equipment

								END
							ELSE
								BEGIN
									Set @strSubQuery='UPDATE EquipmentMasterLog_'+Cast(@Equipment as varchar(10))+' SET ReviewedApprovedStatus = 2 
									WHERE EquipmentMasterId='+ Cast(@Equipment as  varchar(25))+' AND (LogDateTime BETWEEN ''' +  Cast(@FromDate as varchar(25)) + ''' and ''' + Cast(@ToDate as  varchar(25)) + ''')'
									Exec (@strSubQuery)

									SET @ReturnMessage = 'DATA LOG APPROVED SUCCESSFULLY'
									EXECUTE App_UserMaster_AuditTrail @CompanyId,@sssUserId,@CombineDateTime,'DATALOGAPPROVE',''
									set @ReturnId=@Equipment

								END
						END
				End
			else
				Begin
					set @ReturnId=0
					SET @ReturnMessage = 'Data Log Addition Failed ' 
				End
		END   	
	else
		Begin
			set @ReturnId=0
			Set @ReturnMessage='No Records Found...' 
		End
End	

Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--EXEC EquipmentMasterLogReviewApprove_rpt '2015-12-19 21:20:00.000','2018-06-19 23:55:00.000','3','Administrator','99,100','','R',0
CREATE PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_rpt]
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',
	@BranchId AS Bigint=0,
	@UserName AS varchar(4000)='',
	@EquipmentName AS varchar(4000)='',
	@FilterParameter AS varchar(100)='',
	--@LogType AS varchar(3)='',
	@ReviewedApproved AS varchar(3)='',
	@OrderBy as tinyint=0
AS
SET NOCOUNT ON
Begin
	Declare @strQuery Varchar(8000)
	
		BEGIN

			SET @strQuery = ' SELECT Row_Number() Over(Order by RA.EquipmentMasterLogReviewApproveId) As [Sr No], RA.EquipmentMasterLogReviewApproveId,RA.EquipmentMasterId,EM.EquipmentName,
			RA.FromDateTime,RA.ToDateTime,RA.UserId,RA.ReviewedApprovedDateTime,
			--UM.LoginName,
			RA.Comments,RA.LogType,RA.ReviewedApproved
			,(Case ' + cast(@OrderBy as nvarchar(10)) + ' When ''0'' Then '''' Else ''Unsorted'' END) AS Sorting
			FROM EquipmentMasterLogReviewApprove(NOLOCK) AS RA
			Outer Apply  
			(  
				Select LogType from  
				EquipmentMasterLogReviewApprove(NOLOCK) EMA Where  
				EMA.EquipmentMasterId = RA.EquipmentMasterId  
				And RA.FromDateTime = EMA.FromDateTime AND RA.ToDateTime = EMA.ToDateTime  
				AND EMA.ReviewedApproved = ''A''  
			)EMA 
			INNER JOIN EquipmentMaster(NOLOCK) AS EM ON RA.EquipmentMasterId = EM.EquipmentMasterId '
			--INNER JOIN UserMaster AS UM ON RA.UserId = UM.UserId Where RA.EquipmentMasterId > 0
					
			IF @UserName <> '' 
				BEGIN
					SET @strQuery = @strQuery + ' AND (RA.UserId in(select * from CSVTOTable(''' + CAST(@UserName as varchar(4000)) +'''))) '
				END
				
			IF @EquipmentName <> '' 
				BEGIN
					SET @strQuery = @strQuery + ' AND (EM.EquipmentMasterId in(select * from CSVTOTable(''' + CAST(@EquipmentName as varchar(4000)) +'''))) '
				END
								
			SET @strQuery = @strQuery + ' AND RA.FromDateTime BETWEEN ''' + CAST(@ReportFromDate as varchar(25)) + ''' AND ''' + 
			Cast(@ReportToDate as varchar(25)) + ''' AND RA.ToDateTime BETWEEN ''' + CAST(@ReportFromDate as varchar(25)) + ''' AND '''+
			Cast(@ReportToDate as varchar(25)) + '''
			--AND RA.LogType= ''' 
			--+ CAST(@LogType as varchar(3)) + ''''
			
			SET @strQuery = @strQuery + ' AND (RA.ReviewedApproved in (select * from CSVTOTable( ''' + CAST(@ReviewedApproved as varchar(3)) + ''')))'
			
		END
		
		IF @ReviewedApproved = 'R'
			BEGIN
				SET @strQuery = @strQuery + ' AND EMA.LogType IS NULL'
			END
		
		IF @ReviewedApproved = 'R,A'
			BEGIN
				SET @strQuery = @strQuery + ' AND EMA.LogType IS NOT NULL'
			END
		
		if @OrderBy = 0 
			Begin
				SET @strQuery = @strQuery + ' ORDER BY RA.ReviewedApprovedDateTime'
			end
		else
			Begin
				SET @strQuery = @strQuery + ' ORDER BY RA.EquipmentMasterLogReviewApproveId'
			end
	PRINT(@strQuery)
	EXEC(@strQuery)

End
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApprove_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterLogReviewApprove_Sync] 3
CREATE PROCEDURE [dbo].[EquipmentMasterLogReviewApprove_Sync]
	@BranchId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record


--SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove ON
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove
			([EquipmentMasterLogReviewApproveId],[EquipmentMasterId],[LogType],[ReviewedApproved],[UserId],[FromDateTime],[ToDateTime],[ReviewedApprovedDateTime],[Comments])
		select
			SourceDBTable.[EquipmentMasterLogReviewApproveId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[LogType] ,SourceDBTable.[ReviewedApproved]
			,SourceDBTable.[UserId],SourceDBTable.[FromDateTime],SourceDBTable.[ToDateTime],SourceDBTable.[ReviewedApprovedDateTime],SourceDBTable.[Comments]
		from EquipmentMasterLogReviewApprove(NOLOCK) SourceDBTable inner join EquipmentMaster EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND FromDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove(NOLOCK) DestinationDBTable
						 where DestinationDBTable.EquipmentMasterLogReviewApproveId = SourceDBTable.EquipmentMasterLogReviewApproveId)
--SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove OFF
			
--Update Record			

	update  ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[LogType]=SourceDBTable.[LogType],[ReviewedApproved]=SourceDBTable.[ReviewedApproved]
		   ,[UserId]=SourceDBTable.[UserId],[FromDateTime]=SourceDBTable.[FromDateTime],[ToDateTime]=SourceDBTable.[ToDateTime]
		   ,[ReviewedApprovedDateTime]=SourceDBTable.[ReviewedApprovedDateTime],[Comments]=SourceDBTable.[Comments]
	from	ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove DestinationDBTable,
			(
				select	max(TableName) as TableName,[EquipmentMasterLogReviewApproveId],[EquipmentMasterId],[LogType],[ReviewedApproved],[UserId],[FromDateTime],[ToDateTime],[ReviewedApprovedDateTime],[Comments],[BranchId]
				from
					(
						select	'SourceTableName' as TableName,[EquipmentMasterLogReviewApproveId],SourceTableName.[EquipmentMasterId],[LogType],[ReviewedApproved],[UserId],[FromDateTime],[ToDateTime],[ReviewedApprovedDateTime],[Comments],[BranchId]
						from EquipmentMasterLogReviewApprove(NOLOCK) SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName, [EquipmentMasterLogReviewApproveId],DestinationTableName.[EquipmentMasterId],[LogType],[ReviewedApproved],[UserId],[FromDateTime],[ToDateTime],[ReviewedApprovedDateTime],[Comments],[BranchId]
						from ICDAS_3_0_Archive.dbo.EquipmentMasterLogReviewApprove(NOLOCK) DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EquipmentMasterLogReviewApproveId],[EquipmentMasterId],[LogType],[ReviewedApproved],[UserId],[FromDateTime],[ToDateTime],[ReviewedApprovedDateTime],[Comments],[BranchId]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.EquipmentMasterLogReviewApproveId = SourceDBTable.EquipmentMasterLogReviewApproveId and SourceDBTable.BranchId=@BranchId
	
--Delete Record	
		
		Delete From EquipmentMasterLogReviewApprove Where EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@BranchId AND FromDateTime<=@LogDateTime)

			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterLogReviewApproveAuditTrail_rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Exec EquipmentMasterLogReviewApproveAuditTrail_rpt 3,'2018/06/01 00:00', '2018/07/10 23:59', '', '', '', 'A', '0'
CREATE PROCEDURE [dbo].[EquipmentMasterLogReviewApproveAuditTrail_rpt]
	@BranchId AS Bigint=0,
	@ReportFromDate AS DATETIME='',
	@ReportToDate AS DATETIME='',	
	@UserList AS varchar(4000)='',
	@EquipmentList AS varchar(4000)='',
	@FilterParameter AS varchar(100)='',
	--@LogType AS varchar(3)='',
	@ReviewedApproved AS varchar(3)='',
	@OrderBy as tinyint=0
AS
SET NOCOUNT ON
Begin
	Declare @strQuery Varchar(8000)
	
		BEGIN
		
			IF @ReviewedApproved = 'R'
				BEGIN
					SELECT Row_Number() Over(Order by RA.EquipmentMasterLogReviewApproveId) As [Sr No], 
					Convert(varchar, RA.ReviewedApprovedDateTime, 105) As [Date], 
					substring(convert(varchar(8), RA.ReviewedApprovedDateTime, 108), 0, 6) As [Time], 
					EM.EquipmentName As [Equipment Name], RA.UserId As [Reviewed By], 
					Convert(varchar, RA.FromDateTime, 105) As [From Date], 
					substring(convert(varchar(8), RA.FromDateTime, 108), 0, 6) As [From Time], 
					Convert(varchar, RA.ToDateTime, 105) As [To Date], 
					substring(convert(varchar(8), RA.ToDateTime, 108), 0, 6) As [To Time], RA.Comments
					FROM EquipmentMasterLogReviewApprove (NOLOCK) AS RA 
					INNER JOIN EquipmentMaster (NOLOCK) AS EM ON RA.EquipmentMasterId = EM.EquipmentMasterId 
					Where RA.EquipmentMasterId >0  
					AND (@UserList='' OR RA.UserId in(select * from CSVTOTable(CAST(@UserList as varchar(4000)))))
					AND (@EquipmentList='' OR RA.EquipmentMasterId in(select * from CSVTOTable(CAST(@EquipmentList as varchar(4000)))))
					AND (RA.FromDateTime BETWEEN CAST(@ReportFromDate as varchar(25)) AND Cast(@ReportToDate as varchar(25)))
					AND (RA.ToDateTime BETWEEN  CAST(@ReportFromDate as varchar(25))  AND Cast(@ReportToDate as varchar(25))) 
					--AND RA.LogType= CAST(@LogType as varchar(3))
					AND (RA.ReviewedApproved in (select * from CSVTOTable(CAST(@ReviewedApproved as varchar(3)))))
					ORDER BY (CASE @OrderBy WHEN 0 THEN RA.ReviewedApprovedDateTime ELSE RA.EquipmentMasterLogReviewApproveId END)
				END
			ELSE
				BEGIN
					SELECT Row_Number() Over(Order by RA.EquipmentMasterLogReviewApproveId) As [Sr No], 
					Convert(varchar, RA.ReviewedApprovedDateTime, 105) As [Date], 
					substring(convert(varchar(8), RA.ReviewedApprovedDateTime, 108), 0, 6) As [Time], 
					EM.EquipmentName As [Equipment Name], RA.UserId As [Approved By], 
					Convert(varchar, RA.FromDateTime, 105) As [From Date], 
					substring(convert(varchar(8), RA.FromDateTime, 108), 0, 6) As [From Time], 
					Convert(varchar, RA.ToDateTime, 105) As [To Date], 
					substring(convert(varchar(8), RA.ToDateTime, 108), 0, 6) As [To Time], 
					RA.Comments
					FROM EquipmentMasterLogReviewApprove (NOLOCK) AS RA 
					INNER JOIN EquipmentMaster (NOLOCK) AS EM ON RA.EquipmentMasterId = EM.EquipmentMasterId 
					Where RA.EquipmentMasterId >0 
					AND (@UserList='' OR RA.UserId in(select * from CSVTOTable(CAST(@UserList as varchar(4000)))))
					AND (@EquipmentList='' OR EM.EquipmentMasterId in(select * from CSVTOTable(CAST(@EquipmentList as varchar(4000)))))
					AND (RA.FromDateTime BETWEEN CAST(@ReportFromDate as varchar(25)) AND Cast(@ReportToDate as varchar(25)))
					AND (RA.ToDateTime BETWEEN  CAST(@ReportFromDate as varchar(25))  AND Cast(@ReportToDate as varchar(25))) 
					--AND RA.LogType= CAST(@LogType as varchar(3))
					AND RA.ReviewedApproved in (select * from CSVTOTable(CAST(@ReviewedApproved as varchar(3))))
					ORDER BY (CASE @OrderBy WHEN 0 THEN RA.ReviewedApprovedDateTime ELSE RA.EquipmentMasterLogReviewApproveId END)
				END
			
		END
End
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMKT_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

--exec [EquipmentMasterMKT_Manage] '2018-Aug-30 00:00:00','2018-Aug-31 00:00:00',5,'D','admin'
CREATE PROCEDURE [dbo].[EquipmentMasterMKT_Manage]
@FromDate AS DATETIME='',
@ToDate AS DATETIME='',
@EquipmentMasterId as bigint,
@MKTType as nvarchar(5) = '',
@UserName as nvarchar(50)


AS
Begin
		Declare	@strSubQuery1 as VARCHAR(max),@strSubQuery2 as VARCHAR(max),@strSubQuery3 as VARCHAR(max),
		@strSubQuery4 as VARCHAR(max),@strSubQuery5 as VARCHAR(max),@strSubQuery6 as VARCHAR(max),@strQuery as VARCHAR(max),@MKTStatus as nvarchar(5)
		
		Set @strSubQuery1 = 'insert into EquipmentMasterMKT (EquipmentMasterId,LogDateTime,MKTType,UserName
		,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2],[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
		,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6],[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
		,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10],[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
		,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14],[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
		,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18],[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20])
		(
			Select '+ Cast(@EquipmentMasterId as varchar(10)) +',''' +  CONVERT(VARCHAR(10), @FromDate, 110) + ''',''' + @MKTType + ''',''' + @UserName + '''
			,EML.Min1,EML.Avg1,EML.Max1,EML.Min2,EML.Avg2,EML.Max2
			,EML.Min3,EML.Avg3,EML.Max3,EML.Min4,EML.Avg4,EML.Max4
			,EML.Min5,EML.Avg5,EML.Max5,EML.Min6,EML.Avg6,EML.Max6
			,EML.Min7,EML.Avg7,EML.Max7,EML.Min8,EML.Avg8,EML.Max8
			,EML.Min9,EML.Avg9,EML.Max9,EML.Min10,EML.Avg10,EML.Max10
			,EML.Min11,EML.Avg11,EML.Max11,EML.Min12,EML.Avg12,EML.Max12
			,EML.Min13,EML.Avg13,EML.Max13,EML.Min14,EML.Avg14,EML.Max14
			,EML.Min15,EML.Avg15,EML.Max15,EML.Min16,EML.Avg16,EML.Max16
			,EML.Min17,EML.Avg17,EML.Max17,EML.Min18,EML.Avg18,EML.Max18
			,EML.Min19,EML.Avg19,EML.Max19,EML.Min20,EML.Avg20,EML.Max20
			
			From (
					Select 
					 Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue1) When 0 Then 0 Else Cast(SensorValue1 as numeric(18,2)) End))) as Min1
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue1) When 0 Then 0 Else Cast(SensorValue1 as numeric(18,2)) End))) as Avg1
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue1) When 0 Then 0 Else Cast(SensorValue1 as numeric(18,2)) End))) as Max1
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue2) When 0 Then 0 Else Cast(SensorValue2 as numeric(18,2)) End))) as Min2
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue2) When 0 Then 0 Else Cast(SensorValue2 as numeric(18,2)) End))) as Avg2
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue2) When 0 Then 0 Else Cast(SensorValue2 as numeric(18,2)) End))) as Max2
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue3) When 0 Then 0 Else Cast(SensorValue3 as numeric(18,2)) End))) as Min3
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue3) When 0 Then 0 Else Cast(SensorValue3 as numeric(18,2)) End))) as Avg3
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue3) When 0 Then 0 Else Cast(SensorValue3 as numeric(18,2)) End))) as Max3'
					
				Set @strSubQuery2 = ',Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue4) When 0 Then 0 Else Cast(SensorValue4 as numeric(18,2)) End))) as Min4
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue4) When 0 Then 0 Else Cast(SensorValue4 as numeric(18,2)) End))) as Avg4
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue4) When 0 Then 0 Else Cast(SensorValue4 as numeric(18,2)) End))) as Max4
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue5) When 0 Then 0 Else Cast(SensorValue5 as numeric(18,2)) End))) as Min5
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue5) When 0 Then 0 Else Cast(SensorValue5 as numeric(18,2)) End))) as Avg5
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue5) When 0 Then 0 Else Cast(SensorValue5 as numeric(18,2)) End))) as Max5
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue6) When 0 Then 0 Else Cast(SensorValue6 as numeric(18,2)) End))) as Min6
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue6) When 0 Then 0 Else Cast(SensorValue6 as numeric(18,2)) End))) as Avg6
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue6) When 0 Then 0 Else Cast(SensorValue6 as numeric(18,2)) End))) as Max6
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue7) When 0 Then 0 Else Cast(SensorValue7 as numeric(18,2)) End))) as Min7
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue7) When 0 Then 0 Else Cast(SensorValue7 as numeric(18,2)) End))) as Avg7
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue7) When 0 Then 0 Else Cast(SensorValue7 as numeric(18,2)) End))) as Max7
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue8) When 0 Then 0 Else Cast(SensorValue8 as numeric(18,2)) End))) as Min8
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue8) When 0 Then 0 Else Cast(SensorValue8 as numeric(18,2)) End))) as Avg8
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue8) When 0 Then 0 Else Cast(SensorValue8 as numeric(18,2)) End))) as Max8
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue9) When 0 Then 0 Else Cast(SensorValue9 as numeric(18,2)) End))) as Min9
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue9) When 0 Then 0 Else Cast(SensorValue9 as numeric(18,2)) End))) as Avg9
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue9) When 0 Then 0 Else Cast(SensorValue9 as numeric(18,2)) End))) as Max9
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue10) When 0 Then 0 Else Cast(SensorValue10 as numeric(18,2)) End))) as Min10
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue10) When 0 Then 0 Else Cast(SensorValue10 as numeric(18,2)) End))) as Avg10
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue10) When 0 Then 0 Else Cast(SensorValue10 as numeric(18,2)) End))) as Max10'
					
				Set @strSubQuery3 =	',Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue11) When 0 Then 0 Else Cast(SensorValue11 as numeric(18,2)) End))) as Min11
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue11) When 0 Then 0 Else Cast(SensorValue11 as numeric(18,2)) End))) as Avg11
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue11) When 0 Then 0 Else Cast(SensorValue11 as numeric(18,2)) End))) as Max11
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue12) When 0 Then 0 Else Cast(SensorValue12 as numeric(18,2)) End))) as Min12
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue12) When 0 Then 0 Else Cast(SensorValue12 as numeric(18,2)) End))) as Avg12
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue12) When 0 Then 0 Else Cast(SensorValue12 as numeric(18,2)) End))) as Max12
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue13) When 0 Then 0 Else Cast(SensorValue13 as numeric(18,2)) End))) as Min13
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue13) When 0 Then 0 Else Cast(SensorValue13 as numeric(18,2)) End))) as Avg13
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue13) When 0 Then 0 Else Cast(SensorValue13 as numeric(18,2)) End))) as Max13
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue14) When 0 Then 0 Else Cast(SensorValue14 as numeric(18,2)) End))) as Min14
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue14) When 0 Then 0 Else Cast(SensorValue14 as numeric(18,2)) End))) as Avg14
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue14) When 0 Then 0 Else Cast(SensorValue14 as numeric(18,2)) End))) as Max14
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue15) When 0 Then 0 Else Cast(SensorValue15 as numeric(18,2)) End))) as Min15
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue15) When 0 Then 0 Else Cast(SensorValue15 as numeric(18,2)) End))) as Avg15
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue15) When 0 Then 0 Else Cast(SensorValue15 as numeric(18,2)) End))) as Max15
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue16) When 0 Then 0 Else Cast(SensorValue16 as numeric(18,2)) End))) as Min16
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue16) When 0 Then 0 Else Cast(SensorValue16 as numeric(18,2)) End))) as Avg16
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue16) When 0 Then 0 Else Cast(SensorValue16 as numeric(18,2)) End))) as Max16'
					
			  Set @strSubQuery4 = ',Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue17) When 0 Then 0 Else Cast(SensorValue17 as numeric(18,2)) End))) as Min17
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue17) When 0 Then 0 Else Cast(SensorValue17 as numeric(18,2)) End))) as Avg17
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue17) When 0 Then 0 Else Cast(SensorValue17 as numeric(18,2)) End))) as Max17
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue18) When 0 Then 0 Else Cast(SensorValue18 as numeric(18,2)) End))) as Min18
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue18) When 0 Then 0 Else Cast(SensorValue18 as numeric(18,2)) End))) as Avg18
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue18) When 0 Then 0 Else Cast(SensorValue18 as numeric(18,2)) End))) as Max18
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue19) When 0 Then 0 Else Cast(SensorValue19 as numeric(18,2)) End))) as Min19
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue19) When 0 Then 0 Else Cast(SensorValue19 as numeric(18,2)) End))) as Avg19
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue19) When 0 Then 0 Else Cast(SensorValue19 as numeric(18,2)) End))) as Max19
					
					,Convert(DECIMAL(10,2),min((Case isnumeric(SensorValue20) When 0 Then 0 Else Cast(SensorValue20 as numeric(18,2)) End))) as Min20
					,Convert(DECIMAL(10,2),Avg((Case isnumeric(SensorValue20) When 0 Then 0 Else Cast(SensorValue20 as numeric(18,2)) End))) as Avg20
					,Convert(DECIMAL(10,2),Max((Case isnumeric(SensorValue20) When 0 Then 0 Else Cast(SensorValue20 as numeric(18,2)) End))) as Max20
					
					from EquipmentMasterLog_'+Cast(@EquipmentMasterId as varchar(10))+' 
													
					where (LogDateTime BETWEEN '''+ cast(@FromDate as varchar(50))+''' AND ''' + cast(@ToDate as varchar(50))+''')
					
													 
				  ) AS EML
			
		)'
				
				
		--PRINT(@strSubQuery2 + @strSubQuery3 + @strSubQuery4)								
		 Execute(@strSubQuery1+ @strSubQuery2+@strSubQuery3+ @strSubQuery4 )
	
End


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMKT_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EquipmentMasterMKT_Sync 1
CREATE PROCEDURE [dbo].[EquipmentMasterMKT_Sync]
	@BranchId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
	
SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterMKT ON
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMasterMKT
			([EquipmentMasterMKTId],[EquipmentMasterId],[MKTType],[LogDateTime]
			,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2]
           ,[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
           ,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6]
           ,[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
           ,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10]
           ,[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
           ,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14]
           ,[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
           ,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18]
           ,[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20]
           )
		select
			SourceDBTable.[EquipmentMasterMKTId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[MKTType] ,SourceDBTable.[LogDateTime]
			,SourceDBTable.[Min1],SourceDBTable.[Avg1],SourceDBTable.[Max1]
			,SourceDBTable.[Min2],SourceDBTable.[Avg2],SourceDBTable.[Max2]
			,SourceDBTable.[Min3],SourceDBTable.[Avg3],SourceDBTable.[Max3]
			,SourceDBTable.[Min4],SourceDBTable.[Avg4],SourceDBTable.[Max4]
			,SourceDBTable.[Min5],SourceDBTable.[Avg5],SourceDBTable.[Max5]
			,SourceDBTable.[Min6],SourceDBTable.[Avg6],SourceDBTable.[Max6]
			,SourceDBTable.[Min7],SourceDBTable.[Avg7],SourceDBTable.[Max7]
			,SourceDBTable.[Min8],SourceDBTable.[Avg8],SourceDBTable.[Max8]
			,SourceDBTable.[Min9],SourceDBTable.[Avg9],SourceDBTable.[Max9]
			,SourceDBTable.[Min10],SourceDBTable.[Avg10],SourceDBTable.[Max10]
			,SourceDBTable.[Min11],SourceDBTable.[Avg11],SourceDBTable.[Max11]
			,SourceDBTable.[Min12],SourceDBTable.[Avg12],SourceDBTable.[Max12]
			,SourceDBTable.[Min13],SourceDBTable.[Avg13],SourceDBTable.[Max13]
			,SourceDBTable.[Min14],SourceDBTable.[Avg14],SourceDBTable.[Max14]
			,SourceDBTable.[Min15],SourceDBTable.[Avg15],SourceDBTable.[Max15]
			,SourceDBTable.[Min16],SourceDBTable.[Avg16],SourceDBTable.[Max16]
			,SourceDBTable.[Min17],SourceDBTable.[Avg17],SourceDBTable.[Max17]
			,SourceDBTable.[Min18],SourceDBTable.[Avg18],SourceDBTable.[Max18]
			,SourceDBTable.[Min19],SourceDBTable.[Avg19],SourceDBTable.[Max19]
			,SourceDBTable.[Min20],SourceDBTable.[Avg20],SourceDBTable.[Max20]
		from EquipmentMasterMKT(NOLOCK) SourceDBTable inner join EquipmentMaster EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where BranchId=@BranchId AND LogDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterMKT DestinationDBTable
						 where DestinationDBTable.EquipmentMasterMKTId = SourceDBTable.EquipmentMasterMKTId)
		
SET  identity_insert ICDAS_3_0_Archive.dbo.EquipmentMasterMKT OFF			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.EquipmentMasterMKT 
	set      [EquipmentMasterId] = SourceDBTable.[EquipmentMasterId],[MKTType] = SourceDBTable.[MKTType] ,[LogDateTime] = SourceDBTable.[LogDateTime]
			,[Min1] = SourceDBTable.[Min1],[Avg1] = SourceDBTable.[Avg1],[Max1] = SourceDBTable.[Max1]
			,[Min2] = SourceDBTable.[Min2],[Avg2] = SourceDBTable.[Avg2],[Max2] = SourceDBTable.[Max2]
			,[Min3] = SourceDBTable.[Min3],[Avg3] = SourceDBTable.[Avg3],[Max3] = SourceDBTable.[Max3]
			,[Min4] = SourceDBTable.[Min4],[Avg4] = SourceDBTable.[Avg4],[Max4] = SourceDBTable.[Max4]
			,[Min5] = SourceDBTable.[Min5],[Avg5] = SourceDBTable.[Avg5],[Max5] = SourceDBTable.[Max5]
			,[Min6] = SourceDBTable.[Min6],[Avg6] = SourceDBTable.[Avg6],[Max6] = SourceDBTable.[Max6]
			,[Min7] = SourceDBTable.[Min7],[Avg7] = SourceDBTable.[Avg7],[Max7] = SourceDBTable.[Max7]
			,[Min8] = SourceDBTable.[Min8],[Avg8] = SourceDBTable.[Avg8],[Max8] = SourceDBTable.[Max8]
			,[Min9] = SourceDBTable.[Min9],[Avg9] = SourceDBTable.[Avg9],[Max9] = SourceDBTable.[Max9]
			,[Min10] = SourceDBTable.[Min10],[Avg10] = SourceDBTable.[Avg10],[Max10] = SourceDBTable.[Max10]
			,[Min11] = SourceDBTable.[Min11],[Avg11] = SourceDBTable.[Avg11],[Max11] = SourceDBTable.[Max11]
			,[Min12] = SourceDBTable.[Min12],[Avg12] = SourceDBTable.[Avg12],[Max12] = SourceDBTable.[Max12]
			,[Min13] = SourceDBTable.[Min13],[Avg13] = SourceDBTable.[Avg13],[Max13] = SourceDBTable.[Max13]
			,[Min14] = SourceDBTable.[Min14],[Avg14] = SourceDBTable.[Avg14],[Max14] = SourceDBTable.[Max14]
			,[Min15] = SourceDBTable.[Min15],[Avg15] = SourceDBTable.[Avg15],[Max15] = SourceDBTable.[Max15]
			,[Min16] = SourceDBTable.[Min16],[Avg16] = SourceDBTable.[Avg16],[Max16] = SourceDBTable.[Max16]
			,[Min17] = SourceDBTable.[Min17],[Avg17] = SourceDBTable.[Avg17],[Max17] = SourceDBTable.[Max17]
			,[Min18] = SourceDBTable.[Min18],[Avg18] = SourceDBTable.[Avg18],[Max18] = SourceDBTable.[Max18]
			,[Min19] = SourceDBTable.[Min19],[Avg19] = SourceDBTable.[Avg19],[Max19] = SourceDBTable.[Max19]
			,[Min20] = SourceDBTable.[Min20],[Avg20] = SourceDBTable.[Avg20],[Max20] = SourceDBTable.[Max20]
	
	from	ICDAS_3_0_Archive.dbo.EquipmentMasterMKT DestinationDBTable,
			(
				select	max(TableName) as TableName,[EquipmentMasterMKTId],[EquipmentMasterId],[MKTType] ,[LogDateTime]
			            ,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2]
                        ,[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
                        ,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6]
                        ,[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
                        ,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10]
                        ,[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
                        ,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14]
                        ,[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
                        ,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18]
                        ,[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20],[BranchId]  
				from
					(
						select	'SourceTableName' as TableName,[EquipmentMasterMKTId],SourceTableName.[EquipmentMasterId],[MKTType] ,[LogDateTime]
			            ,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2]
                        ,[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
                        ,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6]
                        ,[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
                        ,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10]
                        ,[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
                        ,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14]
                        ,[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
                        ,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18]
                        ,[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20],[BranchId]
						from EquipmentMasterMKT SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName,[EquipmentMasterMKTId],DestinationTableName.[EquipmentMasterId],[MKTType] ,[LogDateTime]
			            ,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2]
                        ,[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
                        ,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6]
                        ,[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
                        ,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10]
                        ,[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
                        ,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14]
                        ,[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
                        ,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18]
                        ,[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20],[BranchId]
						from ICDAS_3_0_Archive.dbo.EquipmentMasterMKT DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EquipmentMasterMKTId],[EquipmentMasterId],[MKTType] ,[LogDateTime]
			            ,[Min1],[Avg1],[Max1],[Min2],[Avg2],[Max2]
                        ,[Min3],[Avg3],[Max3],[Min4],[Avg4],[Max4]
                        ,[Min5],[Avg5],[Max5],[Min6],[Avg6],[Max6]
                        ,[Min7],[Avg7],[Max7],[Min8],[Avg8],[Max8]
                        ,[Min9],[Avg9],[Max9],[Min10],[Avg10],[Max10]
                        ,[Min11],[Avg11],[Max11],[Min12],[Avg12],[Max12]
                        ,[Min13],[Avg13],[Max13],[Min14],[Avg14],[Max14]
                        ,[Min15],[Avg15],[Max15],[Min16],[Avg16],[Max16]
                        ,[Min17],[Avg17],[Max17],[Min18],[Avg18],[Max18]
                        ,[Min19],[Avg19],[Max19],[Min20],[Avg20],[Max20],[BranchId] 
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable
	where DestinationDBTable.EquipmentMasterMKTId = SourceDBTable.EquipmentMasterMKTId and SourceDBTable.BranchId=@BranchId
		
--Delete Record	
		
		Delete From EquipmentMasterMKT Where LogDateTime<=@LogDateTime AND EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@BranchId )

		
			
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterMovingLog_CreateTable]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- [EquipmentMasterMovingLog_CreateTable] '1'
CREATE PROCEDURE [dbo].[EquipmentMasterMovingLog_CreateTable]
	@EquipmentMasterId as nvarchar(10)
AS
	SET NOCOUNT ON

BEGIN

	Declare @strQuery as varchar(max),@strQuery1 as varchar(max),@strQuery2 as varchar(max),@strQuery3 as varchar(max)
	
	Set @strQuery = 'CREATE TABLE EquipmentMasterMovingLog_' + @EquipmentMasterId + '(
	[EquipmentMasterMovingLogId_' + @EquipmentMasterId + '] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentMasterId] [bigint] NULL,
	[LogDateTime] [datetime] NULL UNIQUE,
	[Min1] [nvarchar](10) NULL,	[Avg1] [nvarchar](10) NULL,	[Max1] [nvarchar](10) NULL,	[Min2] [nvarchar](10) NULL,	[Avg2] [nvarchar](10) NULL,	[Max2] [nvarchar](10) NULL,
	[Min3] [nvarchar](10) NULL,	[Avg3] [nvarchar](10) NULL,	[Max3] [nvarchar](10) NULL,	[Min4] [nvarchar](10) NULL,	[Avg4] [nvarchar](10) NULL,	[Max4] [nvarchar](10) NULL,
	[Min5] [nvarchar](10) NULL,	[Avg5] [nvarchar](10) NULL,	[Max5] [nvarchar](10) NULL,	[Min6] [nvarchar](10) NULL,	[Avg6] [nvarchar](10) NULL,	[Max6] [nvarchar](10) NULL,
	[Min7] [nvarchar](10) NULL,	[Avg7] [nvarchar](10) NULL,	[Max7] [nvarchar](10) NULL,	[Min8] [nvarchar](10) NULL,	[Avg8] [nvarchar](10) NULL,	[Max8] [nvarchar](10) NULL,
	[Min9] [nvarchar](10) NULL,	[Avg9] [nvarchar](10) NULL,	[Max9] [nvarchar](10) NULL,	[Min10] [nvarchar](10) NULL,	[Avg10] [nvarchar](10) NULL,	[Max10] [nvarchar](10) NULL,'
	
	Set @strQuery1 = '[Min11] [nvarchar](10) NULL,	[Avg11] [nvarchar](10) NULL,	[Max11] [nvarchar](10) NULL,	[Min12] [nvarchar](10) NULL,	[Avg12] [nvarchar](10) NULL,	[Max12] [nvarchar](10) NULL,
	[Min13] [nvarchar](10) NULL,	[Avg13] [nvarchar](10) NULL,	[Max13] [nvarchar](10) NULL,	[Min14] [nvarchar](10) NULL,	[Avg14] [nvarchar](10) NULL,	[Max14] [nvarchar](10) NULL,
	[Min15] [nvarchar](10) NULL,	[Avg15] [nvarchar](10) NULL,	[Max15] [nvarchar](10) NULL,	[Min16] [nvarchar](10) NULL,	[Avg16] [nvarchar](10) NULL,	[Max16] [nvarchar](10) NULL,
	[Min17] [nvarchar](10) NULL,	[Avg17] [nvarchar](10) NULL,	[Max17] [nvarchar](10) NULL,	[Min18] [nvarchar](10) NULL,	[Avg18] [nvarchar](10) NULL,	[Max18] [nvarchar](10) NULL,
	[Min19] [nvarchar](10) NULL,	[Avg19] [nvarchar](10) NULL,	[Max19] [nvarchar](10) NULL,	[Min20] [nvarchar](10) NULL,	[Avg20] [nvarchar](10) NULL,	[Max20] [nvarchar](10) NULL'
	
	
	Set @strQuery2 = ' CONSTRAINT [PK_EquipmentMasterMovingLog_' + @EquipmentMasterId + '] PRIMARY KEY CLUSTERED 
	(
	[EquipmentMasterMovingLogId_' + @EquipmentMasterId + '] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
	'
	Execute(@strQuery + @strQuery1 + @strQuery2 )
	
	
	Execute ('ALTER TABLE [EquipmentMasterMovingLog_' + @EquipmentMasterId + ']  WITH CHECK ADD  CONSTRAINT [FK_EquipmentMasterMovingLog_' + @EquipmentMasterId + '_EquipmentMaster] FOREIGN KEY([EquipmentMasterId])
	REFERENCES [EquipmentMaster] ([EquipmentMasterId])')
	 
	Execute ('ALTER TABLE [EquipmentMasterMovingLog_' + @EquipmentMasterId + '] CHECK CONSTRAINT [FK_EquipmentMasterMovingLog_' + @EquipmentMasterId + '_EquipmentMaster]')
	
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterOnlineStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[EquipmentMasterOnlineStatus_Update]
	@EquipmentMasterId AS  nVarchar(500)=''
AS
SET NOCOUNT ON;
BEGIN
		Update EquipmentMaster Set  EquipmentOnlineStatus=1	
		Where EquipmentMasterId in (Select * from dbo.CSVTotable(@EquipmentMasterId))
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_CreateList]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--select * from EquipmentMasterParameter
-- exec [EquipmentMasterParameter_CreateList] 48,'COT1H1'
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_CreateList] 
	@EquipmentMasterId as BIGINT =0,
	@EquipmentType as nvarchar(10)=''
AS
Set nocount on;
BEGIN

	DECLARE @i AS BIGINT,
	@ParaNo as tinyint,
	@ParaName AS VARCHAR(50),@ParaUnit AS VARCHAR(10),@ParameterHighLimit as nvarchar(50),@ParameterLowLimit as nvarchar(50),
	@ParameterColor as nvarchar(50),@ParameterColorCode as nvarchar(50),@ParameterResolution as VARCHAR(5),@ParameterType as nvarchar(50)
	DECLARE @Axis AS Int,@strRecordkey as nvarchar(10),@EquipmentParameterMaxValue as bigint,@hdnRecordKeyId as Bigint
	
	SET @ParaNo=0
	
	SET @EquipmentParameterMaxValue = 0
	
	SELECT @ParaNo=ParameterNo FROM EquipmentType (NoLock) WHERE EquipmentType=@EquipmentType
	Set @Axis=0
	SET @i=1

				
		WHILE @ParaNo != 0
			BEGIN
			
				Select @ParaName=dbo.SplitString(Parameter,'@',@i),@ParaUnit=dbo.SplitString(ParameterUnit,'@',@i),
				@ParameterLowLimit=dbo.SplitString(ParameterLowLimit,'@',@i),@ParameterHighLimit=dbo.SplitString(ParameterHighLimit,'@',@i),
				@ParameterColor=dbo.SplitString(ParameterColor,'@',@i),@ParameterColorCode=dbo.SplitString(ParameterColorCode,'@',@i),
				@ParameterResolution=dbo.SplitString(ParameterResolution,'@',@i),@ParameterType=dbo.SplitString(ParameterType,'@',@i)
				From EquipmentType (NoLock) Where EquipmentType=@EquipmentType
				
				INSERT INTO EquipmentMasterParameter(EquipmentMasterId,ParameterName
				,ParameterUnit,ParameterResolution,ParameterColor,ParameterColorCode,ParameterLowerLimit,ParameterUpperLimit,ParameterRealValue,ParameterType,ParameterAxis)
				VALUES(@EquipmentMasterId,@ParaName,@ParaUnit,@ParameterResolution,@ParameterColor,@ParameterColorCode,@ParameterLowLimit,@ParameterHighLimit,'0',@ParameterType,@Axis)
				
				SET @i = @i + 1
				SET @ParaNo = @ParaNo - 1
				if @Axis=0
					Set @Axis=1
				else
					Set @Axis=0
				IF @ParaNo = 0 BREAK
			END		
			PRINT 'EquipmentMasterParameter_CreateList'
END
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--select * from EquipmentMasterParameter
-- exec [EquipmentMasterParameter_ListData] 99,'',2
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_ListData] 
	@EquipmentMasterId as BIGINT =0,
	@ParameterName as varchar(100)='',
	@ParameterAxis as tinyint=0
AS
Set nocount on;
BEGIN
	SELECT * FROM (
	SELECT ROW_NUMBER() OVER (ORDER BY EquipmentMasterParameterId ASC) AS rowNum,
	EMP.EquipmentMasterParameterId, EMP.EquipmentMasterId, EMP.ParameterName, EMP.ParameterResolution, EMP.ParameterUnit, EMP.ParameterColor, 
	EMP.ParameterColorCode, EMP.ParameterAxis, EMP.ParameterLowerLimit, EMP.ParameterUpperLimit, EM.ActiveChannel,EMP.ParameterType,ParameterLimitType,EMP.ParameterSetValue,
	CASE ISNUMERIC(EMP.ParameterRealValue) WHEN 1 THEN CAST(EMP.ParameterRealValue AS DECIMAL(18,1)) ELSE -99.9 END ParameterRealValue,EM.EquipmentStatus
	,EM.LowerRange,EM.HigherRange,EMP.SoakTime,EMP.ElaspsedSoakTime,EMP.RealLux,EMP.RealUV,EMP.RealSCHSpeed,EMP.RealSCHTime,EMP.SCHStatus
	FROM EquipmentMaster (NoLock) AS EM 
	INNER JOIN EquipmentMasterParameter (NoLock) AS EMP ON EM.EquipmentMasterId = EMP.EquipmentMasterId 
	Where (@EquipmentMasterId=0 or EMP.EquipmentMasterId=@EquipmentMasterId)
	and (@ParameterName='' or EMP.ParameterName=@ParameterName)
	and (@ParameterAxis=2 or EMP.ParameterAxis=@ParameterAxis)
	) AS x 
	WHERE rowNum <= (ActiveChannel*2)


End

Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_ListData_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

--select * from EquipmentMasterParameter
-- exec [EquipmentMasterParameter_ListData] 101,2
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_ListData_Service] 
	@EquipmentMasterId as BIGINT =0,
	@ParameterAxis as tinyint=0
AS
Set nocount on;
BEGIN
	SELECT * FROM (
	SELECT ROW_NUMBER() OVER (ORDER BY EquipmentMasterParameterId ASC) AS rowNum,
	EMP.EquipmentMasterParameterId, EMP.EquipmentMasterId, EMP.ParameterName, EMP.ParameterResolution, EMP.ParameterUnit, EMP.ParameterColor, 
	EMP.ParameterColorCode, EMP.ParameterAxis, EMP.ParameterLowerLimit, EMP.ParameterUpperLimit, EM.ActiveChannel,EMP.ParameterType,ParameterLimitType,EMP.ParameterSetValue,
	CASE ISNUMERIC(EMP.ParameterRealValue) WHEN 1 THEN CAST(EMP.ParameterRealValue AS DECIMAL(18,1)) ELSE -99.9 END ParameterRealValue,EM.EquipmentStatus
	,EM.LowerRange,EM.HigherRange,EMP.SoakTime,EMP.ElaspsedSoakTime,EMP.RealLux,EMP.RealUV,EMP.RealSCHSpeed,EMP.RealSCHTime,EMP.SCHStatus
	FROM EquipmentMaster (NoLock) AS EM 
	INNER JOIN EquipmentMasterParameter (NoLock) AS EMP ON EM.EquipmentMasterId = EMP.EquipmentMasterId 
	Where (@EquipmentMasterId=0 or EMP.EquipmentMasterId=@EquipmentMasterId)
	--and (@ParameterName='' or EMP.ParameterName=@ParameterName)
	and (@ParameterAxis=2 or EMP.ParameterAxis=@ParameterAxis)
	) AS x 
	WHERE rowNum <= (ActiveChannel*2)


End

Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Populate]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[EquipmentMasterParameter_Populate] 3,6
CREATE  Procedure [dbo].[EquipmentMasterParameter_Populate]
 @BranchId as BIGINT=0,
 @EquipmentMasterId AS BIGINT =0
As 
Begin
	SET NOCOUNT ON;
	SELECT EP.EquipmentMasterParameterId,(EP.ParameterName+'('+EP.ParameterUnit+')')AS [NAME] 
	FROM EquipmentMasterParameter (NOLOCK) AS EP 
	INNER JOIN EquipmentMaster (NOLOCK) AS EM 
	ON EM.EquipmentMasterId=EP.EquipmentMasterId 
	WHERE EM.BranchId=@BranchId 
	AND EP.EquipmentMasterId = @EquipmentMasterId			
	AND EP.ParameterType like'T%'
End


GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[EquipmentMasterParameter_Sync] 3
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_Sync]
	@BranchId as bigint = 0
AS
	Set nocount on
	Begin
--Insert Record
		insert into	ICDAS_3_0_Archive.dbo.EquipmentMasterParameter
			([EquipmentMasterParameterId],[EquipmentMasterId],[ParameterName],[ParameterType],[ParameterResolution],[ParameterUnit],[ParameterColor],[ParameterColorCode]
           ,[ParameterAxis],[ParameterLowerLimit],[ParameterUpperLimit],[ParameterLimitType],[ParameterAlert],[ParameterRealValue],[ParameterSetValue]
           ,[SoakTime],[ElaspsedSoakTime],[RealLux],[RealUV],[RealSCHSpeed],[RealSCHTime],[SCHStatus] ,[CreateBy] ,[ModifyBy] )
		select
			SourceDBTable.[EquipmentMasterParameterId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[ParameterName],SourceDBTable.[ParameterType] ,SourceDBTable.[ParameterResolution],SourceDBTable.[ParameterUnit],SourceDBTable.[ParameterColor]
           ,SourceDBTable.[ParameterColorCode],SourceDBTable.[ParameterAxis],SourceDBTable.[ParameterLowerLimit],SourceDBTable.[ParameterUpperLimit],SourceDBTable.[ParameterLimitType],SourceDBTable.[ParameterAlert]
           ,SourceDBTable.[ParameterRealValue],SourceDBTable.[ParameterSetValue]
           ,SourceDBTable.[SoakTime],SourceDBTable.[ElaspsedSoakTime],SourceDBTable.[RealLux],SourceDBTable.[RealUV]
		   ,SourceDBTable.[RealSCHSpeed],SourceDBTable.[RealSCHTime],SourceDBTable.[SCHStatus] ,SourceDBTable.[CreateBy] ,SourceDBTable.[ModifyBy]
		from EquipmentMasterParameter(NOLOCK) SourceDBTable inner join EquipmentMaster EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.EquipmentMasterParameter DestinationDBTable
						 where DestinationDBTable.EquipmentMasterParameterId = SourceDBTable.EquipmentMasterParameterId)
			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.EquipmentMasterParameter 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[ParameterName]=SourceDBTable.[ParameterName],[ParameterType]=SourceDBTable.[ParameterType],[ParameterResolution]=SourceDBTable.[ParameterResolution]
		   ,[ParameterUnit]=SourceDBTable.[ParameterUnit],[ParameterColor]=SourceDBTable.[ParameterColor],[ParameterColorCode]=SourceDBTable.[ParameterColorCode],[ParameterAxis]=SourceDBTable.[ParameterAxis]
		   ,[ParameterLowerLimit]=SourceDBTable.[ParameterLowerLimit],[ParameterUpperLimit]=SourceDBTable.[ParameterUpperLimit],[ParameterLimitType]=SourceDBTable.[ParameterLimitType]
		   ,[ParameterAlert]=SourceDBTable.[ParameterAlert],[ParameterRealValue]=SourceDBTable.[ParameterRealValue],[ParameterSetValue]=SourceDBTable.[ParameterSetValue]
		   ,[SoakTime]=SourceDBTable.[SoakTime],[ElaspsedSoakTime]=SourceDBTable.[ElaspsedSoakTime],[RealLux]=SourceDBTable.[RealLux],[RealUV]=SourceDBTable.[RealUV]
		    ,[RealSCHSpeed]=SourceDBTable.[RealSCHSpeed],[SCHStatus]=SourceDBTable.[SCHStatus] ,[CreateBy]=SourceDBTable.[CreateBy] ,[ModifyBy]=SourceDBTable.[ModifyBy]
	from	ICDAS_3_0_Archive.dbo.EquipmentMasterParameter(NOLOCK) DestinationDBTable,
			(
				select	max(TableName) as TableName,[EquipmentMasterParameterId],[EquipmentMasterId],[ParameterName],[ParameterType],[ParameterResolution],[ParameterUnit],[ParameterColor],[ParameterColorCode]
						,[ParameterAxis],[ParameterLowerLimit],[ParameterUpperLimit],[ParameterLimitType],[ParameterAlert],[ParameterRealValue],[ParameterSetValue],[SoakTime],[ElaspsedSoakTime],[RealLux],[RealUV],[BranchId]
						,[RealSCHSpeed],[RealSCHTime],[SCHStatus] ,[CreateBy] ,[ModifyBy] 

				from
					(
						select	'SourceTableName' as TableName,[EquipmentMasterParameterId],SourceTableName.[EquipmentMasterId],[ParameterName],[ParameterType],[ParameterResolution],[ParameterUnit],[ParameterColor],[ParameterColorCode]
								,[ParameterAxis],[ParameterLowerLimit],[ParameterUpperLimit],[ParameterLimitType],[ParameterAlert],[ParameterRealValue],[ParameterSetValue],[SoakTime],[ElaspsedSoakTime],[RealLux],[RealUV],EM.[BranchId]
							 ,[RealSCHSpeed],[RealSCHTime],[SCHStatus] ,[CreateBy] ,[ModifyBy] 
						from EquipmentMasterParameter(NOLOCK) SourceTableName inner join EquipmentMaster EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
						
						union all
						
						select	'DestinationiTableName' as TableName, [EquipmentMasterParameterId],DestinationTableName.[EquipmentMasterId],[ParameterName],[ParameterType],[ParameterResolution],[ParameterUnit],[ParameterColor],[ParameterColorCode]
								,[ParameterAxis],[ParameterLowerLimit],[ParameterUpperLimit],[ParameterLimitType],[ParameterAlert],[ParameterRealValue],[ParameterSetValue],[SoakTime],[ElaspsedSoakTime],[RealLux],[RealUV],EM.[BranchId]
								 ,[RealSCHSpeed],[RealSCHTime],[SCHStatus] ,[CreateBy] ,[ModifyBy] 
						from ICDAS_3_0_Archive.dbo.EquipmentMasterParameter(NOLOCK) DestinationTableName inner join EquipmentMaster EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [EquipmentMasterParameterId],[EquipmentMasterId],[ParameterName],[ParameterType],[ParameterResolution],[ParameterUnit],[ParameterColor],[ParameterColorCode]
							,[ParameterAxis],[ParameterLowerLimit],[ParameterUpperLimit],[ParameterLimitType],[ParameterAlert],[ParameterRealValue],[ParameterSetValue],[SoakTime],[ElaspsedSoakTime],[RealLux],[RealUV],[BranchId]
							 ,[RealSCHSpeed],[RealSCHTime],[SCHStatus] ,[CreateBy] ,[ModifyBy] 
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.EquipmentMasterParameterId = SourceDBTable.EquipmentMasterParameterId and SourceDBTable.BranchId=@BranchId
			
	End
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_Unit_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [EquipmentMasterParameter_ListData] 1002          
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_Unit_ListData]           
 @EquipmentMasterId as BIGINT =0,          
 @ParameterName as varchar(100)='',          
 @ParameterAxis as tinyint=2,       
 @ParameterType as varchar(1) =''   
AS          
Set nocount on;          
BEGIN          
          
SELECT * FROM (          
SELECT         
EMP.EquipmentMasterParameterId,EMP.ParameterName, ROW_NUMBER() OVER (ORDER BY EquipmentMasterParameterId ASC) AS rowNum,EMP.ParameterUnit, EM.ActiveChannel,    
EMP.ParameterColor, EMP.ParameterAxis,EMP.ParameterType   
FROM EquipmentMaster(NOLOCK) AS EM INNER JOIN          
EquipmentMasterParameter(NOLOCK) AS EMP ON EM.EquipmentMasterId = EMP.EquipmentMasterId           
Where (@EquipmentMasterId=0 or EMP.EquipmentMasterId=@EquipmentMasterId)          
and (@ParameterName='' or EMP.ParameterName=@ParameterName)          
and (@ParameterAxis=2 or EMP.ParameterAxis=@ParameterAxis) 
and (@ParameterType = '' or EMP.ParameterType = @ParameterType)
) AS x           
WHERE rowNum <= (case @ParameterType when '' then ActiveChannel*2 else ActiveChannel end)          
          
End          
          
Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterParameter_UpdateColor]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--select * from EquipmentMasterParameter
-- exec [EquipmentMasterParameter_UpdateColor] 1001,6,'','Yellow','#f2ec3b'
CREATE PROCEDURE [dbo].[EquipmentMasterParameter_UpdateColor] 
	@EquipmentMasterParameterId as BIGINT =0,
	@EquipmentName as nvarchar(100)='',
	@EquipmentMasterId as BIGINT =0,		
	@ParameterName as varchar(100)='',
	@ParameterColor as varchar(100)='',
	@ParameterColorCode as varchar(100)='',
	@comments as nvarchar(200)='',
	@username as nvarchar(100)=''
AS
Set nocount on;
BEGIN
	begin try
		Declare @ParameterColorOld as varchar(100),@ParameterColorCodeOld AS VARCHAR(100),@ColorNew as varchar(200),@ColorOld as varchar(200)
		
		select @ParameterColorOld = ParameterColor , @ParameterColorCodeOld = ParameterColorCode from EquipmentMasterParameter(NOLOCK) where EquipmentMasterParameterId=@EquipmentMasterParameterId
		
		update EMP set ParameterColor=@ParameterColor ,parametercolorcode=@ParameterColorCode 
		from EquipmentMasterParameter (NoLock) EMP inner join EquipmentMaster (NoLock) EM on EM.EquipmentMasterId = EMP.EquipmentMasterId 
		where emp.EquipmentMasterParameterId=@EquipmentMasterParameterId and (@ParameterName='' or EMP.ParameterName = @ParameterName)
		
		IF @@ROWCOUNT>0
		BEGIN 
			
			set @ColorNew = @ParameterColor
			set @ColorOld = @ParameterColorOld
			
			EXEC EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,@ParameterName,@ColorOld,@ColorNew,@comments,@username,''
			
		END
	end try
	begin catch
		declare @ReturnMessage as nvarchar(1000)=''
		set @ReturnMessage=dbo.RemoveSpecialChars(Error_message())
	end catch
End

Set nocount off;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterRunningHours_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec [EquipmentMasterRunningHours_Service] '<RunningHours> <Equipment> <EquipmentMasterId>14</EquipmentMasterId> <ComponentRunningHoursId>1</ComponentRunningHoursId> <OldValue>OFF</OldValue> <LastValue>OFF</LastValue> <RunHours>0</RunHours> </Equipment> </RunningHours>'
CREATE PROCEDURE [dbo].[EquipmentMasterRunningHours_Service]
@xml XML
AS
BEGIN
	  SET NOCOUNT ON;
	  
	   Declare @strQuery as Varchar(max),@strQuery1 as Varchar(max)

	  
	  INSERT INTO EquipmentComponentRunningHoursTemp(EquipmentMasterId,ComponentRunningHoursId,RunHours,Value)
	  SELECT
	  Equipment.value('(EquipmentMasterId/text())[1]','BigInt') AS EquipmentMasterId,
	  Equipment.value('(ComponentRunningHoursId/text())[1]','BigInt') AS ComponentRunningHoursId,
	  Equipment.value('(RunHours/text())[1]','BigInt') AS RunHours,
	  Equipment.value('(LastValue/text())[1]','nvarchar(100)') AS Value

	  FROM
	  @xml.nodes('/RunningHours/Equipment')AS TEMPTABLE(Equipment)


	  Set @strQuery = 'Update EquipmentComponentRunningHours Set EquipmentComponentRunningHours.RunHours = EquipmentComponentRunningHoursTemp.RunHours,
						EquipmentComponentRunningHours.Value=EquipmentComponentRunningHoursTemp.Value
						From EquipmentComponentRunningHoursTemp 
						Where EquipmentComponentRunningHours.EquipmentMasterId = EquipmentComponentRunningHoursTemp.EquipmentMasterId
						and EquipmentComponentRunningHours.ComponentRunningHoursId = EquipmentComponentRunningHoursTemp.ComponentRunningHoursId'
			
	  Exec (@strQuery)
						
	  Truncate table EquipmentComponentRunningHoursTemp
						
	   
	   --print (@strQuery+@strQuery1)

  
END



GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterVersionUpdate_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--exec [EquipmentMasterAlarmLogManage_Service] '101','<AlarmLog> <AlarmLog> <EquipmentMasterId>101</EquipmentMasterId> <EquipmentName>Equipment 3</EquipmentName> <AlarmLogDateTime>2018/06/19 09:55</AlarmLogDateTime> <AlarmEvent>TEMP 1 LOW ALARM</AlarmEvent> </AlarmLog> </AlarmLog>'

CREATE PROCEDURE [dbo].[EquipmentMasterVersionUpdate_Service]
@EquipmentMasterId nvarchar(10),
@xml XML
AS
BEGIN
      SET NOCOUNT ON;
	  

  
END




GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Execute EquipmentMasterWrite_ListData '3',99,'F','','B','' 
--Execute EquipmentMasterWrite_ListData '182',139,'F','','B','DCT5T5'
CREATE PROCEDURE [dbo].[EquipmentMasterWrite_ListData]	
	@EquipmentMasterId as nvarchar(4)='',
	@BranchId as bigint=0,
	@Status as nvarchar(15)='P',
	@SettingParameterType as nvarchar(15)='',
	@DoorAccessType as nvarchar(5)='',
	@EquipmentType as nvarchar(20)=''
	
AS
SET NOCOUNT ON;
BEGIN
	--if @EquipmentMasterId=0

	if @BranchId <> 0 	
		Begin
		PRINT 1
			SELECT Top 20 EquipmentMasterWriteId,EMW.EquipmentMasterId,EM.EquipmentName,EquipmentMasterParameterNo,
			(convert(varchar, LogDatetime, 103) +' '+ SUBSTRING(convert(varchar, LogDatetime, 108),0,6)) AS LogDatetime,
			EMW.EquipmentType,SettingParameterType,SettingParameterLabel,SettingParameterValue, 
			Case [Status] When 'P' THen 'PENDING' When 'D' THen 'DONE' When 'NS' THen 'NOT SUPPORTED' When 'F' THen 'FAILED' When 'C' THen 'CANCELED' End as [Status],
			StatusDescription,BranchId as CompanyId,CompanyCode,ModbusAddress,EquipmentId
			FROM  EquipmentMasterWrite (NoLock) EMW 
			Inner Join EquipmentMaster (NoLock) EM On  EMW.EquipmentMasterId=EM.EquipmentMasterId
			inner join EquipmentType (nolock) ET on EMW.EquipmentType=ET.EquipmentType			
			WHERE (@EquipmentMasterId = '' or EMW.EquipmentMasterId in (Select * from dbo.CSVToTable(@EquipmentMasterId)))			
			and [Status]<>'SP' and [Status]<>'SD' and [Status]<>'SC'
			and EMW.SettingParameterType<>'SYD'   and ET.EquipmentType like '%'+@EquipmentType+'%'
			AND EM.DoorAccessType=@DoorAccessType
			Order By EquipmentMasterWriteId Desc 
			
		End
	else
		Begin
			SELECT *,(Select EquipmentTypeGroup from EquipmentType DT Where DT.EquipmentType=EquipmentMasterWrite.EquipmentType) as EquipmentTypeGroup  
			FROM  EquipmentMasterWrite (NoLock)
			WHERE (@EquipmentMasterId = '' or EquipmentMasterId in (Select * from dbo.CSVToTable(@EquipmentMasterId)))			
			and ([Status] in (Select [SID] from dbo.CSVToTable(@Status)))
			and SettingParameterType<>'SYD' 
			Order By EquipmentMasterWriteId Asc
		End
	
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--Select * From EquipmentMasterWrite 
--exec [EquipmentMasterWrite_Manage] 0,0,1,'DI','','','P'
CREATE PROCEDURE [dbo].[EquipmentMasterWrite_Manage]
@BranchId as bigint,
@EquipmentMasterId as bigint,
@EquipmentMasterParameterNo as Tinyint,
@SettingParameterType as nvarchar(10)='',
@SettingParameterLabel as nvarchar(500)='',
@SettingParameterValue as nvarchar(100)='',
@Status as nvarchar(10)='P',
@Comments AS nVARCHAR(255)='',
@RetunId as bigint=0 output
AS
Begin
	Declare @DeviceAuditTrailId as Bigint
	if @EquipmentMasterParameterNo=0
		Begin
			Set @EquipmentMasterParameterNo=NULL
		End
	if @EquipmentMasterId=0
		Begin
			Set @EquipmentMasterId=NULL
		End
	
	if @SettingParameterType='DI'
		Begin
			Set @SettingParameterLabel='Equipment Information'
		End
	
	if @Status='SP'
		Begin
			Select EquipmentMasterWriteId From EquipmentMasterWrite (NOLOCK)
			Where EquipmentMasterId=@EquipmentMasterId and EquipmentMasterParameterNo=@EquipmentMasterParameterNo and SettingParameterType=@SettingParameterType and [Status]='SP'
			if @@rowcount >0
				return;
		End
	
	if @SettingParameterType='IO' or  @SettingParameterType='RUNHR' or @SettingParameterType='IOCS' or @SettingParameterType='IOCSP'
		Begin
			Select EquipmentMasterWriteId From EquipmentMasterWrite (NOLOCK)
			Where EquipmentMasterId=@EquipmentMasterId and EquipmentMasterParameterNo=@EquipmentMasterParameterNo and SettingParameterType=@SettingParameterType and [Status]='P'
			if @@rowcount >0
				return;
		End
		
	Declare @EquipmentType as nvarchar(10)
	SELECT @EquipmentType=EquipmentType From EquipmentMaster(NOLOCK) where EquipmentMasterId=@EquipmentMasterId
		
	Declare @ModbusAddress as bigint
	
	select @ModbusAddress=ModbusAddress from ModbusLookup(NOLOCK) where ModbusEvent=@SettingParameterType and EquipmentMasterParameterNo=@EquipmentMasterParameterNo
	
	insert into EquipmentMasterWrite (CompanyId,EquipmentMasterId,EquipmentMasterParameterNo,EquipmentType,SettingParameterType,SettingParameterLabel,SettingParameterValue,LogDatetime,[Status],ModbusAddress) 
	values(@BranchId,@EquipmentMasterId,@EquipmentMasterParameterNo,@EquipmentType,@SettingParameterType,@SettingParameterLabel,@SettingParameterValue,GetDate(),@Status,@ModbusAddress)
	
	if @@rowcount >0
		Begin
		set @RetunId = @@IDENTITY
			if @EquipmentMasterParameterNo = NULL
				Begin
					  Set @EquipmentMasterParameterNo=1
				End
		End
End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentMasterWrite_Status_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--EquipmentMasterWrite_Status_Manage '13','C','57','Equipment Date Time Synchronize Request Sent','1'
CREATE PROCEDURE [dbo].[EquipmentMasterWrite_Status_Manage]
@EquipmentMasterWriteId as bigint,
@EquipmentName as nvarchar(100),
@Status as nvarchar(10)='P',
@EquipmentMasterId as bigint,
@ParameterLabel as nvarchar(200)='',
@ParameterOldValue as nvarchar(100)='',
@Username as nvarchar(100)=''
AS
Begin
	
	Update EquipmentMasterWrite Set [Status]=@Status 
	Where EquipmentMasterWriteId=@EquipmentMasterWriteId	
	if @@rowcount > 0 
		Begin
			if @ParameterOldValue = 'P'
				begin
					set @ParameterOldValue = 'Pending'
				end
			else
				begin
					set @ParameterOldValue = 'Cancelled'
				end

				if @Status = 'P'
				begin
					set @Status = 'Pending'
				end
			else
				begin
					set @Status = 'Cancelled'
				end

			select @EquipmentMasterId=EquipmentMasterId from EquipmentMasterWrite(NOLOCK) where EquipmentMasterWriteId=@EquipmentMasterWriteId
			EXEC EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,@ParameterLabel,@ParameterOldValue,@Status,'','','',@Username,''--'EWSC'
		End
	
End

GO
/****** Object:  StoredProcedure [dbo].[EquipmentStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[EquipmentStatus_Update]
 @EquipmentMasterId as bigint,
 @EquipmentName as nvarchar(100),
 @EquipmentStatus as NVARCHAR(100)='',
 @LoginComments as nvarchar(255)='',
 @ParameterOldValue as NVARCHAR(100)='', 
 @Username as nvarchar(100)='',
 @ReturnMessage as nvarchar(1000)='' output,
 @ReturnId as bigint=0 output
  
As  
Begin
	SET NOCOUNT ON;
	
	update Equipmentmaster set EquipmentStatus=@EquipmentStatus
	where EquipmentMasterId = @EquipmentMasterId
	
	if @@ROWCOUNT>0
		BEGIN
			
			SET @ParameterOldValue = (CASE WHEN @ParameterOldValue='0' THEN 'ACTIVE' ELSE 'NOT ACTIVE' END)
			SET @EquipmentStatus = (CASE WHEN @EquipmentStatus='0' THEN 'ACTIVE' ELSE 'NOT ACTIVE' END)
			
			Execute EquipmentMasterAuditTrail_Manage @EquipmentMasterId,@EquipmentName,'ESTATUS',@ParameterOldValue,@EquipmentStatus,@LoginComments,@Username,@ReturnMessage
			
			set @ReturnMessage = 'EQUIPMENT STATUS UPDATED SUCCESSFULLY'
			set @ReturnId = @EquipmentMasterId
			
		END
	ELSE
		BEGIN
			set @ReturnMessage = 'EQUIPMENT STATUS UPDATION FAILED'
			set @ReturnId = 0
		END

end	
GO
/****** Object:  StoredProcedure [dbo].[EquipmentSupervisorEmail]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



--Exec [AlarmAuditTrail_rpt] '2009-10-17','00','00','2014-10-17','23','57','1,2'
--Exec [EquipmentMasterAlarmAuditTrail_ListData] 64,3
CREATE PROCEDURE [dbo].[EquipmentSupervisorEmail]

AS
SET NOCOUNT ON;
BEGIN
		Select *,AC.SupervisorEmailAdd,EmailTime from EquipmentMasterAlarmAuditTrail EAT
		Inner Join EquipmentMaster EM ON EM.EquipmentMasterId=EAT.EquipmentMasterId
		Inner Join App_Company AC ON AC.CompanyId=EM.BranchId
		Where AckUserId Is NUll
		Order By AC.CompanyId,EAT.AlarmLogDateTime
	
END
SET NOCOUNT OFF




GO
/****** Object:  StoredProcedure [dbo].[EquipmentSupervisorEmail_LogDateTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--Exec [EquipmentSupervisorEmail_LogDateTime] 5
CREATE PROCEDURE [dbo].[EquipmentSupervisorEmail_LogDateTime]
@CompanyId as bigint=0
AS
SET NOCOUNT ON;
BEGIN
		Select * From EquipmentMaster EM 
		Inner Join App_Company AC ON AC.CompanyId=EM.BranchId
		Outer Apply
		(

			Select Top 1 ToDateTime From EquipmentMasterLogReviewApprove ERL
			Where ERL.EquipmentMasterId = EM.EquipmentMasterId
			Order By ToDateTime Desc
		)MT
		Where Em.BranchId =@CompanyId
	
END
SET NOCOUNT OFF




GO
/****** Object:  StoredProcedure [dbo].[EquipmentType_List]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[EquipmentType_List] 
	@EquipmentType as nvarchar(20)='',
	@EquipmentPLCCode as nvarchar(20)=''
AS
SET NOCOUNT ON;
BEGIN
	SELECT * FROM EquipmentType (NoLock) 
	where (@EquipmentType='' or EquipmentType=@EquipmentType)
	and (@EquipmentPLCCode='' or EquipmentPLCCode=@EquipmentPLCCode)
	order By EquipmentTypeName
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[Get_Equipment_RunningHours]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Get_Equipment_RunningHours 43
CREATE Procedure [dbo].[Get_Equipment_RunningHours]
 @RecordKeyId as bigint=0
As 
Begin
	SET NOCOUNT ON;
	SELECT EquipmentComponentRunningHoursId,ECR.EquipmentMasterId,EM.EquipmentId,EM.EquipmentName,ECR.ComponentRunningHoursId,CR.Name,SetRunHours,RunHours,Value FROM EquipmentComponentRunningHours(NOLOCK) ECR
	INNER JOIN ComponentRunningHours CR ON ECR.ComponentRunningHoursId=CR.ComponentRunningHoursId
	INNER JOIN EquipmentMaster EM ON EM.EquipmentMasterId=ECR.EquipmentMasterId   WHERE ECR.EquipmentMasterId = @RecordKeyId 

	--SELECT * FROM EquipmentComponentRunningHours(NOLOCK) WHERE EquipmentMasterId = @RecordKeyId
	--SELECT EquipmentMasterId,EquipmentName,EquipmentId,CompanyCode,BranchId FROM EquipmentMaster(NOLOCK) WHERE EquipmentMasterId=@RecordKeyId

end
GO
/****** Object:  StoredProcedure [dbo].[Get_IOStatus_RealTime]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Get_IOStatus_RealTime] 102
CREATE  Procedure [dbo].[Get_IOStatus_RealTime]
@RecordId BIGINT=0
As 
Begin
			SELECT * from IOStatus(NOLOCK);
			SELECT * FROM EquipmentMasterParameter(NOLOCK) WHERE EquipmentMasterId=@RecordId OR @RecordId=0;
			SELECT * FROM EquipmentMaster(NOLOCK) WHERE EquipmentMasterId=@RecordId OR @RecordId=0;

End


GO
/****** Object:  StoredProcedure [dbo].[Get_RunningHours]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[Get_IOStatus_RealTime] 102
CREATE  Procedure [dbo].[Get_RunningHours]
As 
Begin
			SELECT * FROM ComponentRunningHours
			

End


GO
/****** Object:  StoredProcedure [dbo].[IOStatus_Service]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[IOStatus_Service] CI
CREATE PROCEDURE [dbo].[IOStatus_Service]
@EquipmentTypeGroup nvarchar(5)= ''
AS
	Set nocount on
	Begin
		Select * From IOStatus (nolock)
		where (',' + EquipmentTypeGroup + ',') like '%,' + @EquipmentTypeGroup + ',%'
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[ServiceStatus_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ServiceStatus_ListData]
	@CompanyId As Bigint=0,
	@ServiceStatusId as Bigint=0
AS
Set nocount on;
Begin
	
		Declare @EmailSystem as integer
	
		SELECT ServiceStatusId,ss.CompanyId,ServiceStep as [Service Step],ServiceStepValue as [Service Step Value]
		FROM ServiceStatus (nolock) as SS inner join App_Company (nolock) as AC 
		on ss.CompanyId=ac.CompanyId
		WHERE ServiceStatusId > 0
		AND (@CompanyId=0 or ss.CompanyId=@CompanyId)
		AND (@ServiceStatusId = 0 or ServiceStatusId = @ServiceStatusId)
		
	
End
Set nocount off;



GO
/****** Object:  StoredProcedure [dbo].[ServiceStatus_Update]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select *from Servicestatus
--EXECUTE ServiceStatus_Update '3','Administrator'
CREATE PROCEDURE [dbo].[ServiceStatus_Update]
@CompanyId As Bigint=0,
@Username AS NVARCHAR(100)=''
AS
SET NOCOUNT ON;
BEGIN
		Update ServiceStatus Set  ServiceStepValue=''
		WHERE (@CompanyId=0 or CompanyId=@CompanyId)		
		IF @@rowcount > 0 
			BEGIN 				
				Execute App_UserMaster_AuditTrail @CompanyId,@Username,'','SS',''				
			END
END
SET NOCOUNT OFF;

GO
/****** Object:  StoredProcedure [dbo].[SMSLog_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SMSLog_ListData]
	
AS
	Set nocount on
	Begin

	Select * from SMSLog where SMSStatus=0
	
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Manage]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SMSLog_Manage]
	
AS
	Set nocount on
	Begin
	

	INSERT INTO SMSLog ([EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus])
	(	
		SELECT DM.EquipmentMasterId,GetDate() as SMSDateTime
		,MN.MobileUserName
		,MN.MobileNo
		,convert(nvarchar(160),(upper(DM.EquipmentName) +  ' , ' +  CONVERT(VARCHAR(20), AlarmLogDateTime, 100) + ' , ' + AlarmEvent + AlarmInfo)) as SMSMessage
		--,('<tr><td width=''20%''>Department Name</td><td width=''80%''>: ' + upper(BM.BranchName) +  '</td></tr><tr><td width=''20%''>Equipment Name</td><td width=''80%''>: ' + upper(DM.EquipmentName) +  '</td></tr><tr><td width=''20%''>Alarm Log DateTime</td><td width=''80%''>: ' + upper(CONVERT(VARCHAR(20), AlarmLogDateTime, 100)) + '</td></tr><tr><td width=''20%''>Alarm Event</td><td width=''80%''>: ' + upper(AlarmEvent) +'</td></tr>') as EmailMessage
		,0 as SMSStatus
				
		FROM EquipmentMaster AS DM INNER JOIN
		EquipmentMasterAlarmAuditTrail AS DMAL ON DM.EquipmentMasterId = DMAL.EquipmentMasterId INNER JOIN
		App_Company AS BM ON DM.BranchId = BM.CompanyId
		Outer Apply
		(
			Select MobileNo,MobileUserName from dbo.GetMobileUserDetails(BM.MobileNo,BM.MobileUserName)
			Where isnull(MobileNo,'') <> ''
		) MN
	
		Where DMAL.SMSStatus=0 and isnull(MN.MobileNo,'') <> '' --and isnull(MU.MobileUserName,'') <> ''
		and Isnull(AckUserId,'') =''
		and Datediff(n,AlarmLogDateTime,GetDate()) > BM.SMSAlertDelay
	)
	if @@rowcount>0
	Begin
		Update EquipmentMasterAlarmAuditTrail Set SMSStatus=1 Where SMSStatus=0
	End

	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[SMSLog_ManageTestSMS]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SMSLog_ManageTestSMS]
	@EquipmentMasterId as bigint=0,
	@SMSDateTime  as nvarchar(25)='',
	@MobileUserName as nvarchar(100)='',
	@MobileNo as nvarchar(100)='',
	@SMSMessage as nvarchar(500)='',
	@SMSStatus as tinyint,
	@LoginName as nvarchar(100)=''
		
AS
	Set nocount on
	Begin

	begin try
	if @EquipmentMasterId=0
		set @EquipmentMasterId=null

	INSERT INTO SMSLog ([EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],CreatedBy,ModifedBy)
	values(@EquipmentMasterId,@SMSDateTime,@MobileUserName,@MobileNo,@SMSMessage,@SMSStatus,@LoginName,@LoginName)	
		
	end try	

	begin catch
	end catch
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Rpt]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

----[SMSLog_Rpt] 163,'2018/01/01 00:00','2018/08/26 23:59','','',-1,1,0
CREATE PROCEDURE [dbo].[SMSLog_Rpt]  
 @BranchId AS Bigint=0,  
 @ReportFromDate AS DATETIME='',  
 @ReportToDate AS DATETIME='',   
 @EquipmentName AS varchar(4000)='',  
 @FilterParameter AS varchar(100)='',  
 @SMSStatus AS int=-1,
 @IsSystemSMS As tinyint,  
 @OrderBy as tinyint=0  
AS  
SET NOCOUNT ON  
Begin  
  IF @IsSystemSMS = 0
  BEGIN  
	  SELECT Row_Number() Over(Order by (Case @OrderBy When 0 Then SMSDateTime Else SMSAT.SMSLogId End),EM.EquipmentName) As [Sr No]
			 ,Convert(varchar, SMSAT.SMSDateTime, 105) As [Date], 
			 substring(convert(varchar(8), SMSAT.SMSDateTime, 108), 0, 6) As [Time],
			 EM.EquipmentName, SMSAT.MobileUserName As [Mobile User Name], 
			 SMSAT.MobileNo As [Mobile No],
			 SMSAT.SMSMessage As [SMS Message], 
			 (Case SMSAT.SMSStatus When 0 then 'PENDING' When 1 then 'SENT' When 2 then 'FAILED' End) As [Status]
		      
	  FROM  SMSLog AS SMSAT left JOIN  
	  EquipmentMaster AS EM ON SMSAT.EquipmentMasterId = EM.EquipmentMasterId  
	  WHERE (SMSAT.SMSDateTime BETWEEN @ReportFromDate and @ReportToDate)  
	  And (@BranchId=0 or EM.BranchId=@BranchId)  
	  And (@SMSStatus=-1 or SMSStatus=@SMSStatus)  
	  And ((@EquipmentName ='' and SMSAT.EquipmentMasterId is not null ) or ( @EquipmentName='' and SMSAT.EquipmentMasterId is null ) or (EM.EquipmentMasterId in(select * from CSVTOTable(@EquipmentName)) and SMSAT.EquipmentMasterId is not null ))  
	  And (@FilterParameter='' or SMSMessage like '%' + @FilterParameter + '%')  
	  order by (Case @OrderBy When 0 Then SMSDateTime Else SMSAT.SMSLogId End),EM.EquipmentName  
  END
  ELSE
  BEGIN
	  SELECT Row_Number() Over(Order by (Case @OrderBy When 0 Then SMSDateTime Else SMSAT.SMSLogId End),EM.EquipmentName) As [Sr No]
	         ,Convert(varchar, SMSAT.SMSDateTime, 105) As [Date], 
			 substring(convert(varchar(8), SMSAT.SMSDateTime, 108), 0, 6) As [Time],
			 EM.EquipmentName, SMSAT.MobileUserName As [Mobile User Name], 
			 SMSAT.MobileNo As [Mobile No],
			 SMSAT.SMSMessage As [SMS Message], 
			 (Case SMSAT.SMSStatus When 0 then 'PENDING' When 1 then 'SENT' When 2 then 'FAILED' End) As [Status]
		      
	  FROM  SMSLog AS SMSAT left JOIN  
	  EquipmentMaster AS EM ON SMSAT.EquipmentMasterId = EM.EquipmentMasterId  
	  WHERE (SMSAT.SMSDateTime BETWEEN @ReportFromDate and @ReportToDate)  
	  And (@BranchId=0 or EM.BranchId=@BranchId or @IsSystemSMS = 1)  
	  And (@SMSStatus=-1 or SMSStatus=@SMSStatus)  	    
	  And ((SMSAT.EquipmentMasterId is null ) or (SMSAT.EquipmentMasterId is null ) 
	  And (@FilterParameter='' or SMSMessage like '%' + @FilterParameter + '%'))  
	  order by (Case @OrderBy When 0 Then SMSDateTime Else SMSAT.SMSLogId End),EM.EquipmentName  
  END
End  
SET NOCOUNT OFF

GO
/****** Object:  StoredProcedure [dbo].[SMSLog_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Exec [SMSLog_Sync] 1001,'2013-JAN-01'
CREATE PROCEDURE [dbo].[SMSLog_Sync]
	@BranchId as bigint = 0,
	@LogDateTime as Datetime
AS
	Set nocount on
	Begin
--Insert Record

--SET  identity_insert ICDAS_3_0_Archive.dbo.SMSLog ON

		insert into	ICDAS_3_0_Archive.dbo.SMSLog
			([SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate])
		select
			SourceDBTable.[SMSLogId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[SMSDateTime] ,SourceDBTable.[MobileUserName]
			,SourceDBTable.[MobileNo],SourceDBTable.[SMSMessage],SourceDBTable.[SMSStatus],SourceDBTable.[SMSErrorDesc]
			,SourceDBTable.[CreateDate] ,SourceDBTable.[CreatedBy],SourceDBTable.[ModifedBy] ,SourceDBTable.[ModifedDate]
		from SMSLog(NOLOCK) SourceDBTable inner join EquipmentMaster(NOLOCK) EM ON SourceDBTable.EquipmentMasterId=EM.EquipmentMasterId
		where EM.BranchId=@BranchId AND SMSDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.SMSLog DestinationDBTable
						 where DestinationDBTable.SMSLogId = SourceDBTable.SMSLogId)
						 
		insert into	ICDAS_3_0_Archive.dbo.SMSLog
			([SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc]
			,[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate])
		select
			SourceDBTable.[SMSLogId],SourceDBTable.[EquipmentMasterId],SourceDBTable.[SMSDateTime] ,SourceDBTable.[MobileUserName]
			,SourceDBTable.[MobileNo],SourceDBTable.[SMSMessage],SourceDBTable.[SMSStatus],SourceDBTable.[SMSErrorDesc]
			,SourceDBTable.[CreateDate] ,SourceDBTable.[CreatedBy],SourceDBTable.[ModifedBy] ,SourceDBTable.[ModifedDate]
		from SMSLog(NOLOCK) SourceDBTable 
		where EquipmentMasterId is null AND SMSDateTime<=@LogDateTime AND
			 not exists	(select	1 from	ICDAS_3_0_Archive.dbo.SMSLog DestinationDBTable
						 where DestinationDBTable.SMSLogId = SourceDBTable.SMSLogId)
						 
--SET  identity_insert ICDAS_3_0_Archive.dbo.SMSLog OFF
			
--Update Record			

	update  ICDAS_3_0_Archive.dbo.SMSLog 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[SMSDateTime]=SourceDBTable.[SMSDateTime],[MobileUserName]=SourceDBTable.[MobileUserName]
		   ,[MobileNo]=SourceDBTable.[MobileNo],[SMSMessage]=SourceDBTable.[SMSMessage],[SMSStatus]=SourceDBTable.[SMSStatus],[SMSErrorDesc]=SourceDBTable.[SMSErrorDesc]
		   ,[CreateDate]=SourceDBTable.[CreateDate] ,[CreatedBy]=SourceDBTable.[CreatedBy],[ModifedBy]=SourceDBTable.[ModifedBy] ,[ModifedDate]=SourceDBTable.[ModifedDate]
	from	ICDAS_3_0_Archive.dbo.SMSLog DestinationDBTable,
			(
				select	max(TableName) as TableName,[SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[BranchId]
				,[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
				from
					(
						select	'SourceTableName' as TableName,[SMSLogId],SourceTableName.[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[BranchId]
						,SourceTableName.[CreateDate] ,SourceTableName.[CreatedBy],SourceTableName.[ModifedBy] ,SourceTableName.[ModifedDate]
						from SMSLog(NOLOCK) SourceTableName inner join EquipmentMaster(NOLOCK) EM ON SourceTableName.EquipmentMasterId=EM.EquipmentMasterId
											
						
						union all
						
						select	'DestinationiTableName' as TableName,[SMSLogId],DestinationTableName.[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[BranchId]
						,DestinationTableName.[CreateDate] ,DestinationTableName.[CreatedBy],DestinationTableName.[ModifedBy] ,DestinationTableName.[ModifedDate]
						from ICDAS_3_0_Archive.dbo.SMSLog(NOLOCK) DestinationTableName inner join EquipmentMaster(NOLOCK) EM ON DestinationTableName.EquipmentMasterId=EM.EquipmentMasterId
					) AliasName
					
					group by [SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[BranchId],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.SMSLogId = SourceDBTable.SMSLogId and SourceDBTable.BranchId=@BranchId
	
	
	--Where EquipmentMasterId is null
	update  ICDAS_3_0_Archive.dbo.SMSLog 
	set    [EquipmentMasterId]=SourceDBTable.[EquipmentMasterId],[SMSDateTime]=SourceDBTable.[SMSDateTime],[MobileUserName]=SourceDBTable.[MobileUserName]
		   ,[MobileNo]=SourceDBTable.[MobileNo],[SMSMessage]=SourceDBTable.[SMSMessage],[SMSStatus]=SourceDBTable.[SMSStatus],[SMSErrorDesc]=SourceDBTable.[SMSErrorDesc]
			,[CreateDate]=SourceDBTable.[CreateDate] ,[CreatedBy]=SourceDBTable.[CreatedBy],[ModifedBy]=SourceDBTable.[ModifedBy] ,[ModifedDate]=SourceDBTable.[ModifedDate]
	from	ICDAS_3_0_Archive.dbo.SMSLog DestinationDBTable,
			(
				select	max(TableName) as TableName,[SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
				from
					(
						select	'SourceTableName' as TableName,[SMSLogId],SourceTableName.[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
						from SMSLog(NOLOCK) SourceTableName where SourceTableName.EquipmentMasterId is null
											
						
						union all
						
						select	'DestinationiTableName' as TableName,[SMSLogId],DestinationTableName.[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
						from ICDAS_3_0_Archive.dbo.SMSLog(NOLOCK) DestinationTableName where DestinationTableName.EquipmentMasterId is null
					) AliasName
					
					group by [SMSLogId],[EquipmentMasterId],[SMSDateTime],[MobileUserName],[MobileNo],[SMSMessage],[SMSStatus],[SMSErrorDesc],[CreateDate] ,[CreatedBy],[ModifedBy] ,[ModifedDate]
					having	count(*) = 1 and max(TableName) = 'SourceTableName'
			) SourceDBTable 
	where DestinationDBTable.SMSLogId = SourceDBTable.SMSLogId 	
--Delete Record	
		
		Delete From SMSLog Where SMSDateTime<=@LogDateTime AND EquipmentMasterId in (Select EquipmentMasterId from EquipmentMaster as EM Where EM.BranchId=@BranchId )

		Delete From SMSLog Where EquipmentMasterId is NULL and SMSDateTime<=@LogDateTime
	End
Set nocount off;
GO
/****** Object:  StoredProcedure [dbo].[UserGroup_Sync]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--[UserGroup_Sync] 3
CREATE PROCEDURE [dbo].[UserGroup_Sync]

AS
	Set nocount on
	Begin
--Insert Record
		
		insert into	ICDAS_3_0_Archive.dbo.App_UserGroup
			([UserGroupName],[UserGroupDetails])
		
		select
			
			SourceDBTable.[UserGroupName],SourceDBTable.[UserGroupDetails] 
			from App_UserGroup SourceDBTable

		where not exists (select	1 from	ICDAS_3_0_Archive.dbo.App_UserGroup DestinationDBTable
						 where DestinationDBTable.UserGroupId = SourceDBTable.UserGroupId)
			
--Update Record			
			
	update  ICDAS_3_0_Archive.dbo.App_UserGroup 

	set    [UserGroupName]=SourceDBTable.[UserGroupName]
		   ,[UserGroupDetails]=SourceDBTable.[UserGroupDetails]
	
	from	ICDAS_3_0_Archive.dbo.App_UserGroup DestinationDBTable,
			(
				
				select	max(TableName) as TableName,[UserGroupName],[UserGroupDetails]
				
				from
					(
						select	'SourceTableName' as TableName, [UserGroupName],[UserGroupDetails]
						from UserGroup SourceTableName
						
						union all
						
						select	'DestinationiTableName' as TableName, [UserGroupName],[UserGroupDetails]
						from ICDAS_3_0_Archive.dbo.App_UserGroup DestinationTableName
					) AliasName
					
					group by [UserGroupName],[UserGroupDetails]

					having	count(*) = 1 and max(TableName) = 'SourceTableName'

			) SourceDBTable

	where DestinationDBTable.UserGroupId = SourceDBTable.UserGroupId
			
	End
Set nocount off;


GO
/****** Object:  StoredProcedure [dbo].[UserGroupAccess_ListData]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[UserGroupAccess_ListData] 16
CREATE PROCEDURE [dbo].[UserGroupAccess_ListData]   
 @UserGroupId as BIGINT =0
 AS  
Set nocount on;  
BEGIN    

	Declare @UserGroup as nvarchar(100)
	
	Select @UserGroup = UserGroupName From App_UserGroup Where UserGroupId=@UserGroupId

	SELECT PRM.MenuCode,@UserGroup as UserGroupName,@UserGroupId as UserGroupId,
		isnull(PRM.MenuGroup,PRM.MenuCode) AS MenuGroup, PRM.MenuLevel,  MenuLevelType, 
		(CASE WHEN PRM.MenuLevel = 1 THEN '<b>' + PRM.Menuname + '</b>' 
		 When PRM.MenuLevel = 2 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname 
		 When PRM.MenuLevel = 3 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 When PRM.MenuLevel = 4 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 When PRM.MenuLevel = 5 THEN '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + PRM.Menuname
		 End) as MenuName,
		 PRM.MenuSno as SrNo,PRM.MenuType,'N' as Modifed, 
		(Case When MenuLevelType= 'C' Then  Isnull(UAG.AccessId, 0)  Else 0 End) as AccessId,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.ViewAccess, 0) Else 0 End) as ViewAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.AddAccess, 0) Else 0 End) as AddAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.EditAccess, 0) Else 0 End) as EditAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.DeleteAccess, 0) Else 0 End) as DeleteAccess,  
		(Case When MenuLevelType= 'C' Then Isnull(UAG.PrintAccess, 0) Else 0 End) as PrintAccess  
	FROM App_ProjectMenu(NoLock) PRM 
	Left Outer Join App_UserGroupAccess(NoLock) UAG on UAG.MenuCode= PRM.MenuCode And UAG.UserGroupId=@UserGroupId
	WHERE PRM.MenuLock = 0 
	ORDER BY CAST('/' + MenuSno + '/' AS hierarchyid),MenuLevel    
END  
GO
/****** Object:  StoredProcedure [dbo].[UserMaster_LoginValidation]    Script Date: 21-01-2020 16:35:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from App_Users
--UserMaster_LoginValidation 'o14WS%2b2gU34%3d','Hjk7MG8jsvI%2bYYERNoGx6A%3d%3d','',0
--UserMaster_LoginValidation 'o14WS%2b2gU34%3d','Hjk7MG8jsvI%2bYYERNoGx6A%3d%3d','',0
--EXEC [UserMaster_LoginValidation] 'admin','anRglfnSt5s=',0,''
CREATE PROCEDURE [dbo].[UserMaster_LoginValidation]
	@txtValidateLoginName as nvarchar(50)='',
	@txtLoginPassword as nvarchar(100)='',
	@ReturnMessage as varchar(255)='' OUTPUT,
	@ReturnId as BIGINT=0 OUTPUT
AS
SET nocount on;
BEGIN
	set @ReturnId=0
	Select @ReturnId=UserId from App_Users(NOLOCK) Where LoginName=@txtValidateLoginName AND LoginPassword=@txtLoginPassword and RecordStatus=0
	if @ReturnId > 0
		BEGIN
			
			Set @ReturnMessage ='USER LOGGED IN SUCCESSFULLY !!!'
		END
	ELSE
		BEGIN 
		
			Set @ReturnMessage ='INVALID PASSWORD !!!'
		END
END
Set nocount off;

GO
